3 # Proof-of-concept/reference decoder for LBS-format backup snapshots.
5 # This decoder aims to decompress an LBS snapshot. It is not meant to be
6 # particularly efficient, but should be a small and portable tool for doing so
7 # (important for recovering from data loss). It is also meant to serve as a
8 # check on the snapshot tool and data format itself, and serve as documentation
11 # This decoder does not understand TAR archives; it assumes that all segments
12 # in the snapshot have already been decompressed, and that objects are
13 # available simply as files in the filesystem. This simplifies the design.
15 # Limitations: Since this code is probably using 32-bit arithmetic, files
16 # larger than 2-4 GB may not be properly handled.
18 # Copyright (C) 2007 Michael Vrable
24 my $OBJECT_DIR; # Where are the unpacked objects available?
25 my $DEST_DIR = "."; # Where should restored files should be placed?
26 my $RECURSION_LIMIT = 3; # Bound on recursive object references
28 my $VERBOSE = 0; # Set to 1 to enable debugging messages
30 ############################ CHECKSUM VERIFICATION ############################
31 # A very simple layer for verifying checksums. Checksums may be used on object
32 # references directly, and can also be used to verify entire reconstructed
35 # A checksum to verify is given in the form "algorithm=hexdigest". Given such
36 # a string, we can construct a "verifier" object. Bytes can be incrementally
37 # added to the verifier, and at the end a test can be made to see if the
38 # checksum matches. The caller need not know what algorithm is used. However,
39 # at the moment we only support SHA-1 for computing digest (algorith name
44 if ($checksum !~ m/^(\w+)=([0-9a-f]+)$/) {
45 die "Malformed checksum: $checksum";
47 my ($algorithm, $hash) = ($1, $2);
48 if ($algorithm ne 'sha1') {
49 die "Unsupported checksum algorithm: $algorithm";
53 ALGORITHM => $algorithm,
55 DIGESTER => new Digest::SHA1
61 sub verifier_add_bytes {
63 my $digester = $verifier->{DIGESTER};
66 $digester->add($data);
71 my $digester = $verifier->{DIGESTER};
73 my $newhash = $digester->hexdigest();
74 if ($VERBOSE && $verifier->{HASH} ne $newhash) {
75 print STDERR "Verification failure: ",
76 $newhash, " != ", $verifier->{HASH}, "\n";
78 return ($verifier->{HASH} eq $newhash);
81 ################################ OBJECT ACCESS ################################
82 # The base of the decompressor is the object reference layer. See ref.h for a
83 # description of the format for object references. These functions will parse
84 # an object reference, locate the object data from the filesystem, perform any
85 # necessary integrity checks (if a checksum is included), and return the object
88 # First, try to parse the object reference string into constituent pieces.
89 # The format is segment/object(checksum)[range]. Both the checksum and
93 if ($ref_str !~ m/^([-0-9a-f]+)\/([0-9a-f]+)(\(\S+\))?(\[\S+\])?$/) {
94 die "Malformed object reference: $ref_str";
97 my ($segment, $object, $checksum, $range) = ($1, $2, $3, $4);
99 # Next, use the segment/object components to locate and read the object
100 # contents from disk.
101 open OBJECT, "<", "$OBJECT_DIR/$segment/$object"
102 or die "Unable to open object $OBJECT_DIR/$segment/$object: $!";
103 my $contents = join '', <OBJECT>;
106 # If a checksum was specified in the object reference, verify the object
107 # integrity by computing a checksum of the read data and comparing.
109 $checksum =~ m/^\((\S+)\)$/;
110 my $verifier = verifier_create($1);
111 verifier_add_bytes($verifier, $contents);
112 if (!verifier_check($verifier)) {
113 die "Integrity check for object $ref_str failed";
117 # If a range was specified, then only a subset of the bytes of the object
118 # are desired. Extract just the desired bytes.
120 if ($range !~ m/^\[(\d+)\+(\d+)\]$/) {
121 die "Malformed object range: $range";
124 my $object_size = length $contents;
125 my ($start, $length) = ($1 + 0, $2 + 0);
126 if ($start >= $object_size || $start + $length > $object_size) {
127 die "Object range $range falls outside object bounds "
128 . "(actual size $object_size)";
131 $contents = substr $contents, $start, $length;
137 ############################### FILE PROCESSING ###############################
138 # Process the metadata for a single file. process_file is the main entry
139 # point; it should be given a list of file metadata key/value pairs.
140 # iterate_objects is a helper function used to iterate over the set of object
141 # references that contain the file data for a regular file.
145 $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
149 sub iterate_objects {
150 my $callback = shift; # Function to be called for each reference
151 my $arg = shift; # Argument passed to callback
152 my $text = shift; # Whitespace-separate list of object references
154 # Simple limit to guard against cycles in the object references
155 my $recursion_level = shift || 0;
156 if ($recursion_level >= $RECURSION_LIMIT) {
157 die "Recursion limit reached";
160 # Split the provided text at whitespace boundaries to produce the list of
161 # object references. If any of these start with "@", then we have an
162 # indirect reference, and must look up that object and call iterate_objects
165 foreach $obj (split /\s+/, $text) {
167 if ($obj =~ /^@(\S+)$/) {
168 my $indirect = load_ref($1);
169 iterate_objects($callback, $arg, $indirect, $recursion_level + 1);
171 &$callback($arg, $obj);
179 my $data = load_ref($obj);
181 or die "Error writing file data: $!";
182 verifier_add_bytes($state->{VERIFIER}, $data);
183 $state->{BYTES} += length($data);
186 # Extract the contents of a regular file by concatenating all the objects that
193 if (!defined $info{data}) {
194 die "File contents not specified for $name";
196 if (!defined $info{checksum} || !defined $info{size}) {
197 die "File $name is missing checksum or size";
200 # Open the file to be recreated. The data will be written out by the call
201 # to iterate_objects.
202 open FILE, ">", "$DEST_DIR/$name"
203 or die "Cannot write file $name: $!";
205 # Set up state so that we can incrementally compute the checksum and length
206 # of the reconstructed data. Then iterate over all objects in the file.
207 $state{VERIFIER} = verifier_create($info{checksum});
209 iterate_objects(\&obj_callback, \%state, $info{data});
213 # Verify that the reconstructed object matches the size/checksum we were
215 if (!verifier_check($state{VERIFIER}) || $state{BYTES} != $info{size}) {
216 die "File reconstruction failed for $name: size or checksum differs";
223 if (!defined($info{name})) {
224 die "Filename not specified in metadata block";
227 my $type = $info{type};
229 my $filename = uri_decode($info{name});
230 print "$filename\n" if $VERBOSE;
232 # Restore the specified file. How to do so depends upon the file type, so
233 # dispatch based on that.
234 my $dest = "$DEST_DIR/$filename";
237 unpack_file($filename, %info);
238 } elsif ($type eq 'd') {
240 if ($filename ne '.') {
241 mkdir $dest or die "Cannot create directory $filename: $!";
243 } elsif ($type eq 'l') {
245 if (!defined($info{contents})) {
246 die "Symlink $filename has no value specified";
248 my $contents = uri_decode($info{contents});
249 symlink $contents, $dest
250 or die "Cannot create symlink $filename: $!";
252 # TODO: We can't properly restore all metadata for symbolic links
253 # (attempts to do so below will change metadata for the pointed-to
254 # file). This should be later fixed, but for now we simply return
255 # before getting to the restore metadata step below.
257 } elsif ($type eq 'p' || $type eq 's' || $type eq 'c' || $type eq 'b') {
258 # Pipe, socket, character device, block device.
259 # TODO: Handle these cases.
260 print STDERR "Ignoring special file $filename of type $type\n";
263 die "Unknown file type '$type' for file $filename";
266 # Restore mode, ownership, and any other metadata for the file. This is
267 # split out from the code above since the code is the same regardless of
269 my $mtime = $info{mtime} || time();
270 utime time(), $mtime, $dest
271 or warn "Unable to update mtime for $dest";
275 if (defined $info{user}) {
276 my @items = split /\s/, $info{user};
277 $uid = $items[0] + 0 if exists $items[0];
279 if (defined $info{group}) {
280 my @items = split /\s/, $info{group};
281 $gid = $items[0] + 0 if exists $items[0];
283 chown $uid, $gid, $dest
284 or warn "Unable to change ownership for $dest";
286 if (defined $info{mode}) {
287 my $mode = $info{mode};
289 or warn "Unable to change permissions for $dest";
293 ########################### METADATA LIST PROCESSING ##########################
294 # Process the file metadata listing provided, and as information for each file
295 # is extracted, pass it to process_file. This will recursively follow indirect
296 # references to other metadata objects.
297 sub process_metadata {
298 my ($metadata, $recursion_level) = @_;
300 # Check recursion; this will prevent us from infinitely recursing on an
301 # indirect reference which loops back to itself.
302 $recursion_level ||= 0;
303 if ($recursion_level >= $RECURSION_LIMIT) {
304 die "Recursion limit reached";
307 # Split the metadata into lines, then start processing each line. There
308 # are two primary cases:
309 # - Lines starting with "@" are indirect references to other metadata
310 # objects. Recursively process that object before continuing.
311 # - Other lines should come in groups separated by a blank line; these
312 # contain metadata for a single file that should be passed to
314 # Note that blocks of metadata about a file cannot span a boundary between
319 foreach $line (split /\n/, $metadata) {
320 # If we find a blank line or a reference to another block, process any
321 # data for the previous file first.
322 if ($line eq '' || $line =~ m/^@/) {
323 process_file(%info) if %info;
329 # Recursively handle indirect metadata blocks.
330 if ($line =~ m/^@(\S+)$/) {
331 print "Indirect: $1\n" if $VERBOSE;
332 my $indirect = load_ref($1);
333 process_metadata($indirect, $recursion_level + 1);
337 # Try to parse the data as "key: value" pairs of file metadata. Also
338 # handle continuation lines, which start with whitespace and continue
339 # the previous "key: value" pair.
340 if ($line =~ m/^(\w+):\s*(.*)$/) {
343 } elsif ($line =~/^\s/ && defined $last_key) {
344 $info{$last_key} .= $line;
346 print STDERR "Junk in file metadata section: $line\n";
350 # Process any last file metadata which has not already been processed.
351 process_file(%info) if %info;
354 ############################### MAIN ENTRY POINT ##############################
355 # Program start. We expect to be called with a single argument, which is the
356 # name of the backup descriptor file written by a backup pass. This will name
357 # the root object in the snapshot, from which we can reach all other data we
360 # Parse command-line arguments. The first (required) is the name of the
361 # snapshot descriptor file. The backup objects are assumed to be stored in the
362 # same directory as the descriptor. The second (optional) argument is the
363 # directory where the restored files should be written; it defaults to ".";
364 my $descriptor = $ARGV[0];
365 unless (defined($descriptor) && -r $descriptor) {
366 print STDERR "Usage: $0 <snapshot file>\n";
370 if (defined($ARGV[1])) {
371 $DEST_DIR = $ARGV[1];
374 $OBJECT_DIR = dirname($descriptor);
375 print "Source directory: $OBJECT_DIR\n" if $VERBOSE;
377 # Read the snapshot descriptor to find the root object. Parse it to get a set
378 # of key/value pairs.
379 open DESCRIPTOR, "<", $descriptor
380 or die "Cannot open backup descriptor file $descriptor: $!";
382 my ($line, $last_key);
383 while (defined($line = <DESCRIPTOR>)) {
384 # Any lines of the form "key: value" should be inserted into the
385 # %descriptor dictionary. Any continuation line (a line starting with
386 # whitespace) will append text to the previous key's value. Ignore other
390 if ($line =~ m/^(\w+):\s*(.*)$/) {
391 $descriptor{$1} = $2;
393 } elsif ($line =~/^\s/ && defined $last_key) {
394 $descriptor{$last_key} .= $line;
397 print STDERR "Ignoring line in backup descriptor: $line\n";
401 # A valid backup descriptor should at the very least specify the root metadata
403 if (!exists $descriptor{Root}) {
404 die "Expected 'Root:' specification in backup descriptor file";
406 my $root = $descriptor{Root};
409 # Set the umask to something restrictive. As we unpack files, we'll originally
410 # write the files/directories without setting the permissions, so be
411 # conservative and ensure that they can't be read. Afterwards, we'll properly
412 # fix up permissions.
415 # Start processing metadata stored in the root to recreate the files.
416 print "Root object: $root\n" if $VERBOSE;
417 my $contents = load_ref($root);
418 process_metadata($contents);