Belkin N1 Vision router freezes and restarts

Recently I bought Belkin N1 Vision router and ADSL modem for home (exact number is F5D8632-4 v1000). To replace my previous Netgear’s DG834PN, which worked just fine except 2 flaws – its range was limited and it didn’t cover all the house. Besides it couldn’t handle more than 5-6 wireless clients for some reason. N1 on other side, closes this issues but now I have much worse problem – it freezes and restarts every 2 hours or even more often.

Many people blame the NTP service, which indeed updates router’s time every 2 hours and it is not possible to disable it. There was no custom firmware and not official firmware that really fixed this problem. The one on Belkin’s site, claims that it was fixed, when in fact it was not – even after updating to 1.00.09, router behaved the same. So I had no choice but try to find the way to disable NTP by myself. I also couldn’t return it to seller, because it was stuck at customs for a long time and I got it about 2 months after I bought it.

Thankfully, the firmware is open source and even I have no clue in Linux development, I just had to try it. So I used my dual boot Ubuntu, downloaded the firmware and searched brutally for NTP in the source code. I found 2 reference in startup and setup scripts – commented them out, compiled and uploaded firmware to router. Then actually verified that the NTP daemon was not started on startup. Yet, something was starting it. Since I’m not familiar with Linux enough, I had no idea what else could start it, so I thought – why shouldn’t I simply delete the “ntp” file from image? I was a bit worry, since was not sure if router could work without this service or not, but anyway – I either fix it or throw it to trash can. Guess what? It worked!

So here we go, a working firmware image which has ntp service removed for good. I tested it on my router – indeed it stopped restarting and freezes, so hopefully it will work for everyone. If someone needs the altered sources, just ask, I will be happy to provide them. I have to admit, I still have problems from time to time – but they can be eliminated by finding a good channel, not sure how it is connected. For example, on channel 13, I had router restarted every 20 minutes or even less. When I switched to channel 7, it restarts only when one of the wifi clients starts downloading something huge (it gets disconnected after about 400 MB of downloaded data).

Links:

In case your router is broken, here are some manuals how to unbrick them. I recommend trying from Linux, not from Windows.

Reinstalling Google Music Manager on new computer

Reinstalled Windows and Google Music Manager and now it tries to upload all your songs again? Rather just synchronizing with cloud? Here how I solved this problem.

First, you will need your previous computer storage. I always do a full backup to external drive before I wipe OS. So here what needs to be done:

1. Install Google Music Manager. Close the wizard that starts right after installation and close the application (make sure it is not running in System Tray).

2. Go to your backup and find the file “ServerDatabase.db” in folder “C:\users\YOUR USERNAME\AppData\Local\Google\MusicManager”. Again, this is on your OLD computer backup!

3. Copy the file to the same path, but on your new OS.

4. Start Music Manager and complete its wizard. Note, it will say “XXXX files will be uploaded”. Just ignore it and let it configure itself.

5. Close and start Music Manager again and go to options to verify that it says “XXXX songs uploaded”, similar to the screenshot below and your are done:

image_thumb1

Technorati Tags: ,

Writing to EventLog from MSI custom action

I had a task to write to event log from within MSI custom action (WiX in my case, but that doesn’t matter) and the logging should be with the same source as MSI itself is using – e.g. “MsiInstaller”. I couldn’t find a proper way to do this and ended up writing to log myself, without using any of MSI API methods.

I took the logging method from ATL with small modifications. Here it is:

