Release for 3.2.0. Changes since 3.2.0beta1:
[BackupPC.git] / bin / BackupPC_tarCreate
1 #!/usr/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_tarCreate: create a tar archive of an existing dump
5 # for restore on a client.
6 #
7 # DESCRIPTION
8 #  
9 #   Usage: BackupPC_tarCreate [options] files/directories...
10 #
11 #   Flags:
12 #     Required options:
13 #
14 #       -h host         Host from which the tar archive is created.
15 #       -n dumpNum      Dump number from which the tar archive is created.
16 #                       A negative number means relative to the end (eg -1
17 #                       means the most recent dump, -2 2nd most recent etc).
18 #       -s shareName    Share name from which the tar archive is created.
19 #
20 #     Other options:
21 #       -t              print summary totals
22 #       -r pathRemove   path prefix that will be replaced with pathAdd
23 #       -p pathAdd      new path prefix
24 #       -b BLOCKS       output write buffer size in 512-byte blocks (default 20; same as tar)
25 #       -w readBufSz    buffer size for reading files (default 1048576 = 1MB)
26 #       -e charset      charset for encoding file names (default: value of
27 #                       $Conf{ClientCharset} when backup was done)
28 #       -l              just print a file listing; don't generate an archive
29 #       -L              just print a detailed file listing; don't generate an archive
30 #
31 #     The -h, -n and -s options specify which dump is used to generate
32 #     the tar archive.  The -r and -p options can be used to relocate
33 #     the paths in the tar archive so extracted files can be placed
34 #     in a location different from their original location.
35 #
36 # AUTHOR
37 #   Craig Barratt  <cbarratt@users.sourceforge.net>
38 #
39 # COPYRIGHT
40 #   Copyright (C) 2001-2009  Craig Barratt
41 #
42 #   This program is free software; you can redistribute it and/or modify
43 #   it under the terms of the GNU General Public License as published by
44 #   the Free Software Foundation; either version 2 of the License, or
45 #   (at your option) any later version.
46 #
47 #   This program is distributed in the hope that it will be useful,
48 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
49 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
50 #   GNU General Public License for more details.
51 #
52 #   You should have received a copy of the GNU General Public License
53 #   along with this program; if not, write to the Free Software
54 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
55 #
56 #========================================================================
57 #
58 # Version 3.2.0, released 31 Jul 2010.
59 #
60 # See http://backuppc.sourceforge.net.
61 #
62 #========================================================================
63
64 use strict;
65 no  utf8;
66 use lib "/usr/local/BackupPC/lib";
67 use File::Path;
68 use Getopt::Std;
69 use Encode qw/from_to/;
70 use BackupPC::Lib;
71 use BackupPC::Attrib qw(:all);
72 use BackupPC::FileZIO;
73 use BackupPC::View;
74
75 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
76
77 my %opts;
78
79 if ( !getopts("Llte:h:n:p:r:s:b:w:", \%opts) || @ARGV < 1 ) {
80     print STDERR <<EOF;
81 usage: $0 [options] files/directories...
82   Required options:
83      -h host         host from which the tar archive is created
84      -n dumpNum      dump number from which the tar archive is created
85                      A negative number means relative to the end (eg -1
86                      means the most recent dump, -2 2nd most recent etc).
87      -s shareName    share name from which the tar archive is created
88
89   Other options:
90      -t              print summary totals
91      -r pathRemove   path prefix that will be replaced with pathAdd
92      -p pathAdd      new path prefix
93      -b BLOCKS       output write buffer size in 512-byte blocks (default 20; same as tar)
94      -w readBufSz    buffer size for reading files (default 1048576 = 1MB)
95      -e charset      charset for encoding file names (default: value of
96                      \$Conf{ClientCharset} when backup was done)
97      -l              just print a file listing; don't generate an archive
98      -L              just print a detailed file listing; don't generate an archive
99 EOF
100     exit(1);
101 }
102
103 if ( $opts{h} !~ /^([\w\.\s-]+)$/
104         || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
105     print(STDERR "$0: bad host name '$opts{h}'\n");
106     exit(1);
107 }
108 my $Host = $opts{h};
109
110 if ( $opts{n} !~ /^(-?\d+)$/ ) {
111     print(STDERR "$0: bad dump number '$opts{n}'\n");
112     exit(1);
113 }
114 my $Num = $opts{n};
115
116 my @Backups = $bpc->BackupInfoRead($Host);
117 my $FileCnt = 0;
118 my $ByteCnt = 0;
119 my $DirCnt = 0;
120 my $SpecialCnt = 0;
121 my $ErrorCnt = 0;
122
123 my $i;
124 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
125 for ( $i = 0 ; $i < @Backups ; $i++ ) {
126     last if ( $Backups[$i]{num} == $Num );
127 }
128 if ( $i >= @Backups ) {
129     print(STDERR "$0: bad backup number $Num for host $Host\n");
130     exit(1);
131 }
132
133 my $Charset = $Backups[$i]{charset};
134 $Charset = $opts{e} if ( $opts{e} ne "" );
135
136 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
137 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
138 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
139     print(STDERR "$0: bad share name '$opts{s}'\n");
140     exit(1);
141 }
142
143 our $ShareName = $opts{s};
144 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
145
146 #
147 # This constant and the line of code below that uses it are borrowed
148 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
149 # See www.cpan.org.
150 #
151 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
152 #                 Copyright 1998 Stephen Zander. All rights reserved.
153 #
154 my $tar_pack_header
155     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
156 my $tar_header_length = 512;
157
158 my $BufSize    = $opts{w} || 1048576;     # 1MB or 2^20
159 my $WriteBuf   = "";
160 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
161
162 my(%UidCache, %GidCache);
163 my(%HardLinkExtraFiles, @HardLinks);
164
165 #
166 # Write out all the requested files/directories
167 #
168 binmode(STDOUT);
169 my $fh = *STDOUT;
170 if ( $ShareName eq "*" ) {
171     my $PathRemoveOrig = $PathRemove;
172     my $PathAddOrig    = $PathAdd;
173     foreach $ShareName ( $view->shareList($Num) ) {
174         #print(STDERR "Doing share ($ShareName)\n");
175         $PathRemove = "/" if ( !defined($PathRemoveOrig) );
176         ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
177         foreach my $dir ( @ARGV ) {
178             archiveWrite($fh, $dir);
179         }
180         archiveWriteHardLinks($fh);
181     }
182 } else {
183     foreach my $dir ( @ARGV ) {
184         archiveWrite($fh, $dir);
185     }
186     archiveWriteHardLinks($fh);
187 }
188
189 if ( !$opts{l} && !$opts{L} ) {
190     #
191     # Finish with two null 512 byte headers, and then round out a full
192     # block.
193     # 
194     my $data = "\0" x ($tar_header_length * 2);
195     TarWrite($fh, \$data);
196     TarWrite($fh, undef);
197 }
198
199 #
200 # print out totals if requested
201 #
202 if ( $opts{t} ) {
203     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
204                  " $SpecialCnt specials, $ErrorCnt errors\n";
205 }
206 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
207     #
208     # Got errors, with no files or directories; exit with non-zero
209     # status
210     #
211     exit(1);
212 }
213 exit(0);
214
215 ###########################################################################
216 # Subroutines
217 ###########################################################################
218
219 sub archiveWrite
220 {
221     my($fh, $dir, $tarPathOverride) = @_;
222
223     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
224         print(STDERR "$0: bad directory '$dir'\n");
225         $ErrorCnt++;
226         return;
227     }
228     $dir = "/" if ( $dir eq "." );
229     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
230     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
231                 $fh, $tarPathOverride) < 0 ) {
232         print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
233         $ErrorCnt++;
234         return;
235     }
236 }
237
238 #
239 # Write out any hardlinks (if any)
240 #
241 sub archiveWriteHardLinks
242 {
243     my($fh) = @_;
244     foreach my $hdr ( @HardLinks ) {
245         $hdr->{size} = 0;
246         my $name = $hdr->{linkname};
247         $name =~ s{^\./}{/};
248         if ( defined($HardLinkExtraFiles{$name}) ) {
249             $hdr->{linkname} = $HardLinkExtraFiles{$name};
250         }
251         if ( defined($PathRemove)
252               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
253                         eq ".$PathRemove" ) {
254             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
255         }
256         TarWriteFileInfo($fh, $hdr);
257     }
258     @HardLinks = ();
259     %HardLinkExtraFiles = ();
260 }
261
262 sub UidLookup
263 {
264     my($uid) = @_;
265
266     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
267     return $UidCache{$uid};
268 }
269
270 sub GidLookup
271 {
272     my($gid) = @_;
273
274     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
275     return $GidCache{$gid};
276 }
277
278 sub TarWrite
279 {
280     my($fh, $dataRef) = @_;
281
282     if ( !defined($dataRef) ) {
283         #
284         # do flush by padding to a full $WriteBufSz
285         #
286         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
287         $dataRef = \$data;
288     }
289     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
290         #
291         # just buffer and return
292         #
293         $WriteBuf .= $$dataRef;
294         return;
295     }
296     my $done = $WriteBufSz - length($WriteBuf);
297     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
298                                 != $WriteBufSz ) {
299         print(STDERR "Unable to write to output file ($!)\n");
300         exit(1);
301     }
302     while ( $done + $WriteBufSz <= length($$dataRef) ) {
303         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
304                             != $WriteBufSz ) {
305             print(STDERR "Unable to write to output file ($!)\n");
306             exit(1);
307         }
308         $done += $WriteBufSz;
309     }
310     $WriteBuf = substr($$dataRef, $done);
311 }
312
313 sub TarWritePad
314 {
315     my($fh, $size) = @_;
316
317     if ( $size % $tar_header_length ) {
318         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
319         TarWrite($fh, \$data);
320     }
321 }
322
323 sub TarWriteHeader
324 {
325     my($fh, $hdr) = @_;
326
327     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
328     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
329     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
330                                              : "";
331     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
332                                              : "";
333     my $sizeStr;
334     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
335         #
336         # GNU extension for files >= 8GB: send size in big-endian binary
337         #
338         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
339                                   $hdr->{size} / (65536 * 65536),
340                                   $hdr->{size} % (65536 * 65536));
341     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
342         #
343         # sprintf octal only handles up to 2^32 - 1
344         #
345         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
346                  . sprintf("%08o", $hdr->{size} % (1 << 24));
347     } else {
348         $sizeStr = sprintf("%011o", $hdr->{size});
349     }
350     my $data = pack($tar_pack_header,
351                      substr($hdr->{name}, 0, 99),
352                      sprintf("%07o", $hdr->{mode}),
353                      sprintf("%07o", $hdr->{uid}),
354                      sprintf("%07o", $hdr->{gid}),
355                      $sizeStr,
356                      sprintf("%011o", $hdr->{mtime}),
357                      "",        #checksum field - space padded by pack("A8")
358                      $hdr->{type},
359                      substr($hdr->{linkname}, 0, 99),
360                      $hdr->{magic} || 'ustar ',
361                      $hdr->{version} || ' ',
362                      $hdr->{uname},
363                      $hdr->{gname},
364                      $devmajor,
365                      $devminor,
366                      ""         # prefix is empty
367                  );
368     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
369     TarWrite($fh, \$data);
370 }
371
372 sub TarWriteFileInfo
373 {
374     my($fh, $hdr) = @_;
375
376     #
377     # Convert path names to requested (eg: client) charset
378     #
379     if ( $Charset ne "" ) {
380         from_to($hdr->{name},     "utf8", $Charset);
381         from_to($hdr->{linkname}, "utf8", $Charset);
382     }
383
384     if ( $opts{l} ) {
385         print($hdr->{name} . "\n");
386         return;
387     } elsif ( $opts{L} ) {
388         my $owner = "$hdr->{uid}/$hdr->{gid}";
389
390         my $name = $hdr->{name};
391
392         if ( $hdr->{type} == BPC_FTYPE_SYMLINK
393                 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
394             $name .= " -> $hdr->{linkname}";
395         }
396         $name =~ s/\n/\\n/g;
397
398         printf("%6o %9s %11.0f %s\n",
399                                     $hdr->{mode},
400                                     $owner,
401                                     $hdr->{size},
402                                     $name);
403         return;
404     }
405
406     #
407     # Handle long link names (symbolic links)
408     #
409     if ( length($hdr->{linkname}) > 99 ) {
410         my %h;
411         my $data = $hdr->{linkname} . "\0";
412         $h{name} = "././\@LongLink";
413         $h{type} = "K";
414         $h{size} = length($data);
415         TarWriteHeader($fh, \%h);
416         TarWrite($fh, \$data);
417         TarWritePad($fh, length($data));
418     }
419
420     #
421     # Handle long file names
422     #
423     if ( length($hdr->{name}) > 99 ) {
424         my %h;
425         my $data = $hdr->{name} . "\0";
426         $h{name} = "././\@LongLink";
427         $h{type} = "L";
428         $h{size} = length($data);
429         TarWriteHeader($fh, \%h);
430         TarWrite($fh, \$data);
431         TarWritePad($fh, length($data));
432     }
433     TarWriteHeader($fh, $hdr);
434 }
435
436 my $Attr;
437 my $AttrDir;
438
439 sub TarWriteFile
440 {
441     my($hdr, $fh, $tarPathOverride) = @_;
442
443     my $tarPath = $hdr->{relPath};
444     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
445
446     $tarPath =~ s{//+}{/}g;
447     if ( defined($PathRemove)
448             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
449         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
450     }
451     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
452     $tarPath =~ s{//+}{/}g;
453     $hdr->{name} = $tarPath;
454
455     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
456         #
457         # Directory: just write the header
458         #
459         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
460         TarWriteFileInfo($fh, $hdr);
461         $DirCnt++;
462     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
463         my($data, $size);
464         #
465         # Regular file: write the header and file
466         #
467         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
468         if ( !defined($f) ) {
469             print(STDERR "Unable to open file $hdr->{fullPath}\n");
470             $ErrorCnt++;
471             return;
472         }
473         TarWriteFileInfo($fh, $hdr);
474         if ( $opts{l} || $opts{L} ) {
475             $size = $hdr->{size};
476         } else {
477             while ( $f->read(\$data, $BufSize) > 0 ) {
478                 if ( $size + length($data) > $hdr->{size} ) {
479                     print(STDERR "Error: truncating $hdr->{fullPath} to"
480                                . " $hdr->{size} bytes\n");
481                     $data = substr($data, 0, $hdr->{size} - $size);
482                     $ErrorCnt++;
483                 }
484                 TarWrite($fh, \$data);
485                 $size += length($data);
486             }
487             $f->close;
488             if ( $size != $hdr->{size} ) {
489                 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
490                            . " bytes from $size bytes\n");
491                 $ErrorCnt++;
492                 while ( $size < $hdr->{size} ) {
493                     my $len = $hdr->{size} - $size;
494                     $len = $BufSize if ( $len > $BufSize );
495                     $data = "\0" x $len;
496                     TarWrite($fh, \$data);
497                     $size += $len;
498                 }
499             }
500             TarWritePad($fh, $size);
501         }
502         $FileCnt++;
503         $ByteCnt += $size;
504     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
505         #
506         # Hardlink file: either write a hardlink or the complete file
507         # depending upon whether the linked-to file will be written
508         # to the archive.
509         #
510         # Start by reading the contents of the link.
511         #
512         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
513         if ( !defined($f) ) {
514             print(STDERR "Unable to open file $hdr->{fullPath}\n");
515             $ErrorCnt++;
516             return;
517         }
518         my $data;
519         while ( $f->read(\$data, $BufSize) > 0 ) {
520             $hdr->{linkname} .= $data;
521         }
522         $f->close;
523         #
524         # Check @ARGV and the list of hardlinked files we have explicity
525         # dumped to see if we have dumped this file or not
526         #
527         my $done = 0;
528         my $name = $hdr->{linkname};
529         $name =~ s{^\./}{/};
530         if ( defined($HardLinkExtraFiles{$name}) ) {
531             $done = 1;
532         } else {
533             foreach my $arg ( @ARGV ) {
534                 $arg = "/" if ( $arg eq "." );
535                 $arg =~ s{^\./+}{/};
536                 $arg =~ s{/+$}{};
537                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
538             }
539         }
540         if ( $done ) {
541             #
542             # Target file will be or was written, so just remember
543             # the hardlink so we can dump it later.
544             #
545             push(@HardLinks, $hdr);
546             $SpecialCnt++;
547         } else {
548             #
549             # Have to dump the original file.  Just call the top-level
550             # routine, so that we save the hassle of dealing with
551             # mangling, merging and attributes.
552             #
553             my $name = $hdr->{linkname};
554             $name =~ s{^\./}{/};
555             $HardLinkExtraFiles{$name} = $hdr->{name};
556             archiveWrite($fh, $name, $hdr->{name});
557         }
558     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
559         #
560         # Symbolic link: read the symbolic link contents into the header
561         # and write the header.
562         #
563         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
564         if ( !defined($f) ) {
565             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
566             $ErrorCnt++;
567             return;
568         }
569         my $data;
570         while ( $f->read(\$data, $BufSize) > 0 ) {
571             $hdr->{linkname} .= $data;
572         }
573         $f->close;
574         $hdr->{size} = 0;
575         TarWriteFileInfo($fh, $hdr);
576         $SpecialCnt++;
577     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
578            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
579            || $hdr->{type} == BPC_FTYPE_FIFO ) {
580         #
581         # Special files: for char and block special we read the
582         # major and minor numbers from a plain file.
583         #
584         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
585             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
586                                                 $hdr->{compress});
587             my $data;
588             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
589                 print(STDERR "Unable to open/read char/block special file"
590                            . " $hdr->{fullPath}\n");
591                 $f->close if ( defined($f) );
592                 $ErrorCnt++;
593                 return;
594             }
595             $f->close;
596             if ( $data =~ /(\d+),(\d+)/ ) {
597                 $hdr->{devmajor} = $1;
598                 $hdr->{devminor} = $2;
599             }
600         }
601         $hdr->{size} = 0;
602         TarWriteFileInfo($fh, $hdr);
603         $SpecialCnt++;
604     } elsif ( $hdr->{type} == BPC_FTYPE_SOCKET
605            || $hdr->{type} == BPC_FTYPE_UNKNOWN ) {
606         #
607         # ignore these two file types - these are dynamic file types created
608         # by applications as needed
609         #
610     } else {
611         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
612         $ErrorCnt++;
613     }
614 }