Restoring from a Samba-based Time Machine backup (kinda)

Panicking about not being about to find or mount your Samba share you’ve been blissfully backing up to over your network?  Trying to restore to a new hard drive using the Leopard boot DVD?

I recently had the pleasure of a hard disk crash on my MacBook, and only a month earlier had started backing up to a Samba-share via Time Machine.  I had the “how to restore” question nagging in the back of my head when I set it all up but I figured someone had it figured out, otherwise why would so many articles exist to show you how to set it up?

I’ve been trying to find out how people using the TMShowUnsupportedNetworkVolumes hack to use Time Machine on smbfs shares have been restoring and it would seem that the answer is “they aren’t”.  That, or they’re simply using it as an “oops” fixer, restoring a file here and there.

When booting from the Leopard DVD, firing up the terminal and attempting to mount the share, the following delightful message shows up:

mount_smbfs --> mount_smbfs: failed to load the smb library: Unknown error: 1102

Searching for that was even more disappointing.  Other people running into the issue, no solutions.  It seems smb support is just not available on the boot DVD.

I ran into a possible solution, copy the Time Machine sparse bundle onto a removable hard disk, and hook it up to the laptop. Unfortunately all my external storage is formatted ReisferFS or ext3, neither are supported filesystems, and I didn’t feel like changing one just to fix this.

So in comes the hack.  Luckily the Samba share is on an Ubuntu 9.04 (Jaunty) server, so adding support for something Apple does support on the boot DVD is tragically easy. This is a fairly specific solution, but variations on it will work for many different servers.

Enter AFP

Looking through the other available mount applications, we also have mount_afp available.  This mounts Apple Filing Protocol-based shares, and it works too, bonus!

So it boils down to enabling AFP on the server and sharing the same volume via AFP.  AFP on Linux (BSD, etc) is supplied by netatalk, and here’s a step-by-step of how I wrapped it all up.

On the server:

  • sudo aptitude install netatalk
  • Edit /etc/netatalk/AppleVolumes.default
  • Add entry for the volume, such as:
    • /mnt/time_machine "tmachine"
  • Save the file
  • sudo /etc/init.d/netatalk restart

On the Mac:

  • Boot from the Leopard install DVD
  • Enable Airport (if on WiFi), join your network
  • From the menu bar, select Utilities -> Terminal
  • Navigate to /Volumes
  • Create a new mount point for the Time Machine volume
    • mkdir /Volumes/tmachine
  • Mount the AFP share on the new point (details)
    • mount -t afp afp://username:password@server.hostname/tmachine /Volumes/tmachine
  • Quit Terminal
  • Back at the main menu bar, select Utilities -> Restore System From Backup…
  • You should see your Time Machine backup volume listed
  • Select it, and select the date from which you wish to restore
  • Wait a considerable amount of time for it to determine the space needed
  • Enjoy the hours and hours of restore time!

Aftermath

The basic AFP installation added to the server is likely pretty insecure, I purged it as soon as the restore completed.  Read this for a more formal treatment on setting up an AFP server on Linux.  It is likely that the real solution is to stop suggesting people use Samba as a file server for Time Machine backups, instead switching to AFP altogether.

Time to broadcast, iPhone style

Ran into a need to dynamically determine the current UDP broadcast address for the WiFi interface on the ole’ iPhone. Since NSHost appears to be a private API even w/the 3.0 software, it seems one must go lower. I wrapped it up in a neat little bundle that seems fairly usable if not verbose and full of magic (but understandable) numbers.

A few things of note. en0 is the WiFi interface. There are others. Instrument the following code w/some debug to get them all out. The ip/netmask methods return nil when the WiFi interface is not active. I would also be shocked if there were no corner cases I am ignoring…

#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <errno.h>
#include <ifaddrs.h>
#include <stdio.h>
 
static NSString *kWifiInterface = @"en0";
 
@implementation NetUtil
 