#pragma warning(push)
#pragma warning(disable : 4793)
    void __cdecl WriteToEventLog(WORD eventLogType, DWORD eventId, LPCTSTR sourceName, LPCTSTR pszFormat, ...) throw()
    {
        const int LOG_EVENT_MSG_SIZE = 256;
        
        TCHAR chMsg[LOG_EVENT_MSG_SIZE];
        HANDLE hEventSource;
        LPTSTR lpszStrings[1];
        va_list pArg;
        
        va_start(pArg, pszFormat);
        _vsntprintf_s(chMsg, LOG_EVENT_MSG_SIZE, LOG_EVENT_MSG_SIZE-1, pszFormat, pArg);
        va_end(pArg);
 
        chMsg[LOG_EVENT_MSG_SIZE - 1] = 0;
        
        lpszStrings[0] = chMsg;
 
        /* Get a handle to use with ReportEvent(). */
        hEventSource = RegisterEventSource(NULL, sourceName);
        if (hEventSource != NULL)
        {
            /* Write to event log. */
            ReportEvent(hEventSource, eventLogType, 0, eventId, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
            DeregisterEventSource(hEventSource);
        }
    }
#pragma warning(pop)

But the key is usage of this method. Source name should be “MsiInstaller” and Event ID is 1013. This event ID is used by MSI for unhandled exception logging, to simply write text without any additional information, to event log. Here is a sample usage:

 
 
WriteToEventLog(EVENTLOG_ERROR_TYPE, 1013, _T("MsiInstaller"), _T("Oh my God! I got error! Number is %d"), 5);
 
 
 

Шпрехен зи руссиш?

 
Шпрехен зи руссиш?
Шпрехен зи руссиш?Тест на знание заимствованных слов, имён собственных и других хитростей русского языка. Такой небольшой «диктант» , позволяющий проверить вашу грамотность.
Филипп Патрик прошел этот тест с результатом:
Вы допустили 1 ошибку. Считайте, что вы знаете русский язык практически идеально!
Пройти тест "Шпрехен зи руссиш?"
Все познавательные тесты на ШколаЖизни.ру

Question about Ubuntu 64-bit support

Recently I have installed Linux Ubuntu on my mom’s computer, replacing the old Windows XP. Seems enough for googling and mailing that she is doing. BTW, it works just fine after few small tweaks, like getting rid of too-fresh Unity interface and disabling awful overlay scrollbars (that appear only when you mouse over the edge of a window). Anyway, in the process, I had to read some information about Ubuntu and one of the questions was – whether to install 32-bit or 64-bit one. Jumping to the end – I installed 32-bit, to exclude any possibility of applications/drivers incompatibility (search it and you will see many problems with 64-bit Linux installations, old ones and new ones). In the process, I came to the Wiki page, explaining the difference. The thing that I did not understand is the strange claim “As Ubuntu is entirely open source, […] all hardware supported by Ubuntu works equally well in 32-bit and 64-bit environments”. Please someone explain me how the “open source” is connected to ability to “work well” in 64-bit system? For those who do not believe (and I wouldn’t myself if I heard that), here is a screenshot:

image

Technorati Tags: ,,

Refactoring succeeded! :)

I feel like refactoring worked just fine Smile

image

Using Amahi: Installing Subversion and Migrating Repositories

Since all my code is stored in Subversion, which is currently installed on Windows Home Server, I had to check how to install a Subversion server on Amahi server and how to migrate all my repositories there. The installation is pretty straight forward, everything is done form command line.

1. Install subversion:
yum install subversion

2. For some reason SQLite was outdated for me, so verify that you have the latest version:
yum update sqlite

3. Create a root folder for all your repositories. It can be any name and any location. I choose to add a root folder named "svnrepos":
mkdir /svnrepos

4. Now create a repository. I called it "main":
svnadmin create /svnrepos/main

5. (Optional). Importing from old repository

a. First, create a dump file with all data from your old repository:
svnadmin dump /path_to_old_repository > outfile.dump
Note, that "path_to_old_repository" is physical path, not a URL. You should execute  the command on the server having your old subversion. The "outfile.dump" is a path and file name where to save exported repository.

b. Copy the output file somewhere on the new server

c. Import it into newly created repository, by running the following command on new server:
svnadmin load /svnrepos/main < outfile.dump
Note, that here we again need the physical path to repository, not URL.

d. Verify that all data imported successfully, by checking it in your favorite SVN client. To access from another machine, use the following syntax: svn://server/repository_path. For example:
svn://server/svnrepos/main

6. Configure security - unless you want everything to be public. I use my favorite Nano for editing in command line.

a. Enable security first:
nano /svnrepos/main/conf/svnserve.conf
Make sure to write those lines (either add them or uncomment and change):
anon-access = none
auth-access = write
password-db = passwd

