* Failed dumps now cleanup correctly, deleting in-progress file
[BackupPC.git] / bin / BackupPC_tarExtract
1 #!/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_tarExtract: extract data from a dump
5 #
6 # DESCRIPTION
7 #
8 # AUTHOR
9 #   Craig Barratt  <cbarratt@users.sourceforge.net>
10 #
11 # COPYRIGHT
12 #   Copyright (C) 2001-2003  Craig Barratt
13 #
14 #   This program is free software; you can redistribute it and/or modify
15 #   it under the terms of the GNU General Public License as published by
16 #   the Free Software Foundation; either version 2 of the License, or
17 #   (at your option) any later version.
18 #
19 #   This program is distributed in the hope that it will be useful,
20 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
21 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 #   GNU General Public License for more details.
23 #
24 #   You should have received a copy of the GNU General Public License
25 #   along with this program; if not, write to the Free Software
26 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 #
28 #========================================================================
29 #
30 # Version 2.1.0_CVS, released 8 Feb 2004.
31 #
32 # See http://backuppc.sourceforge.net.
33 #
34 #========================================================================
35
36 use strict;
37 no  utf8;
38 use lib "/usr/local/BackupPC/lib";
39 use BackupPC::Lib;
40 use BackupPC::Attrib qw(:all);
41 use BackupPC::FileZIO;
42 use BackupPC::PoolWrite;
43 use File::Path;
44
45 use constant S_IFMT       => 0170000;   # type of file
46
47 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
48 my $TopDir = $bpc->TopDir();
49 my $BinDir = $bpc->BinDir();
50 my %Conf   = $bpc->Conf();
51
52 if ( @ARGV != 3 ) {
53     print("usage: $0 <client> <shareName> <compressLevel>\n");
54     exit(1);
55 }
56 if ( $ARGV[0] !~ /^([\w\.\s-]+)$/ ) {
57     print("$0: bad client name '$ARGV[0]'\n");
58     exit(1);
59 }
60 my $client = $1;
61 if ( $ARGV[1] !~ /^([\w\s\.\/\$-]+)$/ ) {
62     print("$0: bad share name '$ARGV[1]'\n");
63     exit(1);
64 }
65 my $ShareNameUM = $1;
66 my $ShareName = $bpc->fileNameEltMangle($ShareNameUM);
67 if ( $ARGV[2] !~ /^(\d+)$/ ) {
68     print("$0: bad compress level '$ARGV[2]'\n");
69     exit(1);
70 }
71 my $Compress = $1;
72 my $Abort = 0;
73 my $AbortReason;
74
75 #
76 # Re-read config file, so we can include the PC-specific config
77 #
78 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
79     print("BackupPC_tarExtract: Can't read PC's config file: $error\n");
80     exit(1);
81 }
82 %Conf = $bpc->Conf();
83
84 #
85 # Catch various signals
86 #
87 $SIG{INT}  = \&catch_signal;
88 $SIG{ALRM} = \&catch_signal;
89 $SIG{TERM} = \&catch_signal;
90 $SIG{PIPE} = \&catch_signal;
91 $SIG{STOP} = \&catch_signal;
92 $SIG{TSTP} = \&catch_signal;
93 $SIG{TTIN} = \&catch_signal;
94
95 #
96 # This constant and the line of code below that uses it is borrowed
97 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
98 # See www.cpan.org.
99 #
100 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
101 #                 Copyright 1998 Stephen Zander. All rights reserved.
102 #
103 my $tar_unpack_header
104     = 'Z100 A8 A8 A8 A12 A12 A8 A1 Z100 A6 A2 Z32 Z32 A8 A8 A155 x12';
105 my $tar_header_length = 512;
106
107 my $BufSize  = 1048576;     # 1MB or 2^20
108 my $MaxFiles = 20;
109 my $Errors   = 0;
110 my $OutDir   = "$TopDir/pc/$client/new";
111 my %Attrib   = ();
112
113 my $ExistFileCnt      = 0;
114 my $ExistFileSize     = 0;
115 my $ExistFileCompSize = 0;
116 my $TotalFileCnt      = 0;
117 my $TotalFileSize     = 0;
118
119 sub TarRead
120 {
121     my($fh, $totBytes) = @_;
122     my($numBytes, $newBytes, $data);
123
124     $data = "\0" x $totBytes;
125     while ( $numBytes < $totBytes ) {
126         return if ( $Abort );
127         $newBytes = sysread($fh,
128                         substr($data, $numBytes, $totBytes - $numBytes),
129                         $totBytes - $numBytes);
130         if ( $newBytes <= 0 ) {
131             print("Unexpected end of tar archive (tot = $totBytes,"
132                    . " num = $numBytes, posn = " . sysseek($fh, 0, 1) . ")\n");
133             $Abort = 1;
134             $AbortReason = "Unexpected end of tar archive";
135             $Errors++;
136             return;
137         }
138         $numBytes += $newBytes;
139     }
140     return $data;
141 }
142
143 sub TarReadHeader
144 {
145     my($fh) = @_;
146
147     return $1 if ( TarRead($fh, $tar_header_length) =~ /(.*)/s );
148     return;
149 }
150
151 sub TarFlush
152 {
153     my($fh, $size) = @_;
154
155     if ( $size % $tar_header_length ) {
156         TarRead($fh, $tar_header_length - ($size % $tar_header_length));
157     }
158 }
159
160 sub TarReadFileInfo
161 {
162     my($fh) = @_;
163     my($head, $longName, $longLink);
164     my($name, $mode, $uid, $gid, $size, $mtime, $chksum, $type,
165        $linkname, $magic, $version, $uname, $gname, $devmajor,
166        $devminor, $prefix);
167
168     while ( 1 ) {
169         $head = TarReadHeader($fh);
170         return if ( $Abort || $head eq ""
171                            || $head eq "\0" x $tar_header_length );
172         ($name,         # string
173             $mode,      # octal number
174             $uid,       # octal number
175             $gid,       # octal number
176             $size,      # octal number
177             $mtime,     # octal number
178             $chksum,    # octal number
179             $type,      # character
180             $linkname,  # string
181             $magic,     # string
182             $version,   # two bytes
183             $uname,     # string
184             $gname,     # string
185             $devmajor,  # octal number
186             $devminor,  # octal number
187             $prefix) = unpack($tar_unpack_header, $head);
188
189         $mode     = oct $mode;
190         $uid      = oct $uid;
191         $gid      = oct $gid;
192         if ( ord($size) == 128 ) {
193             #
194             # GNU tar extension: for >=8GB files the size is stored
195             # in big endian binary.
196             #
197             $size = 65536 * 65536 * unpack("N", substr($size, 4, 4))
198                                   + unpack("N", substr($size, 8, 4));
199         } else {
200             #
201             # We used to have a patch here for smbclient 2.2.x.  For file
202             # sizes between 2 and 4GB it sent the wrong size.  But since
203             # samba 3.0.0 has been released we no longer support this
204             # patch since valid files could have sizes that start with
205             # 6 or 7 in octal (eg: 6-8GB files).
206             #
207             # $size =~ s/^6/2/;       # fix bug in smbclient for >=2GB files
208             # $size =~ s/^7/3/;       # fix bug in smbclient for >=2GB files
209             #
210             # To avoid integer overflow in case we are in the 4GB - 8GB
211             # range, we do the conversion in two parts.
212             #
213             if ( $size =~ /([0-9]{9,})/ ) {
214                 my $len = length($1);
215                 $size = oct(substr($1, 0, $len - 8)) * (1 << 24)
216                       + oct(substr($1, $len - 8));
217             } else {
218                 $size = oct($size);
219             }
220         }
221         $mtime    = oct $mtime;
222         $chksum   = oct $chksum;
223         $devmajor = oct $devmajor;
224         $devminor = oct $devminor;
225         $name     = "$prefix/$name" if $prefix;
226         $prefix   = "";
227         substr ($head, 148, 8) = "        ";
228         if (unpack ("%16C*", $head) != $chksum) {
229            print("$name: checksum error at "
230                         . sysseek($fh, 0, 1) , "\n");
231            $Errors++;
232         }
233         if ( $type eq "L" ) {
234             $longName = TarRead($fh, $size) || return;
235             # remove trailing NULL
236             $longName = substr($longName, 0, $size - 1);
237             TarFlush($fh, $size);
238             next;
239         } elsif ( $type eq "K" ) {
240             $longLink = TarRead($fh, $size) || return;
241             # remove trailing NULL
242             $longLink = substr($longLink, 0, $size - 1);
243             TarFlush($fh, $size);
244             next;
245         }
246         printf("Got file '%s', mode 0%o, size %g, type %d\n",
247                 $name, $mode, $size, $type) if ( $Conf{XferLogLevel} >= 3 );
248         $name     = $longName if ( defined($longName) );
249         $linkname = $longLink if ( defined($longLink) );
250         $name     =~ s{^\./+}{};
251         $name     =~ s{/+$}{};
252         $name     =~ s{//+}{/}g;
253         return {
254             name       => $name,
255             mangleName => $bpc->fileNameMangle($name),
256             mode       => $mode,
257             uid        => $uid,
258             gid        => $gid,
259             size       => $size,
260             mtime      => $mtime,
261             type       => $type,
262             linkname   => $linkname,
263             devmajor   => $devmajor,
264             devminor   => $devminor,
265         };
266     }
267 }
268
269 sub TarReadFile
270 {
271     my($fh) = @_;
272     my $f = TarReadFileInfo($fh) || return;
273     my($dir, $file);
274
275     if ( $f->{name} eq "" ) {
276         # top-level dir
277         $dir = "";
278         $file = $ShareNameUM;
279     } else {
280         ($file = $f->{name}) =~ s{.*?([^/]*)$}{$1};         # unmangled file
281         if ( ($dir = $f->{mangleName}) =~ m{(.*)/.*} ) {
282             $dir = "$ShareName/$1";
283         } else {
284             $dir = $ShareName;
285         }
286     }
287     if ( !defined($Attrib{$dir}) ) {
288         foreach my $d ( keys(%Attrib) ) {
289             next if ( $dir =~ m{^\Q$d/} );
290             attributeWrite($d);
291         }
292         $Attrib{$dir} = BackupPC::Attrib->new({ compress => $Compress });
293         if ( -f $Attrib{$dir}->fileName("$OutDir/$dir")
294                     && !$Attrib{$dir}->read("$OutDir/$dir") ) {
295             printf("Unable to read attribute file %s\n",
296                                 $Attrib{$dir}->fileName("$OutDir/$dir"));
297             $Errors++;
298         }
299     }
300     if ( $f->{type} == BPC_FTYPE_DIR ) {
301         #
302         # Directory
303         #
304         logFileAction("create", $f) if ( $Conf{XferLogLevel} >= 1 );
305         mkpath("$OutDir/$ShareName/$f->{mangleName}", 0, 0777)
306                             if ( !-d "$OutDir/$ShareName/$f->{mangleName}" );
307     } elsif ( $f->{type} == BPC_FTYPE_FILE ) {
308         #
309         # Regular file
310         #
311         my($nRead);
312         #print("Reading $f->{name}, $f->{size} bytes, type $f->{type}\n");
313         my $poolWrite = BackupPC::PoolWrite->new($bpc,
314                                          "$OutDir/$ShareName/$f->{mangleName}",
315                                          $f->{size}, $Compress);
316         while ( $nRead < $f->{size} ) {
317             my $thisRead = $f->{size} - $nRead < $BufSize
318                                 ? $f->{size} - $nRead : $BufSize;
319             my $data = TarRead($fh, $thisRead);
320             if ( $data eq "" ) {
321                 if ( !$Abort ) {
322                     print("Unexpected end of tar archive during read\n");
323                     $AbortReason = "Unexpected end of tar archive";
324                     $Errors++;
325                 }
326                 $poolWrite->abort;
327                 $Abort = 1;
328                 unlink("$OutDir/$ShareName/$f->{mangleName}");
329                 print("Removing partial file $f->{name}\n");
330                 return;
331             }
332             $poolWrite->write(\$data);
333             $nRead += $thisRead;
334         }
335         my $exist = processClose($poolWrite, "$ShareName/$f->{mangleName}",
336                                  $f->{size});
337         logFileAction($exist ? "pool" : "create", $f)
338                                  if ( $Conf{XferLogLevel} >= 1 );
339         TarFlush($fh, $f->{size});
340     } elsif ( $f->{type} == BPC_FTYPE_HARDLINK ) {
341         #
342         # Hardlink to another file.  GNU tar is clever about files
343         # that are hardlinks to each other.  The first link will be
344         # sent as a regular file.  The additional links will be sent
345         # as this type.  We store the hardlink just like a symlink:
346         # the link name (path of the linked-to file) is stored in
347         # a plain file.
348         #
349         $f->{size} = length($f->{linkname});
350         my $poolWrite = BackupPC::PoolWrite->new($bpc,
351                                          "$OutDir/$ShareName/$f->{mangleName}",
352                                          $f->{size}, $Compress);
353         $poolWrite->write(\$f->{linkname});
354         my $exist = processClose($poolWrite, "$ShareName/$f->{mangleName}",
355                                  $f->{size});
356         logFileAction($exist ? "pool" : "create", $f)
357                                  if ( $Conf{XferLogLevel} >= 1 );
358     } elsif ( $f->{type} == BPC_FTYPE_SYMLINK ) {
359         #
360         # Symbolic link: write the value of the link to a plain file,
361         # that we pool as usual (ie: we don't create a symlink).
362         # The attributes remember the original file type.
363         # We also change the size to reflect the size of the link
364         # contents.
365         #
366         $f->{size} = length($f->{linkname});
367         my $poolWrite = BackupPC::PoolWrite->new($bpc,
368                                          "$OutDir/$ShareName/$f->{mangleName}",
369                                          $f->{size}, $Compress);
370         $poolWrite->write(\$f->{linkname});
371         my $exist = processClose($poolWrite, "$ShareName/$f->{mangleName}",
372                                  $f->{size});
373         logFileAction($exist ? "pool" : "create", $f)
374                                  if ( $Conf{XferLogLevel} >= 1 );
375     } elsif ( $f->{type} == BPC_FTYPE_CHARDEV
376            || $f->{type} == BPC_FTYPE_BLOCKDEV
377            || $f->{type} == BPC_FTYPE_FIFO ) {
378         #
379         # Special files: for char and block special we write the
380         # major and minor numbers to a plain file, that we pool
381         # as usual.  For a pipe file we create an empty file.
382         # The attributes remember the original file type.
383         #
384         my $data;
385         if ( $f->{type} == BPC_FTYPE_FIFO ) {
386             $data = "";
387         } else {
388             $data = "$f->{devmajor},$f->{devminor}";
389         }
390         my $poolWrite = BackupPC::PoolWrite->new($bpc,
391                                          "$OutDir/$ShareName/$f->{mangleName}",
392                                          length($data), $Compress);
393         $poolWrite->write(\$data);
394         $f->{size} = length($data);
395         my $exist = processClose($poolWrite, "$ShareName/$f->{mangleName}",
396                                  length($data));
397         logFileAction($exist ? "pool" : "create", $f)
398                                  if ( $Conf{XferLogLevel} >= 1 );
399     } else {
400         print("Got unknown type $f->{type} for $f->{name}\n");
401         $Errors++;
402     }
403     $Attrib{$dir}->set($file, {
404                             type  => $f->{type},
405                             mode  => $f->{mode},
406                             uid   => $f->{uid},
407                             gid   => $f->{gid},
408                             size  => $f->{size},
409                             mtime => $f->{mtime},
410                        });
411     return 1;
412 }
413
414 sub attributeWrite
415 {
416     my($d) = @_;
417     my($poolWrite);
418
419     return if ( !defined($Attrib{$d}) );
420     if ( $Attrib{$d}->fileCount ) {
421         my $data = $Attrib{$d}->writeData;
422         my $fileName = $Attrib{$d}->fileName("$OutDir/$d");
423         my $poolWrite = BackupPC::PoolWrite->new($bpc, $fileName,
424                                          length($data), $Compress);
425         $poolWrite->write(\$data);
426         processClose($poolWrite, $Attrib{$d}->fileName($d), length($data));
427     }
428     delete($Attrib{$d});
429 }
430
431 sub processClose
432 {
433     my($poolWrite, $fileName, $origSize) = @_;
434     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
435
436     if ( @$errs ) {
437         print(join("", @$errs));
438         $Errors += @$errs;
439     }
440     $TotalFileCnt++;
441     $TotalFileSize += $origSize;
442     if ( $exists ) {
443         $ExistFileCnt++;
444         $ExistFileSize     += $origSize;
445         $ExistFileCompSize += $outSize;
446     } elsif ( $outSize > 0 ) {
447         print(NEW_FILES "$digest $origSize $fileName\n");
448     }
449     return $exists && $origSize > 0;
450 }
451
452 #
453 # Generate a log file message for a completed file
454 #
455 sub logFileAction
456 {
457     my($action, $f) = @_;
458     my $owner = "$f->{uid}/$f->{gid}";
459     my $name = $f->{name};
460     $name = "." if ( $name eq "" );
461     my $type  = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
462                     [($f->{mode} & S_IFMT) >> 12];
463     $type = "h" if ( $f->{type} == BPC_FTYPE_HARDLINK );
464
465     printf("  %-6s %1s%4o %9s %11.0f %s\n",
466                                 $action,
467                                 $type,
468                                 $f->{mode} & 07777,
469                                 $owner,
470                                 $f->{size},
471                                 $name);
472 }
473
474 sub catch_signal
475 {
476     my $sigName = shift;
477
478     #
479     # The first time we receive a signal we try to gracefully
480     # abort the backup.  This allows us to keep a partial dump
481     # with the in-progress file deleted and attribute caches
482     # flushed to disk etc.
483     #
484     print("BackupPC_tarExtract: got signal $sigName\n");
485     if ( !$Abort ) {
486         $Abort++;
487         $AbortReason = "received signal $sigName";
488         return;
489     }
490
491     #
492     # This is a second signal: time to clean up.
493     #
494     print("BackupPC_tarExtract: quitting on second signal $sigName\n");
495     close(NEW_FILES);
496     exit(1)
497 }
498
499 mkpath("$OutDir/$ShareName", 0, 0777);
500 open(NEW_FILES, ">>", "$TopDir/pc/$client/NewFileList")
501                  || die("can't open $TopDir/pc/$client/NewFileList");
502 binmode(NEW_FILES);
503 binmode(STDIN);
504 1 while ( !$Abort && TarReadFile(*STDIN) );
505 1 while ( !$Abort && sysread(STDIN, my $discard, 1024) );
506
507 #
508 # Flush out remaining attributes.
509 #
510 foreach my $d ( keys(%Attrib) ) {
511     attributeWrite($d);
512 }
513 close(NEW_FILES);
514
515 if ( $Abort ) {
516     print("BackupPC_tarExtact aborting ($AbortReason)\n");
517 }
518
519 #
520 # Report results to BackupPC_dump
521 #
522 print("Done: $Errors errors, $ExistFileCnt filesExist,"
523     . " $ExistFileSize sizeExist, $ExistFileCompSize sizeExistComp,"
524     . " $TotalFileCnt filesTotal, $TotalFileSize sizeTotal\n");