662a3be612992ca2cc68b97d9670caaa0b9e5717
[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.1.0beta0, released 3 Sep 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      -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 #
190 # Finish with two null 512 byte headers, and then round out a full
191 # block.
192
193 my $data = "\0" x ($tar_header_length * 2);
194 TarWrite($fh, \$data);
195 TarWrite($fh, undef);
196
197 #
198 # print out totals if requested
199 #
200 if ( $opts{t} ) {
201     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
202                  " $SpecialCnt specials, $ErrorCnt errors\n";
203 }
204 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
205     #
206     # Got errors, with no files or directories; exit with non-zero
207     # status
208     #
209     exit(1);
210 }
211 exit(0);
212
213 ###########################################################################
214 # Subroutines
215 ###########################################################################
216
217 sub archiveWrite
218 {
219     my($fh, $dir, $tarPathOverride) = @_;
220
221     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
222         print(STDERR "$0: bad directory '$dir'\n");
223         $ErrorCnt++;
224         return;
225     }
226     $dir = "/" if ( $dir eq "." );
227     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
228     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
229                 $fh, $tarPathOverride) < 0 ) {
230         print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
231         $ErrorCnt++;
232         return;
233     }
234 }
235
236 #
237 # Write out any hardlinks (if any)
238 #
239 sub archiveWriteHardLinks
240 {
241     my($fh) = @_;
242     foreach my $hdr ( @HardLinks ) {
243         $hdr->{size} = 0;
244         my $name = $hdr->{linkname};
245         $name =~ s{^\./}{/};
246         if ( defined($HardLinkExtraFiles{$name}) ) {
247             $hdr->{linkname} = $HardLinkExtraFiles{$name};
248         }
249         if ( defined($PathRemove)
250               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
251                         eq ".$PathRemove" ) {
252             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
253         }
254         TarWriteFileInfo($fh, $hdr);
255     }
256     @HardLinks = ();
257     %HardLinkExtraFiles = ();
258 }
259
260 sub UidLookup
261 {
262     my($uid) = @_;
263
264     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
265     return $UidCache{$uid};
266 }
267
268 sub GidLookup
269 {
270     my($gid) = @_;
271
272     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
273     return $GidCache{$gid};
274 }
275
276 sub TarWrite
277 {
278     my($fh, $dataRef) = @_;
279
280     if ( !defined($dataRef) ) {
281         #
282         # do flush by padding to a full $WriteBufSz
283         #
284         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
285         $dataRef = \$data;
286     }
287     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
288         #
289         # just buffer and return
290         #
291         $WriteBuf .= $$dataRef;
292         return;
293     }
294     my $done = $WriteBufSz - length($WriteBuf);
295     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
296                                 != $WriteBufSz ) {
297         print(STDERR "Unable to write to output file ($!)\n");
298         exit(1);
299     }
300     while ( $done + $WriteBufSz <= length($$dataRef) ) {
301         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
302                             != $WriteBufSz ) {
303             print(STDERR "Unable to write to output file ($!)\n");
304             exit(1);
305         }
306         $done += $WriteBufSz;
307     }
308     $WriteBuf = substr($$dataRef, $done);
309 }
310
311 sub TarWritePad
312 {
313     my($fh, $size) = @_;
314
315     if ( $size % $tar_header_length ) {
316         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
317         TarWrite($fh, \$data);
318     }
319 }
320
321 sub TarWriteHeader
322 {
323     my($fh, $hdr) = @_;
324
325     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
326     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
327     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
328                                              : "";
329     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
330                                              : "";
331     my $sizeStr;
332     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
333         #
334         # GNU extension for files >= 8GB: send size in big-endian binary
335         #
336         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
337                                   $hdr->{size} / (65536 * 65536),
338                                   $hdr->{size} % (65536 * 65536));
339     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
340         #
341         # sprintf octal only handles up to 2^32 - 1
342         #
343         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
344                  . sprintf("%08o", $hdr->{size} % (1 << 24));
345     } else {
346         $sizeStr = sprintf("%011o", $hdr->{size});
347     }
348     my $data = pack($tar_pack_header,
349                      substr($hdr->{name}, 0, 99),
350                      sprintf("%07o", $hdr->{mode}),
351                      sprintf("%07o", $hdr->{uid}),
352                      sprintf("%07o", $hdr->{gid}),
353                      $sizeStr,
354                      sprintf("%011o", $hdr->{mtime}),
355                      "",        #checksum field - space padded by pack("A8")
356                      $hdr->{type},
357                      substr($hdr->{linkname}, 0, 99),
358                      $hdr->{magic} || 'ustar ',
359                      $hdr->{version} || ' ',
360                      $hdr->{uname},
361                      $hdr->{gname},
362                      $devmajor,
363                      $devminor,
364                      ""         # prefix is empty
365                  );
366     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
367     TarWrite($fh, \$data);
368 }
369
370 sub TarWriteFileInfo
371 {
372     my($fh, $hdr) = @_;
373
374     #
375     # Convert path names to requested (eg: client) charset
376     #
377     if ( $Charset ne "" ) {
378         from_to($hdr->{name},     "utf8", $Charset);
379         from_to($hdr->{linkname}, "utf8", $Charset);
380     }
381
382     if ( $opts{l} ) {
383         print($hdr->{name} . "\n");
384         return;
385     } elsif ( $opts{L} ) {
386         my $owner = "$hdr->{uid}/$hdr->{gid}";
387
388         my $name = $hdr->{name};
389
390         if ( $hdr->{type} == BPC_FTYPE_SYMLINK
391                 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
392             $name .= " -> $hdr->{linkname}";
393         }
394         $name =~ s/\n/\\n/g;
395
396         printf("%6o %9s %11.0f %s\n",
397                                     $hdr->{mode},
398                                     $owner,
399                                     $hdr->{size},
400                                     $name);
401         return;
402     }
403
404     #
405     # Handle long link names (symbolic links)
406     #
407     if ( length($hdr->{linkname}) > 99 ) {
408         my %h;
409         my $data = $hdr->{linkname} . "\0";
410         $h{name} = "././\@LongLink";
411         $h{type} = "K";
412         $h{size} = length($data);
413         TarWriteHeader($fh, \%h);
414         TarWrite($fh, \$data);
415         TarWritePad($fh, length($data));
416     }
417
418     #
419     # Handle long file names
420     #
421     if ( length($hdr->{name}) > 99 ) {
422         my %h;
423         my $data = $hdr->{name} . "\0";
424         $h{name} = "././\@LongLink";
425         $h{type} = "L";
426         $h{size} = length($data);
427         TarWriteHeader($fh, \%h);
428         TarWrite($fh, \$data);
429         TarWritePad($fh, length($data));
430     }
431     TarWriteHeader($fh, $hdr);
432 }
433
434 my $Attr;
435 my $AttrDir;
436
437 sub TarWriteFile
438 {
439     my($hdr, $fh, $tarPathOverride) = @_;
440
441     my $tarPath = $hdr->{relPath};
442     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
443
444     $tarPath =~ s{//+}{/}g;
445     if ( defined($PathRemove)
446             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
447         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
448     }
449     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
450     $tarPath =~ s{//+}{/}g;
451     $hdr->{name} = $tarPath;
452
453     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
454         #
455         # Directory: just write the header
456         #
457         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
458         TarWriteFileInfo($fh, $hdr);
459         $DirCnt++;
460     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
461         my($data, $size);
462         #
463         # Regular file: write the header and file
464         #
465         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
466         if ( !defined($f) ) {
467             print(STDERR "Unable to open file $hdr->{fullPath}\n");
468             $ErrorCnt++;
469             return;
470         }
471         TarWriteFileInfo($fh, $hdr);
472         if ( $opts{l} || $opts{L} ) {
473             $size = $hdr->{size};
474         } else {
475             while ( $f->read(\$data, $BufSize) > 0 ) {
476                 if ( $size + length($data) > $hdr->{size} ) {
477                     print(STDERR "Error: truncating $hdr->{fullPath} to"
478                                . " $hdr->{size} bytes\n");
479                     $data = substr($data, 0, $hdr->{size} - $size);
480                     $ErrorCnt++;
481                 }
482                 TarWrite($fh, \$data);
483                 $size += length($data);
484             }
485             $f->close;
486             if ( $size != $hdr->{size} ) {
487                 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
488                            . " bytes from $size bytes\n");
489                 $ErrorCnt++;
490                 while ( $size < $hdr->{size} ) {
491                     my $len = $hdr->{size} - $size;
492                     $len = $BufSize if ( $len > $BufSize );
493                     $data = "\0" x $len;
494                     TarWrite($fh, \$data);
495                     $size += $len;
496                 }
497             }
498             TarWritePad($fh, $size);
499         }
500         $FileCnt++;
501         $ByteCnt += $size;
502     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
503         #
504         # Hardlink file: either write a hardlink or the complete file
505         # depending upon whether the linked-to file will be written
506         # to the archive.
507         #
508         # Start by reading the contents of the link.
509         #
510         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
511         if ( !defined($f) ) {
512             print(STDERR "Unable to open file $hdr->{fullPath}\n");
513             $ErrorCnt++;
514             return;
515         }
516         my $data;
517         while ( $f->read(\$data, $BufSize) > 0 ) {
518             $hdr->{linkname} .= $data;
519         }
520         $f->close;
521         #
522         # Check @ARGV and the list of hardlinked files we have explicity
523         # dumped to see if we have dumped this file or not
524         #
525         my $done = 0;
526         my $name = $hdr->{linkname};
527         $name =~ s{^\./}{/};
528         if ( defined($HardLinkExtraFiles{$name}) ) {
529             $done = 1;
530         } else {
531             foreach my $arg ( @ARGV ) {
532                 $arg = "/" if ( $arg eq "." );
533                 $arg =~ s{^\./+}{/};
534                 $arg =~ s{/+$}{};
535                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
536             }
537         }
538         if ( $done ) {
539             #
540             # Target file will be or was written, so just remember
541             # the hardlink so we can dump it later.
542             #
543             push(@HardLinks, $hdr);
544             $SpecialCnt++;
545         } else {
546             #
547             # Have to dump the original file.  Just call the top-level
548             # routine, so that we save the hassle of dealing with
549             # mangling, merging and attributes.
550             #
551             my $name = $hdr->{linkname};
552             $name =~ s{^\./}{/};
553             $HardLinkExtraFiles{$name} = $hdr->{name};
554             archiveWrite($fh, $name, $hdr->{name});
555         }
556     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
557         #
558         # Symbolic link: read the symbolic link contents into the header
559         # and write the header.
560         #
561         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
562         if ( !defined($f) ) {
563             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
564             $ErrorCnt++;
565             return;
566         }
567         my $data;
568         while ( $f->read(\$data, $BufSize) > 0 ) {
569             $hdr->{linkname} .= $data;
570         }
571         $f->close;
572         $hdr->{size} = 0;
573         TarWriteFileInfo($fh, $hdr);
574         $SpecialCnt++;
575     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
576            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
577            || $hdr->{type} == BPC_FTYPE_FIFO ) {
578         #
579         # Special files: for char and block special we read the
580         # major and minor numbers from a plain file.
581         #
582         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
583             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
584                                                 $hdr->{compress});
585             my $data;
586             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
587                 print(STDERR "Unable to open/read char/block special file"
588                            . " $hdr->{fullPath}\n");
589                 $f->close if ( defined($f) );
590                 $ErrorCnt++;
591                 return;
592             }
593             $f->close;
594             if ( $data =~ /(\d+),(\d+)/ ) {
595                 $hdr->{devmajor} = $1;
596                 $hdr->{devminor} = $2;
597             }
598         }
599         $hdr->{size} = 0;
600         TarWriteFileInfo($fh, $hdr);
601         $SpecialCnt++;
602     } else {
603         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
604         $ErrorCnt++;
605     }
606 }