b. Edit passwords file:
nano /svnrepos/main/conf/passwd
Add the user:
john = password

c. Protect the passwords file - after this command only root will have access to the file:
chmod o= /svnrepos/main/conf/passwd

7. Start svn server as daemon:
svnserver –d

Technorati Tags: ,,,

Using Amahi: Recovering from non-system disk failure

Brief overview: this is about Linux Home Server, called Amahi, which I’m trying to figure out whether it suits my needs and I can migrate to it from Windows Home Server. Currently, the server is installed in VIrtualBox.

The task: simulate an unrecoverable hard disk failure of one of non-system disks. E.g. one of the disks that contain your data and participate in mirroring, managed by Greyhole.

Environment:

  • VirtualBox with Fedora 12 and Amahi on top.
  • 3 hard disks attached to the virtual machine. One is system disk, second and third contain user data, managed by Greyhole.
  • MediaWiki installed – just to check what happens to applications.

Scenario:

  • Perform hard-reset of the system, simulating power failure
  • Remove the third disk
  • Recover the system
  • Add replacement disk

So now the story. After I shut the system down and removed the third hard disk, I started the system and got not-so-nice error during boot – system couldn’t find device and cannot continue to load. I was asked to fix the problems or reboot. Since rebooting doesn’t help, I understood that recovering will not be easy, or at least not automatic. I actually hoped that system can recognize the missing disk, warn, but continue. Remember, I‘m not talking about the disk where the system is installed, it is just one of the data disks. Because I’m not a Linux pro, more like newbie (the only Linux command I always remember is “dir”, since it appears in MSDOS as well Smile ), I had to dig and find what are the steps to recover the system and let it continue. Turns out, there is a special file which contains all devices to mount on start up and all I need is to edit it and remove the line with missing drive. Here are the steps:

1. After the system started, you will be notified about missing device and boot sequence will stop with command prompt, asking you to fix the problems:
image_thumb
Type your root password to get to console.

2. The root file system is most likely mounted as read-only, so we need to remount it, as we are going to change one of the system files. Do this by typing the following command:
mount –n –o remount /

3. Open “/etc/fstab” file for editing, with following command:
nano –Bw /etc/fstab
image_thumb1
In my case, the missing drive is shown in the last line.
-Bw switch tells Nano to create a backup copy when you save the file. Just in case.

4. Find the line with your missing drive and remove it completely. Hit Control+O to save your changes and Control-X to exit editing.
Note, if you get an error saying something like "Cannot write file, the system is read-only”, it means the previous command didn’t work, exit the editor and try it again. Don’t miss the trailing slash – this is the root file system path.

5. Hit Control+D to restart the system. It should boot properly now. At least we have a running system again, so let’s continue fixing it and adding a disk replacement.

6. Start LVM (Logical Volume Management). It can be found in System->Administration. You should see your failed disk as “unknown device” in the tree:
image_thumb2
This is not good and we need to repair it.

6. CAUTION! BE VERY CAUTIOS IN THIS STEP! YOU MAY CAUSE A LOSS OF DATA IF YOU REMOVE THE WRONG VOLUME! You’ve been warned.
First, we should remove the logical volume. In my case, the volume that is pointing to physical failed device is “lv_data1”. In your case it may be something else, figure it out and delete it, by selecting it in the tree and clicking “Remove Logical Volume”.

