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)
27 # The -h, -n and -s options specify which dump is used to generate
28 # the tar archive. The -r and -p options can be used to relocate
29 # the paths in the tar archive so extracted files can be placed
30 # in a location different from their original location.
33 # Craig Barratt <cbarratt@users.sourceforge.net>
36 # Copyright (C) 2001-2003 Craig Barratt
38 # This program is free software; you can redistribute it and/or modify
39 # it under the terms of the GNU General Public License as published by
40 # the Free Software Foundation; either version 2 of the License, or
41 # (at your option) any later version.
43 # This program is distributed in the hope that it will be useful,
44 # but WITHOUT ANY WARRANTY; without even the implied warranty of
45 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 # GNU General Public License for more details.
48 # You should have received a copy of the GNU General Public License
49 # along with this program; if not, write to the Free Software
50 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
52 #========================================================================
54 # Version 2.1.2, released 5 Sep 2005.
56 # See http://backuppc.sourceforge.net.
58 #========================================================================
62 use lib "__INSTALLDIR__/lib";
66 use BackupPC::Attrib qw(:all);
67 use BackupPC::FileZIO;
70 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
71 my $TopDir = $bpc->TopDir();
72 my $BinDir = $bpc->BinDir();
73 my %Conf = $bpc->Conf();
77 if ( !getopts("th: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)
97 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
98 print(STDERR "$0: bad host name '$opts{h}'\n");
103 if ( $opts{n} !~ /^(-?\d+)$/ ) {
104 print(STDERR "$0: bad dump number '$opts{n}'\n");
109 my @Backups = $bpc->BackupInfoRead($Host);
117 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
118 for ( $i = 0 ; $i < @Backups ; $i++ ) {
119 last if ( $Backups[$i]{num} == $Num );
121 if ( $i >= @Backups ) {
122 print(STDERR "$0: bad backup number $Num for host $Host\n");
126 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
127 my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
128 if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ && $opts{s} ne "*" ) {
129 print(STDERR "$0: bad share name '$opts{s}'\n");
132 our $ShareName = $opts{s};
133 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
136 # This constant and the line of code below that uses it are borrowed
137 # from Archive::Tar. Thanks to Calle Dybedahl and Stephen Zander.
140 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
141 # Copyright 1998 Stephen Zander. All rights reserved.
144 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
145 my $tar_header_length = 512;
147 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
149 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
151 my(%UidCache, %GidCache);
152 my(%HardLinkExtraFiles, @HardLinks);
155 # Write out all the requested files/directories
159 if ( $ShareName eq "*" ) {
160 my $PathRemoveOrig = $PathRemove;
161 my $PathAddOrig = $PathAdd;
162 foreach $ShareName ( $view->shareList($Num) ) {
163 #print(STDERR "Doing share ($ShareName)\n");
164 $PathRemove = "/" if ( !defined($PathRemoveOrig) );
165 ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
166 foreach my $dir ( @ARGV ) {
167 archiveWrite($fh, $dir);
169 archiveWriteHardLinks($fh);
172 foreach my $dir ( @ARGV ) {
173 archiveWrite($fh, $dir);
175 archiveWriteHardLinks($fh);
179 # Finish with two null 512 byte headers, and then round out a full
182 my $data = "\0" x ($tar_header_length * 2);
183 TarWrite($fh, \$data);
184 TarWrite($fh, undef);
187 # print out totals if requested
190 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
191 " $SpecialCnt specials, $ErrorCnt errors\n";
193 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
195 # Got errors, with no files or directories; exit with non-zero
202 ###########################################################################
204 ###########################################################################
208 my($fh, $dir, $tarPathOverride) = @_;
210 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
211 print(STDERR "$0: bad directory '$dir'\n");
215 $dir = "/" if ( $dir eq "." );
216 #print(STDERR "calling find with $Num, $ShareName, $dir\n");
217 if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
218 $fh, $tarPathOverride) < 0 ) {
219 print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
226 # Write out any hardlinks (if any)
228 sub archiveWriteHardLinks
231 foreach my $hdr ( @HardLinks ) {
233 my $name = $hdr->{linkname};
235 if ( defined($HardLinkExtraFiles{$name}) ) {
236 $hdr->{linkname} = $HardLinkExtraFiles{$name};
238 if ( defined($PathRemove)
239 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
240 eq ".$PathRemove" ) {
241 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
243 TarWriteFileInfo($fh, $hdr);
246 %HardLinkExtraFiles = ();
253 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
254 return $UidCache{$uid};
261 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
262 return $GidCache{$gid};
267 my($fh, $dataRef) = @_;
269 if ( !defined($dataRef) ) {
271 # do flush by padding to a full $WriteBufSz
273 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
276 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
278 # just buffer and return
280 $WriteBuf .= $$dataRef;
283 my $done = $WriteBufSz - length($WriteBuf);
284 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
286 print(STDERR "Unable to write to output file ($!)\n");
289 while ( $done + $WriteBufSz <= length($$dataRef) ) {
290 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
292 print(STDERR "Unable to write to output file ($!)\n");
295 $done += $WriteBufSz;
297 $WriteBuf = substr($$dataRef, $done);
304 if ( $size % $tar_header_length ) {
305 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
306 TarWrite($fh, \$data);
314 $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
315 $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
316 my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
318 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
321 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
323 # GNU extension for files >= 8GB: send size in big-endian binary
325 $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
326 $hdr->{size} / (65536 * 65536),
327 $hdr->{size} % (65536 * 65536));
328 } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
330 # sprintf octal only handles up to 2^32 - 1
332 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
333 . sprintf("%08o", $hdr->{size} % (1 << 24));
335 $sizeStr = sprintf("%011o", $hdr->{size});
337 my $data = pack($tar_pack_header,
338 substr($hdr->{name}, 0, 99),
339 sprintf("%07o", $hdr->{mode}),
340 sprintf("%07o", $hdr->{uid}),
341 sprintf("%07o", $hdr->{gid}),
343 sprintf("%011o", $hdr->{mtime}),
344 "", #checksum field - space padded by pack("A8")
346 substr($hdr->{linkname}, 0, 99),
347 $hdr->{magic} || 'ustar ',
348 $hdr->{version} || ' ',
355 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
356 TarWrite($fh, \$data);
364 # Handle long link names (symbolic links)
366 if ( length($hdr->{linkname}) > 99 ) {
368 my $data = $hdr->{linkname} . "\0";
369 $h{name} = "././\@LongLink";
371 $h{size} = length($data);
372 TarWriteHeader($fh, \%h);
373 TarWrite($fh, \$data);
374 TarWritePad($fh, length($data));
377 # Handle long file names
379 if ( length($hdr->{name}) > 99 ) {
381 my $data = $hdr->{name} . "\0";
382 $h{name} = "././\@LongLink";
384 $h{size} = length($data);
385 TarWriteHeader($fh, \%h);
386 TarWrite($fh, \$data);
387 TarWritePad($fh, length($data));
389 TarWriteHeader($fh, $hdr);
397 my($hdr, $fh, $tarPathOverride) = @_;
399 my $tarPath = $hdr->{relPath};
400 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
402 $tarPath =~ s{//+}{/}g;
403 if ( defined($PathRemove)
404 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
405 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
407 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
408 $tarPath =~ s{//+}{/}g;
409 $hdr->{name} = $tarPath;
411 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
413 # Directory: just write the header
415 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
416 TarWriteFileInfo($fh, $hdr);
418 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
420 # Regular file: write the header and file
422 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
423 if ( !defined($f) ) {
424 print(STDERR "Unable to open file $hdr->{fullPath}\n");
428 TarWriteFileInfo($fh, $hdr);
430 while ( $f->read(\$data, $BufSize) > 0 ) {
431 if ( $size + length($data) > $hdr->{size} ) {
432 print(STDERR "Error: truncating $hdr->{fullPath} to"
433 . " $hdr->{size} bytes\n");
434 $data = substr($data, 0, $hdr->{size} - $size);
437 TarWrite($fh, \$data);
438 $size += length($data);
441 if ( $size != $hdr->{size} ) {
442 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
443 . " bytes from $size bytes\n");
445 while ( $size < $hdr->{size} ) {
446 my $len = $hdr->{size} - $size;
447 $len = $BufSize if ( $len > $BufSize );
449 TarWrite($fh, \$data);
453 TarWritePad($fh, $size);
456 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
458 # Hardlink file: either write a hardlink or the complete file
459 # depending upon whether the linked-to file will be written
462 # Start by reading the contents of the link.
464 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
465 if ( !defined($f) ) {
466 print(STDERR "Unable to open file $hdr->{fullPath}\n");
471 while ( $f->read(\$data, $BufSize) > 0 ) {
472 $hdr->{linkname} .= $data;
476 # Check @ARGV and the list of hardlinked files we have explicity
477 # dumped to see if we have dumped this file or not
480 my $name = $hdr->{linkname};
482 if ( defined($HardLinkExtraFiles{$name}) ) {
485 foreach my $arg ( @ARGV ) {
486 $arg = "/" if ( $arg eq "." );
489 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
494 # Target file will be or was written, so just remember
495 # the hardlink so we can dump it later.
497 push(@HardLinks, $hdr);
501 # Have to dump the original file. Just call the top-level
502 # routine, so that we save the hassle of dealing with
503 # mangling, merging and attributes.
505 my $name = $hdr->{linkname};
507 $HardLinkExtraFiles{$name} = $hdr->{name};
508 archiveWrite($fh, $name, $hdr->{name});
510 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
512 # Symbolic link: read the symbolic link contents into the header
513 # and write the header.
515 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
516 if ( !defined($f) ) {
517 print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
522 while ( $f->read(\$data, $BufSize) > 0 ) {
523 $hdr->{linkname} .= $data;
527 TarWriteFileInfo($fh, $hdr);
529 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
530 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
531 || $hdr->{type} == BPC_FTYPE_FIFO ) {
533 # Special files: for char and block special we read the
534 # major and minor numbers from a plain file.
536 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
537 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
540 if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
541 print(STDERR "Unable to open/read char/block special file"
542 . " $hdr->{fullPath}\n");
543 $f->close if ( defined($f) );
548 if ( $data =~ /(\d+),(\d+)/ ) {
549 $hdr->{devmajor} = $1;
550 $hdr->{devminor} = $2;
554 TarWriteFileInfo($fh, $hdr);
557 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");