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