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
90 # Check for special objects before attempting general parsing.
91 if ($ref_str =~ m/^zero\[((\d+)\+)?(\d+)\]$/) {
92 return "\0" x ($3 + 0);
95 # Try to parse the object reference string into constituent pieces. The
96 # format is segment/object(checksum)[range]. Both the checksum and range
98 if ($ref_str !~ m/^([-0-9a-f]+)\/([0-9a-f]+)(\(\S+\))?(\[\S+\])?$/) {
99 die "Malformed object reference: $ref_str";
102 my ($segment, $object, $checksum, $range) = ($1, $2, $3, $4);
104 # Next, use the segment/object components to locate and read the object
105 # contents from disk.
106 open OBJECT, "<", "$OBJECT_DIR/$segment/$object"
107 or die "Unable to open object $OBJECT_DIR/$segment/$object: $!";
108 my $contents = join '', <OBJECT>;
111 # If a checksum was specified in the object reference, verify the object
112 # integrity by computing a checksum of the read data and comparing.
114 $checksum =~ m/^\((\S+)\)$/;
115 my $verifier = verifier_create($1);
116 verifier_add_bytes($verifier, $contents);
117 if (!verifier_check($verifier)) {
118 die "Integrity check for object $ref_str failed";
122 # If a range was specified, then only a subset of the bytes of the object
123 # are desired. Extract just the desired bytes.
125 if ($range !~ m/^\[((\d+)\+)?(\d+)\]$/) {
126 die "Malformed object range: $range";
129 my $object_size = length $contents;
130 my ($start, $length);
132 ($start, $length) = ($2 + 0, $3 + 0);
134 ($start, $length) = (0, $3 + 0);
136 if ($start >= $object_size || $start + $length > $object_size) {
137 die "Object range $range falls outside object bounds "
138 . "(actual size $object_size)";
141 $contents = substr $contents, $start, $length;
147 ############################### FILE PROCESSING ###############################
148 # Process the metadata for a single file. process_file is the main entry
149 # point; it should be given a list of file metadata key/value pairs.
150 # iterate_objects is a helper function used to iterate over the set of object
151 # references that contain the file data for a regular file.
164 $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
168 sub iterate_objects {
169 my $callback = shift; # Function to be called for each reference
170 my $arg = shift; # Argument passed to callback
171 my $text = shift; # Whitespace-separate list of object references
173 # Simple limit to guard against cycles in the object references
174 my $recursion_level = shift || 0;
175 if ($recursion_level >= $RECURSION_LIMIT) {
176 die "Recursion limit reached";
179 # Split the provided text at whitespace boundaries to produce the list of
180 # object references. If any of these start with "@", then we have an
181 # indirect reference, and must look up that object and call iterate_objects
184 foreach $obj (split /\s+/, $text) {
186 if ($obj =~ /^@(\S+)$/) {
187 my $indirect = load_ref($1);
188 iterate_objects($callback, $arg, $indirect, $recursion_level + 1);
190 &$callback($arg, $obj);
198 my $data = load_ref($obj);
200 or die "Error writing file data: $!";
201 verifier_add_bytes($state->{VERIFIER}, $data);
202 $state->{BYTES} += length($data);
205 # Extract the contents of a regular file by concatenating all the objects that
212 if (!defined $info{data}) {
213 die "File contents not specified for $name";
215 if (!defined $info{checksum} || !defined $info{size}) {
216 die "File $name is missing checksum or size";
219 $info{size} = parse_int($info{size});
221 # Open the file to be recreated. The data will be written out by the call
222 # to iterate_objects.
223 open FILE, ">", "$DEST_DIR/$name"
224 or die "Cannot write file $name: $!";
226 # Set up state so that we can incrementally compute the checksum and length
227 # of the reconstructed data. Then iterate over all objects in the file.
228 $state{VERIFIER} = verifier_create($info{checksum});
230 iterate_objects(\&obj_callback, \%state, $info{data});
234 # Verify that the reconstructed object matches the size/checksum we were
236 if (!verifier_check($state{VERIFIER}) || $state{BYTES} != $info{size}) {
237 die "File reconstruction failed for $name: size or checksum differs";
244 if (!defined($info{name})) {
245 die "Filename not specified in metadata block";
248 my $type = $info{type};
250 my $filename = uri_decode($info{name});
251 print "$filename\n" if $VERBOSE;
253 # Restore the specified file. How to do so depends upon the file type, so
254 # dispatch based on that.
255 my $dest = "$DEST_DIR/$filename";
256 if ($type eq '-' || $type eq 'f') {
258 unpack_file($filename, %info);
259 } elsif ($type eq 'd') {
261 if ($filename ne '.') {
262 mkdir $dest or die "Cannot create directory $filename: $!";
264 } elsif ($type eq 'l') {
266 my $target = $info{target} || $info{contents};
267 if (!defined($target)) {
268 die "Symlink $filename has no value specified";
270 $target = uri_decode($target);
271 symlink $target, $dest
272 or die "Cannot create symlink $filename: $!";
274 # TODO: We can't properly restore all metadata for symbolic links
275 # (attempts to do so below will change metadata for the pointed-to
276 # file). This should be later fixed, but for now we simply return
277 # before getting to the restore metadata step below.
279 } elsif ($type eq 'p' || $type eq 's' || $type eq 'c' || $type eq 'b') {
280 # Pipe, socket, character device, block device.
281 # TODO: Handle these cases.
282 print STDERR "Ignoring special file $filename of type $type\n";
285 die "Unknown file type '$type' for file $filename";
288 # Restore mode, ownership, and any other metadata for the file. This is
289 # split out from the code above since the code is the same regardless of
291 my $mtime = $info{mtime} || time();
292 utime time(), $mtime, $dest
293 or warn "Unable to update mtime for $dest";
297 if (defined $info{user}) {
298 my @items = split /\s/, $info{user};
299 $uid = parse_int($items[0]) if exists $items[0];
301 if (defined $info{group}) {
302 my @items = split /\s/, $info{group};
303 $gid = parse_int($items[0]) if exists $items[0];
305 chown $uid, $gid, $dest
306 or warn "Unable to change ownership for $dest";
308 if (defined $info{mode}) {
309 my $mode = parse_int($info{mode});
311 or warn "Unable to change permissions for $dest";
315 ########################### METADATA LIST PROCESSING ##########################
316 # Process the file metadata listing provided, and as information for each file
317 # is extracted, pass it to process_file. This will recursively follow indirect
318 # references to other metadata objects.
319 sub process_metadata {
320 my ($metadata, $recursion_level) = @_;
322 # Check recursion; this will prevent us from infinitely recursing on an
323 # indirect reference which loops back to itself.
324 $recursion_level ||= 0;
325 if ($recursion_level >= $RECURSION_LIMIT) {
326 die "Recursion limit reached";
329 # Split the metadata into lines, then start processing each line. There
330 # are two primary cases:
331 # - Lines starting with "@" are indirect references to other metadata
332 # objects. Recursively process that object before continuing.
333 # - Other lines should come in groups separated by a blank line; these
334 # contain metadata for a single file that should be passed to
336 # Note that blocks of metadata about a file cannot span a boundary between
341 foreach $line (split /\n/, $metadata) {
342 # If we find a blank line or a reference to another block, process any
343 # data for the previous file first.
344 if ($line eq '' || $line =~ m/^@/) {
345 process_file(%info) if %info;
351 # Recursively handle indirect metadata blocks.
352 if ($line =~ m/^@(\S+)$/) {
353 print "Indirect: $1\n" if $VERBOSE;
354 my $indirect = load_ref($1);
355 process_metadata($indirect, $recursion_level + 1);
359 # Try to parse the data as "key: value" pairs of file metadata. Also
360 # handle continuation lines, which start with whitespace and continue
361 # the previous "key: value" pair.
362 if ($line =~ m/^(\w+):\s*(.*)$/) {
365 } elsif ($line =~/^\s/ && defined $last_key) {
366 $info{$last_key} .= $line;
368 print STDERR "Junk in file metadata section: $line\n";
372 # Process any last file metadata which has not already been processed.
373 process_file(%info) if %info;
376 ############################### MAIN ENTRY POINT ##############################
377 # Program start. We expect to be called with a single argument, which is the
378 # name of the backup descriptor file written by a backup pass. This will name
379 # the root object in the snapshot, from which we can reach all other data we
382 # Parse command-line arguments. The first (required) is the name of the
383 # snapshot descriptor file. The backup objects are assumed to be stored in the
384 # same directory as the descriptor. The second (optional) argument is the
385 # directory where the restored files should be written; it defaults to ".";
386 my $descriptor = $ARGV[0];
387 unless (defined($descriptor) && -r $descriptor) {
388 print STDERR "Usage: $0 <snapshot file>\n";
392 if (defined($ARGV[1])) {
393 $DEST_DIR = $ARGV[1];
396 $OBJECT_DIR = dirname($descriptor);
397 print "Source directory: $OBJECT_DIR\n" if $VERBOSE;
399 # Read the snapshot descriptor to find the root object. Parse it to get a set
400 # of key/value pairs.
401 open DESCRIPTOR, "<", $descriptor
402 or die "Cannot open backup descriptor file $descriptor: $!";
404 my ($line, $last_key);
405 while (defined($line = <DESCRIPTOR>)) {
406 # Any lines of the form "key: value" should be inserted into the
407 # %descriptor dictionary. Any continuation line (a line starting with
408 # whitespace) will append text to the previous key's value. Ignore other
412 if ($line =~ m/^(\w+):\s*(.*)$/) {
413 $descriptor{$1} = $2;
415 } elsif ($line =~/^\s/ && defined $last_key) {
416 $descriptor{$last_key} .= $line;
419 print STDERR "Ignoring line in backup descriptor: $line\n";
423 # A valid backup descriptor should at the very least specify the root metadata
425 if (!exists $descriptor{Root}) {
426 die "Expected 'Root:' specification in backup descriptor file";
428 my $root = $descriptor{Root};
431 # Set the umask to something restrictive. As we unpack files, we'll originally
432 # write the files/directories without setting the permissions, so be
433 # conservative and ensure that they can't be read. Afterwards, we'll properly
434 # fix up permissions.
437 # Start processing metadata stored in the root to recreate the files.
438 print "Root object: $root\n" if $VERBOSE;
439 my $contents = load_ref($root);
440 process_metadata($contents);