2 #============================================================= -*-perl-*-
4 # BackupPC_tarCreate: create a tar archive of an existing dump
5 # for restore on a client.
9 # Usage: BackupPC_tarCreate [options] files/directories...
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.
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)
29 # The -h, -n and -s options specify which dump is used to generate
30 # the tar archive. The -r and -p options can be used to relocate
31 # the paths in the tar archive so extracted files can be placed
32 # in a location different from their original location.
35 # Craig Barratt <cbarratt@users.sourceforge.net>
38 # Copyright (C) 2001-2003 Craig Barratt
40 # This program is free software; you can redistribute it and/or modify
41 # it under the terms of the GNU General Public License as published by
42 # the Free Software Foundation; either version 2 of the License, or
43 # (at your option) any later version.
45 # This program is distributed in the hope that it will be useful,
46 # but WITHOUT ANY WARRANTY; without even the implied warranty of
47 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48 # GNU General Public License for more details.
50 # You should have received a copy of the GNU General Public License
51 # along with this program; if not, write to the Free Software
52 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
54 #========================================================================
56 # Version 3.0.0beta2, released 11 Nov 2006.
58 # See http://backuppc.sourceforge.net.
60 #========================================================================
64 use lib "/usr/local/BackupPC/lib";
67 use Encode qw/from_to/;
69 use BackupPC::Attrib qw(:all);
70 use BackupPC::FileZIO;
73 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
77 if ( !getopts("te:h:n:p:r:s:b:w:", \%opts) || @ARGV < 1 ) {
79 usage: $0 [options] files/directories...
81 -h host host from which the tar archive is created
82 -n dumpNum dump number from which the tar archive is created
83 A negative number means relative to the end (eg -1
84 means the most recent dump, -2 2nd most recent etc).
85 -s shareName share name from which the tar archive is created
88 -t print summary totals
89 -r pathRemove path prefix that will be replaced with pathAdd
90 -p pathAdd new path prefix
91 -b BLOCKS BLOCKS x 512 bytes per record (default 20; same as tar)
92 -w writeBufSz write buffer size (default 1048576 = 1MB)
93 -e charset charset for encoding file names (default: value of
94 \$Conf{ClientCharset} when backup was done)
99 if ( $opts{h} !~ /^([\w\.\s-]+)$/
100 || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
101 print(STDERR "$0: bad host name '$opts{h}'\n");
106 if ( $opts{n} !~ /^(-?\d+)$/ ) {
107 print(STDERR "$0: bad dump number '$opts{n}'\n");
112 my @Backups = $bpc->BackupInfoRead($Host);
120 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
121 for ( $i = 0 ; $i < @Backups ; $i++ ) {
122 last if ( $Backups[$i]{num} == $Num );
124 if ( $i >= @Backups ) {
125 print(STDERR "$0: bad backup number $Num for host $Host\n");
129 my $Charset = $Backups[$i]{charset};
130 $Charset = $opts{e} if ( $opts{e} ne "" );
132 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
133 my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
134 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
135 print(STDERR "$0: bad share name '$opts{s}'\n");
139 our $ShareName = $opts{s};
140 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
143 # This constant and the line of code below that uses it are borrowed
144 # from Archive::Tar. Thanks to Calle Dybedahl and Stephen Zander.
147 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
148 # Copyright 1998 Stephen Zander. All rights reserved.
151 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
152 my $tar_header_length = 512;
154 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
156 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
158 my(%UidCache, %GidCache);
159 my(%HardLinkExtraFiles, @HardLinks);
162 # Write out all the requested files/directories
166 if ( $ShareName eq "*" ) {
167 my $PathRemoveOrig = $PathRemove;
168 my $PathAddOrig = $PathAdd;
169 foreach $ShareName ( $view->shareList($Num) ) {
170 #print(STDERR "Doing share ($ShareName)\n");
171 $PathRemove = "/" if ( !defined($PathRemoveOrig) );
172 ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
173 foreach my $dir ( @ARGV ) {
174 archiveWrite($fh, $dir);
176 archiveWriteHardLinks($fh);
179 foreach my $dir ( @ARGV ) {
180 archiveWrite($fh, $dir);
182 archiveWriteHardLinks($fh);
186 # Finish with two null 512 byte headers, and then round out a full
189 my $data = "\0" x ($tar_header_length * 2);
190 TarWrite($fh, \$data);
191 TarWrite($fh, undef);
194 # print out totals if requested
197 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
198 " $SpecialCnt specials, $ErrorCnt errors\n";
200 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
202 # Got errors, with no files or directories; exit with non-zero
209 ###########################################################################
211 ###########################################################################
215 my($fh, $dir, $tarPathOverride) = @_;
217 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
218 print(STDERR "$0: bad directory '$dir'\n");
222 $dir = "/" if ( $dir eq "." );
223 #print(STDERR "calling find with $Num, $ShareName, $dir\n");
224 if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
225 $fh, $tarPathOverride) < 0 ) {
226 print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
233 # Write out any hardlinks (if any)
235 sub archiveWriteHardLinks
238 foreach my $hdr ( @HardLinks ) {
240 my $name = $hdr->{linkname};
242 if ( defined($HardLinkExtraFiles{$name}) ) {
243 $hdr->{linkname} = $HardLinkExtraFiles{$name};
245 if ( defined($PathRemove)
246 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
247 eq ".$PathRemove" ) {
248 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
250 TarWriteFileInfo($fh, $hdr);
253 %HardLinkExtraFiles = ();
260 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
261 return $UidCache{$uid};
268 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
269 return $GidCache{$gid};
274 my($fh, $dataRef) = @_;
276 if ( !defined($dataRef) ) {
278 # do flush by padding to a full $WriteBufSz
280 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
283 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
285 # just buffer and return
287 $WriteBuf .= $$dataRef;
290 my $done = $WriteBufSz - length($WriteBuf);
291 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
293 print(STDERR "Unable to write to output file ($!)\n");
296 while ( $done + $WriteBufSz <= length($$dataRef) ) {
297 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
299 print(STDERR "Unable to write to output file ($!)\n");
302 $done += $WriteBufSz;
304 $WriteBuf = substr($$dataRef, $done);
311 if ( $size % $tar_header_length ) {
312 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
313 TarWrite($fh, \$data);
321 $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
322 $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
323 my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
325 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
328 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
330 # GNU extension for files >= 8GB: send size in big-endian binary
332 $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
333 $hdr->{size} / (65536 * 65536),
334 $hdr->{size} % (65536 * 65536));
335 } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
337 # sprintf octal only handles up to 2^32 - 1
339 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
340 . sprintf("%08o", $hdr->{size} % (1 << 24));
342 $sizeStr = sprintf("%011o", $hdr->{size});
344 my $data = pack($tar_pack_header,
345 substr($hdr->{name}, 0, 99),
346 sprintf("%07o", $hdr->{mode}),
347 sprintf("%07o", $hdr->{uid}),
348 sprintf("%07o", $hdr->{gid}),
350 sprintf("%011o", $hdr->{mtime}),
351 "", #checksum field - space padded by pack("A8")
353 substr($hdr->{linkname}, 0, 99),
354 $hdr->{magic} || 'ustar ',
355 $hdr->{version} || ' ',
362 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
363 TarWrite($fh, \$data);
371 # Convert path names to requested (eg: client) charset
373 if ( $Charset ne "" ) {
374 from_to($hdr->{name}, "utf8", $Charset);
375 from_to($hdr->{linkname}, "utf8", $Charset);
379 # Handle long link names (symbolic links)
381 if ( length($hdr->{linkname}) > 99 ) {
383 my $data = $hdr->{linkname} . "\0";
384 $h{name} = "././\@LongLink";
386 $h{size} = length($data);
387 TarWriteHeader($fh, \%h);
388 TarWrite($fh, \$data);
389 TarWritePad($fh, length($data));
393 # Handle long file names
395 if ( length($hdr->{name}) > 99 ) {
397 my $data = $hdr->{name} . "\0";
398 $h{name} = "././\@LongLink";
400 $h{size} = length($data);
401 TarWriteHeader($fh, \%h);
402 TarWrite($fh, \$data);
403 TarWritePad($fh, length($data));
405 TarWriteHeader($fh, $hdr);
413 my($hdr, $fh, $tarPathOverride) = @_;
415 my $tarPath = $hdr->{relPath};
416 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
418 $tarPath =~ s{//+}{/}g;
419 if ( defined($PathRemove)
420 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
421 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
423 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
424 $tarPath =~ s{//+}{/}g;
425 $hdr->{name} = $tarPath;
427 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
429 # Directory: just write the header
431 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
432 TarWriteFileInfo($fh, $hdr);
434 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
436 # Regular file: write the header and file
438 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
439 if ( !defined($f) ) {
440 print(STDERR "Unable to open file $hdr->{fullPath}\n");
444 TarWriteFileInfo($fh, $hdr);
446 while ( $f->read(\$data, $BufSize) > 0 ) {
447 if ( $size + length($data) > $hdr->{size} ) {
448 print(STDERR "Error: truncating $hdr->{fullPath} to"
449 . " $hdr->{size} bytes\n");
450 $data = substr($data, 0, $hdr->{size} - $size);
453 TarWrite($fh, \$data);
454 $size += length($data);
457 if ( $size != $hdr->{size} ) {
458 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
459 . " bytes from $size bytes\n");
461 while ( $size < $hdr->{size} ) {
462 my $len = $hdr->{size} - $size;
463 $len = $BufSize if ( $len > $BufSize );
465 TarWrite($fh, \$data);
469 TarWritePad($fh, $size);
472 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
474 # Hardlink file: either write a hardlink or the complete file
475 # depending upon whether the linked-to file will be written
478 # Start by reading the contents of the link.
480 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
481 if ( !defined($f) ) {
482 print(STDERR "Unable to open file $hdr->{fullPath}\n");
487 while ( $f->read(\$data, $BufSize) > 0 ) {
488 $hdr->{linkname} .= $data;
492 # Check @ARGV and the list of hardlinked files we have explicity
493 # dumped to see if we have dumped this file or not
496 my $name = $hdr->{linkname};
498 if ( defined($HardLinkExtraFiles{$name}) ) {
501 foreach my $arg ( @ARGV ) {
502 $arg = "/" if ( $arg eq "." );
505 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
510 # Target file will be or was written, so just remember
511 # the hardlink so we can dump it later.
513 push(@HardLinks, $hdr);
517 # Have to dump the original file. Just call the top-level
518 # routine, so that we save the hassle of dealing with
519 # mangling, merging and attributes.
521 my $name = $hdr->{linkname};
523 $HardLinkExtraFiles{$name} = $hdr->{name};
524 archiveWrite($fh, $name, $hdr->{name});
526 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
528 # Symbolic link: read the symbolic link contents into the header
529 # and write the header.
531 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
532 if ( !defined($f) ) {
533 print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
538 while ( $f->read(\$data, $BufSize) > 0 ) {
539 $hdr->{linkname} .= $data;
543 TarWriteFileInfo($fh, $hdr);
545 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
546 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
547 || $hdr->{type} == BPC_FTYPE_FIFO ) {
549 # Special files: for char and block special we read the
550 # major and minor numbers from a plain file.
552 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
553 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
556 if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
557 print(STDERR "Unable to open/read char/block special file"
558 . " $hdr->{fullPath}\n");
559 $f->close if ( defined($f) );
564 if ( $data =~ /(\d+),(\d+)/ ) {
565 $hdr->{devmajor} = $1;
566 $hdr->{devminor} = $2;
570 TarWriteFileInfo($fh, $hdr);
573 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");