7. Now we need to remove the physical drive. Start console and su to root (e.g. type “su” in the command line, without quotas, then your root password"). Type the following command, which will remove missing devices from the system:
vgreduce –removemissing vg_hda
Change “vg_hda” to your volume group name, which contains the missing device.
Reload LVM (View->Reload) and you should not see any more “unknown device”s anymore. Our system is fully repaired:
image_thumb3

8. Next step, is to install a replacement disk. If you don’t have it, just stop here, as there is nothing more to do at this point.
Shutdown the system, insert your new disk and start again as usual. You can follow the guide posted on Amahi’s Wiki here, but it takes the path of command line, which I don’t really like, so if you want to do everything with UI, continue reading.

9. You will see your new drive in “Uninitialized Entities” group. Go ahead, select it and hit “Initialize Entity”:
image_thumb4

The drive will be moved to Unallocated Volumes group:
image_thumb5

Hit “Add to Existing Volume Group”, select your group and add it. Now our group has expanded with new unused space:
image_thumb6

Select “Logical View” and hit “Create New Logical Volume”. A dialog for adding new volume will appear. Fill in the details and remember to mount your new volume somewhere under “/var/hda/files”. In my case, I mount it in “/var/hda/files/drives/sdc1”:
image_thumb7
Select file system (Ext4) and check both Mount and Mount when rebooted and click OK. This may be a lengthy operation, so be patient.

10. Go to your HAD, by navigating to http://hda and add your new volume into storage pool as usual. Check the configuration of each folder’s pool and we are done.

11. Optionally, you may want to force Greyhole to resynchronize all data and copy it wherever needed by executing the following command in console:
greyhole –fsck

That’s it, we are done! And please remember, I’m a total noob in Linux, so if you find any issue in what I wrote above, feel free to post about it in comments.

Technorati Tags: ,,,

Regular Expression to extract quoted text

If you have a text enclosed with single or double quotes and optionally containing escaped quotes inside the text, the following regular expression will help you to extract the text:

(['"])(?<text>.*?)(?<!\\)\1

For example, parsing text:

'Hello world' 
'World\'s test'
"World's test"

will yield following results:

Hello world
World\’s test
World’s test

Technorati Tags:

Enumerating user privileges

We had some issues in the impersonation code and I needed to enumerate privileges of currently logged in user – before and after impersonation. Since I couldn’t find quickly such code, I wrote it myself, by compiling few pieces I found on net. Hopefully it will be useful.

static void EnumRights()
 {
     uint length = 0;
     bool res;
 
     // first call gets lenght of TokenInformation
     res = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, length, out length);
     IntPtr tokenInformation = Marshal.AllocHGlobal(unchecked((int)length));
     res = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, length, out length);
     if (res)
     {
         TOKEN_PRIVILEGES privs = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES));
         for (int i = 0; i < privs.Count; i++)
         {
             IntPtr ptr = new IntPtr(tokenInformation.ToInt64() + sizeof(uint) + i * Marshal.SizeOf(typeof(LUID_AND_ATTRIBUTES)));
             LUID_AND_ATTRIBUTES privInfo = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(ptr, typeof(LUID_AND_ATTRIBUTES));
             StringBuilder name = new StringBuilder();
             IntPtr luidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID)));
             Marshal.StructureToPtr(privInfo.Luid, luidPtr, false);
             int size = 0;
             LookupPrivilegeName(null, luidPtr, null, ref size);
             name.EnsureCapacity(size);
             LookupPrivilegeName(null, luidPtr, name, ref size);
             Marshal.FreeHGlobal(luidPtr);
 
             Console.WriteLine(name.ToString());
         }
     }
 
     Marshal.FreeHGlobal(tokenInformation);
 }
 
 
 #region Interop
 [StructLayout(LayoutKind.Sequential)]
 struct LUID
 {
     public uint LowPart;
     public int HighPart;
 }
 
 [StructLayout(LayoutKind.Sequential)]
 struct LUID_AND_ATTRIBUTES
 {
     public LUID Luid;
     public uint Attributes;
 }
 
 [StructLayout(LayoutKind.Sequential)]
 struct TOKEN_PRIVILEGES
 {
     public uint Count;
     //public IntPtr Privileges; //array of LUID_AND_ATTRIBUTES
 }
 
 [DllImport("advapi32.dll", SetLastError = true)]
 static extern bool GetTokenInformation(
     IntPtr TokenHandle,
     TOKEN_INFORMATION_CLASS TokenInformationClass,
     IntPtr TokenInformation,
     uint TokenInformationLength,
     out uint ReturnLength);
 
 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool LookupPrivilegeName(
    string lpSystemName,
    IntPtr lpLuid,
    System.Text.StringBuilder lpName,
    ref int cchName);
 
 #endregion

If you prefer to check a full testing solution (also containing a code for impersonation), you can download it here.

Technorati Tags: ,,,