* Added Simplified Chinese CGI translation from Youlin Feng.
[BackupPC.git] / bin / BackupPC_tarCreate
1 #!/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       BLOCKS x 512 bytes per record (default 20; same as tar)
25 #       -w writeBufSz   write buffer size (default 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-2003  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.0.0, released 28 Jan 2007.
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       BLOCKS x 512 bytes per record (default 20; same as tar)
94      -w writeBufSz   write buffer size (default 1048576 = 1MB)
95      -e charset      charset for encoding file names (default: value of
96                      \$Conf{ClientCharset} when backup was done)
97 EOF
98     exit(1);
99 }
100
101 if ( $opts{h} !~ /^([\w\.\s-]+)$/
102         || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
103     print(STDERR "$0: bad host name '$opts{h}'\n");
104     exit(1);
105 }
106 my $Host = $opts{h};
107
108 if ( $opts{n} !~ /^(-?\d+)$/ ) {
109     print(STDERR "$0: bad dump number '$opts{n}'\n");
110     exit(1);
111 }
112 my $Num = $opts{n};
113
114 my @Backups = $bpc->BackupInfoRead($Host);
115 my $FileCnt = 0;
116 my $ByteCnt = 0;
117 my $DirCnt = 0;
118 my $SpecialCnt = 0;
119 my $ErrorCnt = 0;
120
121 my $i;
122 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
123 for ( $i = 0 ; $i < @Backups ; $i++ ) {
124     last if ( $Backups[$i]{num} == $Num );
125 }
126 if ( $i >= @Backups ) {
127     print(STDERR "$0: bad backup number $Num for host $Host\n");
128     exit(1);
129 }
130
131 my $Charset = $Backups[$i]{charset};
132 $Charset = $opts{e} if ( $opts{e} ne "" );
133
134 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
135 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
136 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
137     print(STDERR "$0: bad share name '$opts{s}'\n");
138     exit(1);
139 }
140
141 our $ShareName = $opts{s};
142 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
143
144 #
145 # This constant and the line of code below that uses it are borrowed
146 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
147 # See www.cpan.org.
148 #
149 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
150 #                 Copyright 1998 Stephen Zander. All rights reserved.
151 #
152 my $tar_pack_header
153     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
154 my $tar_header_length = 512;
155
156 my $BufSize    = $opts{w} || 1048576;     # 1MB or 2^20
157 my $WriteBuf   = "";
158 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
159
160 my(%UidCache, %GidCache);
161 my(%HardLinkExtraFiles, @HardLinks);
162
163 #
164 # Write out all the requested files/directories
165 #
166 binmode(STDOUT);
167 my $fh = *STDOUT;
168 if ( $ShareName eq "*" ) {
169     my $PathRemoveOrig = $PathRemove;
170     my $PathAddOrig    = $PathAdd;
171     foreach $ShareName ( $view->shareList($Num) ) {
172         #print(STDERR "Doing share ($ShareName)\n");
173         $PathRemove = "/" if ( !defined($PathRemoveOrig) );
174         ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
175         foreach my $dir ( @ARGV ) {
176             archiveWrite($fh, $dir);
177         }
178         archiveWriteHardLinks($fh);
179     }
180 } else {
181     foreach my $dir ( @ARGV ) {
182         archiveWrite($fh, $dir);
183     }
184     archiveWriteHardLinks($fh);
185 }
186
187 #
188 # Finish with two null 512 byte headers, and then round out a full
189 # block.
190
191 my $data = "\0" x ($tar_header_length * 2);
192 TarWrite($fh, \$data);
193 TarWrite($fh, undef);
194
195 #
196 # print out totals if requested
197 #
198 if ( $opts{t} ) {
199     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
200                  " $SpecialCnt specials, $ErrorCnt errors\n";
201 }
202 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
203     #
204     # Got errors, with no files or directories; exit with non-zero
205     # status
206     #
207     exit(1);
208 }
209 exit(0);
210
211 ###########################################################################
212 # Subroutines
213 ###########################################################################
214
215 sub archiveWrite
216 {
217     my($fh, $dir, $tarPathOverride) = @_;
218
219     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
220         print(STDERR "$0: bad directory '$dir'\n");
221         $ErrorCnt++;
222         return;
223     }
224     $dir = "/" if ( $dir eq "." );
225     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
226     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
227                 $fh, $tarPathOverride) < 0 ) {
228         print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
229         $ErrorCnt++;
230         return;
231     }
232 }
233
234 #
235 # Write out any hardlinks (if any)
236 #
237 sub archiveWriteHardLinks
238 {
239     my($fh) = @_;
240     foreach my $hdr ( @HardLinks ) {
241         $hdr->{size} = 0;
242         my $name = $hdr->{linkname};
243         $name =~ s{^\./}{/};
244         if ( defined($HardLinkExtraFiles{$name}) ) {
245             $hdr->{linkname} = $HardLinkExtraFiles{$name};
246         }
247         if ( defined($PathRemove)
248               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
249                         eq ".$PathRemove" ) {
250             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
251         }
252         TarWriteFileInfo($fh, $hdr);
253     }
254     @HardLinks = ();
255     %HardLinkExtraFiles = ();
256 }
257
258 sub UidLookup
259 {
260     my($uid) = @_;
261
262     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
263     return $UidCache{$uid};
264 }
265
266 sub GidLookup
267 {
268     my($gid) = @_;
269
270     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
271     return $GidCache{$gid};
272 }
273
274 sub TarWrite
275 {
276     my($fh, $dataRef) = @_;
277
278     if ( !defined($dataRef) ) {
279         #
280         # do flush by padding to a full $WriteBufSz
281         #
282         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
283         $dataRef = \$data;
284     }
285     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
286         #
287         # just buffer and return
288         #
289         $WriteBuf .= $$dataRef;
290         return;
291     }
292     my $done = $WriteBufSz - length($WriteBuf);
293     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
294                                 != $WriteBufSz ) {
295         print(STDERR "Unable to write to output file ($!)\n");
296         exit(1);
297     }
298     while ( $done + $WriteBufSz <= length($$dataRef) ) {
299         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
300                             != $WriteBufSz ) {
301             print(STDERR "Unable to write to output file ($!)\n");
302             exit(1);
303         }
304         $done += $WriteBufSz;
305     }
306     $WriteBuf = substr($$dataRef, $done);
307 }
308
309 sub TarWritePad
310 {
311     my($fh, $size) = @_;
312
313     if ( $size % $tar_header_length ) {
314         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
315         TarWrite($fh, \$data);
316     }
317 }
318
319 sub TarWriteHeader
320 {
321     my($fh, $hdr) = @_;
322
323     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
324     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
325     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
326                                              : "";
327     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
328                                              : "";
329     my $sizeStr;
330     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
331         #
332         # GNU extension for files >= 8GB: send size in big-endian binary
333         #
334         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
335                                   $hdr->{size} / (65536 * 65536),
336                                   $hdr->{size} % (65536 * 65536));
337     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
338         #
339         # sprintf octal only handles up to 2^32 - 1
340         #
341         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
342                  . sprintf("%08o", $hdr->{size} % (1 << 24));
343     } else {
344         $sizeStr = sprintf("%011o", $hdr->{size});
345     }
346     my $data = pack($tar_pack_header,
347                      substr($hdr->{name}, 0, 99),
348                      sprintf("%07o", $hdr->{mode}),
349                      sprintf("%07o", $hdr->{uid}),
350                      sprintf("%07o", $hdr->{gid}),
351                      $sizeStr,
352                      sprintf("%011o", $hdr->{mtime}),
353                      "",        #checksum field - space padded by pack("A8")
354                      $hdr->{type},
355                      substr($hdr->{linkname}, 0, 99),
356                      $hdr->{magic} || 'ustar ',
357                      $hdr->{version} || ' ',
358                      $hdr->{uname},
359                      $hdr->{gname},
360                      $devmajor,
361                      $devminor,
362                      ""         # prefix is empty
363                  );
364     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
365     TarWrite($fh, \$data);
366 }
367
368 sub TarWriteFileInfo
369 {
370     my($fh, $hdr) = @_;
371
372     #
373     # Convert path names to requested (eg: client) charset
374     #
375     if ( $Charset ne "" ) {
376         from_to($hdr->{name},     "utf8", $Charset);
377         from_to($hdr->{linkname}, "utf8", $Charset);
378     }
379
380     if ( $opts{l} ) {
381         print($hdr->{name} . "\n");
382         return;
383     } elsif ( $opts{L} ) {
384         my $owner = "$hdr->{uid}/$hdr->{gid}";
385
386         my $name = $hdr->{name};
387
388         if ( $hdr->{type} == BPC_FTYPE_SYMLINK
389                 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
390             $name .= " -> $hdr->{linkname}";
391         }
392         $name =~ s/\n/\\n/g;
393
394         printf("%6o %9s %11.0f %s\n",
395                                     $hdr->{mode},
396                                     $owner,
397                                     $hdr->{size},
398                                     $name);
399         return;
400     }
401
402     #
403     # Handle long link names (symbolic links)
404     #
405     if ( length($hdr->{linkname}) > 99 ) {
406         my %h;
407         my $data = $hdr->{linkname} . "\0";
408         $h{name} = "././\@LongLink";
409         $h{type} = "K";
410         $h{size} = length($data);
411         TarWriteHeader($fh, \%h);
412         TarWrite($fh, \$data);
413         TarWritePad($fh, length($data));
414     }
415
416     #
417     # Handle long file names
418     #
419     if ( length($hdr->{name}) > 99 ) {
420         my %h;
421         my $data = $hdr->{name} . "\0";
422         $h{name} = "././\@LongLink";
423         $h{type} = "L";
424         $h{size} = length($data);
425         TarWriteHeader($fh, \%h);
426         TarWrite($fh, \$data);
427         TarWritePad($fh, length($data));
428     }
429     TarWriteHeader($fh, $hdr);
430 }
431
432 my $Attr;
433 my $AttrDir;
434
435 sub TarWriteFile
436 {
437     my($hdr, $fh, $tarPathOverride) = @_;
438
439     my $tarPath = $hdr->{relPath};
440     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
441
442     $tarPath =~ s{//+}{/}g;
443     if ( defined($PathRemove)
444             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
445         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
446     }
447     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
448     $tarPath =~ s{//+}{/}g;
449     $hdr->{name} = $tarPath;
450
451     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
452         #
453         # Directory: just write the header
454         #
455         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
456         TarWriteFileInfo($fh, $hdr);
457         $DirCnt++;
458     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
459         my($data, $size);
460         #
461         # Regular file: write the header and file
462         #
463         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
464         if ( !defined($f) ) {
465             print(STDERR "Unable to open file $hdr->{fullPath}\n");
466             $ErrorCnt++;
467             return;
468         }
469         TarWriteFileInfo($fh, $hdr);
470         if ( $opts{l} || $opts{L} ) {
471             $size = $hdr->{size};
472         } else {
473             while ( $f->read(\$data, $BufSize) > 0 ) {
474                 if ( $size + length($data) > $hdr->{size} ) {
475                     print(STDERR "Error: truncating $hdr->{fullPath} to"
476                                . " $hdr->{size} bytes\n");
477                     $data = substr($data, 0, $hdr->{size} - $size);
478                     $ErrorCnt++;
479                 }
480                 TarWrite($fh, \$data);
481                 $size += length($data);
482             }
483             $f->close;
484             if ( $size != $hdr->{size} ) {
485                 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
486                            . " bytes from $size bytes\n");
487                 $ErrorCnt++;
488                 while ( $size < $hdr->{size} ) {
489                     my $len = $hdr->{size} - $size;
490                     $len = $BufSize if ( $len > $BufSize );
491                     $data = "\0" x $len;
492                     TarWrite($fh, \$data);
493                     $size += $len;
494                 }
495             }
496             TarWritePad($fh, $size);
497         }
498         $FileCnt++;
499         $ByteCnt += $size;
500     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
501         #
502         # Hardlink file: either write a hardlink or the complete file
503         # depending upon whether the linked-to file will be written
504         # to the archive.
505         #
506         # Start by reading the contents of the link.
507         #
508         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
509         if ( !defined($f) ) {
510             print(STDERR "Unable to open file $hdr->{fullPath}\n");
511             $ErrorCnt++;
512             return;
513         }
514         my $data;
515         while ( $f->read(\$data, $BufSize) > 0 ) {
516             $hdr->{linkname} .= $data;
517         }
518         $f->close;
519         #
520         # Check @ARGV and the list of hardlinked files we have explicity
521         # dumped to see if we have dumped this file or not
522         #
523         my $done = 0;
524         my $name = $hdr->{linkname};
525         $name =~ s{^\./}{/};
526         if ( defined($HardLinkExtraFiles{$name}) ) {
527             $done = 1;
528         } else {
529             foreach my $arg ( @ARGV ) {
530                 $arg = "/" if ( $arg eq "." );
531                 $arg =~ s{^\./+}{/};
532                 $arg =~ s{/+$}{};
533                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
534             }
535         }
536         if ( $done ) {
537             #
538             # Target file will be or was written, so just remember
539             # the hardlink so we can dump it later.
540             #
541             push(@HardLinks, $hdr);
542             $SpecialCnt++;
543         } else {
544             #
545             # Have to dump the original file.  Just call the top-level
546             # routine, so that we save the hassle of dealing with
547             # mangling, merging and attributes.
548             #
549             my $name = $hdr->{linkname};
550             $name =~ s{^\./}{/};
551             $HardLinkExtraFiles{$name} = $hdr->{name};
552             archiveWrite($fh, $name, $hdr->{name});
553         }
554     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
555         #
556         # Symbolic link: read the symbolic link contents into the header
557         # and write the header.
558         #
559         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
560         if ( !defined($f) ) {
561             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
562             $ErrorCnt++;
563             return;
564         }
565         my $data;
566         while ( $f->read(\$data, $BufSize) > 0 ) {
567             $hdr->{linkname} .= $data;
568         }
569         $f->close;
570         $hdr->{size} = 0;
571         TarWriteFileInfo($fh, $hdr);
572         $SpecialCnt++;
573     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
574            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
575            || $hdr->{type} == BPC_FTYPE_FIFO ) {
576         #
577         # Special files: for char and block special we read the
578         # major and minor numbers from a plain file.
579         #
580         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
581             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
582                                                 $hdr->{compress});
583             my $data;
584             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
585                 print(STDERR "Unable to open/read char/block special file"
586                            . " $hdr->{fullPath}\n");
587                 $f->close if ( defined($f) );
588                 $ErrorCnt++;
589                 return;
590             }
591             $f->close;
592             if ( $data =~ /(\d+),(\d+)/ ) {
593                 $hdr->{devmajor} = $1;
594                 $hdr->{devminor} = $2;
595             }
596         }
597         $hdr->{size} = 0;
598         TarWriteFileInfo($fh, $hdr);
599         $SpecialCnt++;
600     } else {
601         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
602         $ErrorCnt++;
603     }
604 }