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 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
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.
37 # Craig Barratt <cbarratt@users.sourceforge.net>
40 # Copyright (C) 2001-2009 Craig Barratt
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.
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.
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
56 #========================================================================
58 # Version 3.2.0, released 31 Jul 2010.
60 # See http://backuppc.sourceforge.net.
62 #========================================================================
66 use lib "/usr/local/BackupPC/lib";
69 use Encode qw/from_to/;
71 use BackupPC::Attrib qw(:all);
72 use BackupPC::FileZIO;
75 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
79 if ( !getopts("Llte:h:n:p:r:s:b:w:", \%opts) || @ARGV < 1 ) {
81 usage: $0 [options] files/directories...
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
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
103 if ( $opts{h} !~ /^([\w\.\s-]+)$/
104 || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
105 print(STDERR "$0: bad host name '$opts{h}'\n");
110 if ( $opts{n} !~ /^(-?\d+)$/ ) {
111 print(STDERR "$0: bad dump number '$opts{n}'\n");
116 my @Backups = $bpc->BackupInfoRead($Host);
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 );
128 if ( $i >= @Backups ) {
129 print(STDERR "$0: bad backup number $Num for host $Host\n");
133 my $Charset = $Backups[$i]{charset};
134 $Charset = $opts{e} if ( $opts{e} ne "" );
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");
143 our $ShareName = $opts{s};
144 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
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.
151 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
152 # Copyright 1998 Stephen Zander. All rights reserved.
155 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
156 my $tar_header_length = 512;
158 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
160 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
162 my(%UidCache, %GidCache);
163 my(%HardLinkExtraFiles, @HardLinks);
166 # Write out all the requested files/directories
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);
180 archiveWriteHardLinks($fh);
183 foreach my $dir ( @ARGV ) {
184 archiveWrite($fh, $dir);
186 archiveWriteHardLinks($fh);
189 if ( !$opts{l} && !$opts{L} ) {
191 # Finish with two null 512 byte headers, and then round out a full
194 my $data = "\0" x ($tar_header_length * 2);
195 TarWrite($fh, \$data);
196 TarWrite($fh, undef);
200 # print out totals if requested
203 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
204 " $SpecialCnt specials, $ErrorCnt errors\n";
206 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
208 # Got errors, with no files or directories; exit with non-zero
215 ###########################################################################
217 ###########################################################################
221 my($fh, $dir, $tarPathOverride) = @_;
223 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
224 print(STDERR "$0: bad directory '$dir'\n");
228 $dir = "/" if ( $dir eq "." );
229 #print(STDERR "calling find with $Num, $ShareName, $dir\n");
230 if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
231 $fh, $tarPathOverride) < 0 ) {
232 print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
239 # Write out any hardlinks (if any)
241 sub archiveWriteHardLinks
244 foreach my $hdr ( @HardLinks ) {
246 my $name = $hdr->{linkname};
248 if ( defined($HardLinkExtraFiles{$name}) ) {
249 $hdr->{linkname} = $HardLinkExtraFiles{$name};
251 if ( defined($PathRemove)
252 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
253 eq ".$PathRemove" ) {
254 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
256 TarWriteFileInfo($fh, $hdr);
259 %HardLinkExtraFiles = ();
266 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
267 return $UidCache{$uid};
274 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
275 return $GidCache{$gid};
280 my($fh, $dataRef) = @_;
282 if ( !defined($dataRef) ) {
284 # do flush by padding to a full $WriteBufSz
286 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
289 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
291 # just buffer and return
293 $WriteBuf .= $$dataRef;
296 my $done = $WriteBufSz - length($WriteBuf);
297 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
299 print(STDERR "Unable to write to output file ($!)\n");
302 while ( $done + $WriteBufSz <= length($$dataRef) ) {
303 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
305 print(STDERR "Unable to write to output file ($!)\n");
308 $done += $WriteBufSz;
310 $WriteBuf = substr($$dataRef, $done);
317 if ( $size % $tar_header_length ) {
318 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
319 TarWrite($fh, \$data);
327 $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
328 $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
329 my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
331 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
334 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
336 # GNU extension for files >= 8GB: send size in big-endian binary
338 $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
339 $hdr->{size} / (65536 * 65536),
340 $hdr->{size} % (65536 * 65536));
341 } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
343 # sprintf octal only handles up to 2^32 - 1
345 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
346 . sprintf("%08o", $hdr->{size} % (1 << 24));
348 $sizeStr = sprintf("%011o", $hdr->{size});
350 my $data = pack($tar_pack_header,
351 substr($hdr->{name}, 0, 99),
352 sprintf("%07o", $hdr->{mode}),
353 sprintf("%07o", $hdr->{uid}),
354 sprintf("%07o", $hdr->{gid}),
356 sprintf("%011o", $hdr->{mtime}),
357 "", #checksum field - space padded by pack("A8")
359 substr($hdr->{linkname}, 0, 99),
360 $hdr->{magic} || 'ustar ',
361 $hdr->{version} || ' ',
368 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
369 TarWrite($fh, \$data);
377 # Convert path names to requested (eg: client) charset
379 if ( $Charset ne "" ) {
380 from_to($hdr->{name}, "utf8", $Charset);
381 from_to($hdr->{linkname}, "utf8", $Charset);
385 print($hdr->{name} . "\n");
387 } elsif ( $opts{L} ) {
388 my $owner = "$hdr->{uid}/$hdr->{gid}";
390 my $name = $hdr->{name};
392 if ( $hdr->{type} == BPC_FTYPE_SYMLINK
393 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
394 $name .= " -> $hdr->{linkname}";
398 printf("%6o %9s %11.0f %s\n",
407 # Handle long link names (symbolic links)
409 if ( length($hdr->{linkname}) > 99 ) {
411 my $data = $hdr->{linkname} . "\0";
412 $h{name} = "././\@LongLink";
414 $h{size} = length($data);
415 TarWriteHeader($fh, \%h);
416 TarWrite($fh, \$data);
417 TarWritePad($fh, length($data));
421 # Handle long file names
423 if ( length($hdr->{name}) > 99 ) {
425 my $data = $hdr->{name} . "\0";
426 $h{name} = "././\@LongLink";
428 $h{size} = length($data);
429 TarWriteHeader($fh, \%h);
430 TarWrite($fh, \$data);
431 TarWritePad($fh, length($data));
433 TarWriteHeader($fh, $hdr);
441 my($hdr, $fh, $tarPathOverride) = @_;
443 my $tarPath = $hdr->{relPath};
444 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
446 $tarPath =~ s{//+}{/}g;
447 if ( defined($PathRemove)
448 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
449 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
451 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
452 $tarPath =~ s{//+}{/}g;
453 $hdr->{name} = $tarPath;
455 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
457 # Directory: just write the header
459 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
460 TarWriteFileInfo($fh, $hdr);
462 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
465 # Regular file: write the header and file
467 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
468 if ( !defined($f) ) {
469 print(STDERR "Unable to open file $hdr->{fullPath}\n");
473 TarWriteFileInfo($fh, $hdr);
474 if ( $opts{l} || $opts{L} ) {
475 $size = $hdr->{size};
477 while ( $f->read(\$data, $BufSize) > 0 ) {
478 if ( $size + length($data) > $hdr->{size} ) {
479 print(STDERR "Error: truncating $hdr->{fullPath} to"
480 . " $hdr->{size} bytes\n");
481 $data = substr($data, 0, $hdr->{size} - $size);
484 TarWrite($fh, \$data);
485 $size += length($data);
488 if ( $size != $hdr->{size} ) {
489 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
490 . " bytes from $size bytes\n");
492 while ( $size < $hdr->{size} ) {
493 my $len = $hdr->{size} - $size;
494 $len = $BufSize if ( $len > $BufSize );
496 TarWrite($fh, \$data);
500 TarWritePad($fh, $size);
504 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
506 # Hardlink file: either write a hardlink or the complete file
507 # depending upon whether the linked-to file will be written
510 # Start by reading the contents of the link.
512 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
513 if ( !defined($f) ) {
514 print(STDERR "Unable to open file $hdr->{fullPath}\n");
519 while ( $f->read(\$data, $BufSize) > 0 ) {
520 $hdr->{linkname} .= $data;
524 # Check @ARGV and the list of hardlinked files we have explicity
525 # dumped to see if we have dumped this file or not
528 my $name = $hdr->{linkname};
530 if ( defined($HardLinkExtraFiles{$name}) ) {
533 foreach my $arg ( @ARGV ) {
534 $arg = "/" if ( $arg eq "." );
537 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
542 # Target file will be or was written, so just remember
543 # the hardlink so we can dump it later.
545 push(@HardLinks, $hdr);
549 # Have to dump the original file. Just call the top-level
550 # routine, so that we save the hassle of dealing with
551 # mangling, merging and attributes.
553 my $name = $hdr->{linkname};
555 $HardLinkExtraFiles{$name} = $hdr->{name};
556 archiveWrite($fh, $name, $hdr->{name});
558 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
560 # Symbolic link: read the symbolic link contents into the header
561 # and write the header.
563 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
564 if ( !defined($f) ) {
565 print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
570 while ( $f->read(\$data, $BufSize) > 0 ) {
571 $hdr->{linkname} .= $data;
575 TarWriteFileInfo($fh, $hdr);
577 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
578 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
579 || $hdr->{type} == BPC_FTYPE_FIFO ) {
581 # Special files: for char and block special we read the
582 # major and minor numbers from a plain file.
584 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
585 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
588 if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
589 print(STDERR "Unable to open/read char/block special file"
590 . " $hdr->{fullPath}\n");
591 $f->close if ( defined($f) );
596 if ( $data =~ /(\d+),(\d+)/ ) {
597 $hdr->{devmajor} = $1;
598 $hdr->{devminor} = $2;
602 TarWriteFileInfo($fh, $hdr);
604 } elsif ( $hdr->{type} == BPC_FTYPE_SOCKET
605 || $hdr->{type} == BPC_FTYPE_UNKNOWN ) {
607 # ignore these two file types - these are dynamic file types created
608 # by applications as needed
611 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");