+ (NSString *)broadcastAddressForAddress:(NSString *)ipAddress withMask:(NSString *)netmask {
    NSAssert(nil != ipAddress, @"IP address cannot be nil");
    NSAssert(nil != netmask, @"Netmask cannot be nil");
    NSArray *ipChunks = [ipAddress componentsSeparatedByString:@"."];
    NSAssert([ipChunks count] == 4, @"IP does not have 4 octets!");
    NSArray *nmChunks = [netmask componentsSeparatedByString:@"."];
    NSAssert([nmChunks count] == 4, @"Netmask does not have 4 octets!");
 
    NSUInteger ipRaw = 0;
    NSUInteger nmRaw = 0;
    NSUInteger shift = 24;
    for (NSUInteger i = 0; i < 4; ++i, shift -= 8) {
        ipRaw |= [[ipChunks objectAtIndex:i] intValue] << shift;
        nmRaw |= [[nmChunks objectAtIndex:i] intValue] << shift;
    }
 
    NSUInteger bcRaw = ~nmRaw | ipRaw;
    return [NSString stringWithFormat:@"%d.%d.%d.%d", (bcRaw & 0xFF000000) >> 24,
            (bcRaw & 0x00FF0000) >> 16, (bcRaw & 0x0000FF00) >> 8, bcRaw & 0x000000FF];
}
 
+ (NSString *)ipAddressForInterface:(NSString *)ifName {
    NSAssert(nil != ifName, @"Interface name cannot be nil");
 
    struct ifaddrs *addrs = NULL;
    if (getifaddrs(&addrs)) {
        NSLog(@"Failed to enumerate interfaces: %@", [NSString stringWithCString:strerror(errno)]);
        return nil;
    }
 
    /* walk the linked-list of interfaces until we find the desired one */
    NSString *addr = nil;
    struct ifaddrs *curAddr = addrs;
    while (curAddr != NULL) {
        if (AF_INET == curAddr->ifa_addr->sa_family) {
            NSString *curName = [NSString stringWithCString:curAddr->ifa_name];
            if ([ifName isEqualToString:curName]) {
                char* cstring = inet_ntoa(((struct sockaddr_in *)curAddr->ifa_addr)->sin_addr);
                addr = [NSString stringWithCString:cstring];
                break;
            }
        }
        curAddr = curAddr->ifa_next;
    }
 
    /* clean up, return what we found */
    freeifaddrs(addrs);
    return addr;
}
 
+ (NSString *)ipAddressForWifi {
    return [NetUtil ipAddressForInterface:kWifiInterface];
}
 
+ (NSString *)netmaskForInterface:(NSString *)ifName {
    NSAssert(nil != ifName, @"Interface name cannot be nil");
 
    struct ifreq ifr;
    strncpy(ifr.ifr_name, [ifName UTF8String], IFNAMSIZ-1);
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == fd) {
        NSLog(@"Failed to open socket to get netmask");
        return nil;
    }
 
    if (-1 == ioctl(fd, SIOCGIFNETMASK, &ifr)) {
        NSLog(@"Failed to read netmask: %@", [NSString stringWithCString:strerror(errno)]);
        close(fd);
        return nil;
    }
 
    close(fd);
    char *cstring = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
    return [NSString stringWithCString:cstring];
}
 
+ (NSString *)netmaskForWifi {
    return [NetUtil netmaskForInterface:kWifiInterface];
}
 
@end

NSURLConnection + startImmediately:NO == boom?

Having issues creating NSURLConnections using initWithRequest:delegate:startImmediately?

NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:url]
                                                     delegate:self
                                             startImmediately:NO];

Apparently when not using the simpler initWithRequest:delegate:, or even startImmediately:YES, the connection does not get scheduled in the current run loop. And again apparently, this causes unhappiness to occur when you eventually get around to calling start.

Simple fix, just stuff it in the current run loop before calling start and everyone gets along just fine.

[c scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[c start];

If there is something I am doing wrong or something I can do to prevent this, I’d like to know. Alas, the API is fairly brief on NSURLConnection, I don’t think I’m missing anything. This seems consistent with Cocoa, Cocoa Touch.

Some Airsoft Turret play

Been toying with the idea of making an Airsoft Gun controller wirelessly via Wii Remote.  Inspired by a previous DefconBots challenge.  Just managed to get control of 2 servos via a ATMega8, serial link to a PC and a Wii Remote talking to said PC via BlueTooth.  Pretty hacky but it works, and it’s way easier than grokking BlueTooth on the MCU for now.

First video is of 1 servo working with really jittery input.

Second video is 2 servos on X and Y axis with smoothed input.  Much nicer.

Using libwiimote on the host side for Wii Remote interfacing.

Python SubWCRev

Fired out a little Python script for exercise…

pysubwcrev is a Python version of TortoiseSVN’s SubWCRev app. SubWCRev is a windows-only console app, pysubwcrev is a command-line argument compatible replacement that is Python-based, and therefore runs on any platform with an available Python interpreter and pysvn. Currently only Linux is tested.

The code is hosted @ Google Code. Currently no packaged release exists but it is (should be?) feature complete in svn.

Note: This is just a hack at playing w/Python, jabs and criticism w/the style can come in the form of patches.

Mr. Baybus 3 Preview

Yet another digital baybus.  The original Mr. Baybus, then Mr. Baybus 2, and now this one with PC control and a graphical LCD!

Currently only a few shots of some basic functionality, nothing concrete to announce or deliver unfortunately.

Screen Images

Splash screen

Splash screen

Fans

Fans

Lights

Lights

Temperatures

Temperatures

Application Screenshots

Main Menu

Fan Controls

Lighting Controls

Temperatures

Conditional Jumping in PIC16 Assembly

PIC Microcontrollers have a funky way of handling conditionals. I’d like to present a set of macros I’ve made to make this easier to use, as well as explain the basics behind the technique in general.

Most MCU’s I’ve worked with before PICs had nice simple conditional statements… The mnemonic was usually to the effect of “branch if x to destination”. Not so on the PICs.

On a PIC, we have to do an operation between the data to test, then either skip the next instruction or not, based on the results of this test.

Take the instruction “BTFSS” meaning “Bit-test F, Skip if Set”. This instruction takes a register and a bit number, and will jump over the next instruction if that bit number in the register is set. For example:

We have 2 registers, REG1 and REG2. We want to know if the value in REG1 equals the value in REG2. A quick, simple way to do this is first to load one into W, then subtract the other from it, with the result going in to W as not to destroy one of the variables. This sets the “ZERO” bit in the STATUS register to either 1 if the operation resulted in a 0, or 0 otherwise. We know if the operation resulted in 0 the two values are equal, so we can code like so:

TESTIFZERO
  movf REG1, w
  subwf REG2, w
  btfss STATUS, Z
    goto NOTEQUAL
EQUAL
  ; they were equal
  goto DONETESTING
NOTEQUAL
  ; they weren't equal

So we can test for equality.

We can also macro-ize it for ease of use…

BEQ macro REG1, REG2, DEST	; branch if REG1 == REG2
  movf REG2, W			; W &lt;- REG2
  subwf REG1, W			; W &lt;- REG1 - REG2
  btfsc STATUS, Z		; if result was nonzero: skip out
    goto DEST			; otherwise jump
  endm

This gives us a macro we can call with 2 registers and a destination, and have it jump there if the condition ends up being true, and just pass on through if it’s not true. Much, much easier to use.

The other tests: inequality, less than, greater than, less than or equal to, greater than or equal to and so on follow a similar pattern. They are all covered in the “conditionals.inc” file I use quite often. I have both register-register comparisons and register-literal comparisons in there. Feel free to grab a copy and use it in your next project.

Downloads