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:i", \%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
99 -i create incremental tar dump with just new files
104 if ( $opts{h} !~ /^([\w\.\s-]+)$/
105 || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
106 print(STDERR "$0: bad host name '$opts{h}'\n");
111 if ( $opts{n} !~ /^(-?\d+)$/ ) {
112 print(STDERR "$0: bad dump number '$opts{n}'\n");
117 my @Backups = $bpc->BackupInfoRead($Host);
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 );
129 if ( $i >= @Backups ) {
130 print(STDERR "$0: bad backup number $Num for host $Host\n");
134 my $Charset = $Backups[$i]{charset};
135 $Charset = $opts{e} if ( $opts{e} ne "" );
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");
144 # XXX ASA Search extension
147 my %Conf = $bpc->Conf;
148 if ( $Conf{TarCreateIncremental} || $opts{i} ) {
149 warn "# incremental dump";
150 $view_opts = { only_increment => 1 };
153 our $ShareName = $opts{s};
154 our $view = BackupPC::View->new($bpc, $Host, \@Backups, $view_opts);
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.
161 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
162 # Copyright 1998 Stephen Zander. All rights reserved.
165 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
166 my $tar_header_length = 512;
168 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
170 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
172 my(%UidCache, %GidCache);
173 my(%HardLinkExtraFiles, @HardLinks);
176 # Write out all the requested files/directories
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);
190 archiveWriteHardLinks($fh);
193 foreach my $dir ( @ARGV ) {
194 archiveWrite($fh, $dir);
196 archiveWriteHardLinks($fh);
199 if ( !$opts{l} && !$opts{L} ) {
201 # Finish with two null 512 byte headers, and then round out a full
204 my $data = "\0" x ($tar_header_length * 2);
205 TarWrite($fh, \$data);
206 TarWrite($fh, undef);
210 # print out totals if requested
213 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
214 " $SpecialCnt specials, $ErrorCnt errors\n";
216 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
218 # Got errors, with no files or directories; exit with non-zero
225 ###########################################################################
227 ###########################################################################
231 my($fh, $dir, $tarPathOverride) = @_;
233 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
234 print(STDERR "$0: bad directory '$dir'\n");
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");
249 # Write out any hardlinks (if any)
251 sub archiveWriteHardLinks
254 foreach my $hdr ( @HardLinks ) {
256 my $name = $hdr->{linkname};
258 if ( defined($HardLinkExtraFiles{$name}) ) {
259 $hdr->{linkname} = $HardLinkExtraFiles{$name};
261 if ( defined($PathRemove)
262 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
263 eq ".$PathRemove" ) {
264 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
266 TarWriteFileInfo($fh, $hdr);
269 %HardLinkExtraFiles = ();
276 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
277 return $UidCache{$uid};
284 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
285 return $GidCache{$gid};
290 my($fh, $dataRef) = @_;
292 if ( !defined($dataRef) ) {
294 # do flush by padding to a full $WriteBufSz
296 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
299 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
301 # just buffer and return
303 $WriteBuf .= $$dataRef;
306 my $done = $WriteBufSz - length($WriteBuf);
307 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
309 print(STDERR "Unable to write to output file ($!)\n");
312 while ( $done + $WriteBufSz <= length($$dataRef) ) {
313 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
315 print(STDERR "Unable to write to output file ($!)\n");
318 $done += $WriteBufSz;
320 $WriteBuf = substr($$dataRef, $done);
327 if ( $size % $tar_header_length ) {
328 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
329 TarWrite($fh, \$data);
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})
341 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
344 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
346 # GNU extension for files >= 8GB: send size in big-endian binary
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 ) {
353 # sprintf octal only handles up to 2^32 - 1
355 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
356 . sprintf("%08o", $hdr->{size} % (1 << 24));
358 $sizeStr = sprintf("%011o", $hdr->{size});
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}),
366 sprintf("%011o", $hdr->{mtime}),
367 "", #checksum field - space padded by pack("A8")
369 substr($hdr->{linkname}, 0, 99),
370 $hdr->{magic} || 'ustar ',
371 $hdr->{version} || ' ',
378 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
379 TarWrite($fh, \$data);
387 # Convert path names to requested (eg: client) charset
389 if ( $Charset ne "" ) {
390 from_to($hdr->{name}, "utf8", $Charset);
391 from_to($hdr->{linkname}, "utf8", $Charset);
395 print($hdr->{name} . "\n");
397 } elsif ( $opts{L} ) {
398 my $owner = "$hdr->{uid}/$hdr->{gid}";
400 my $name = $hdr->{name};
402 if ( $hdr->{type} == BPC_FTYPE_SYMLINK
403 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
404 $name .= " -> $hdr->{linkname}";
408 printf("%6o %9s %11.0f %s\n",
417 # Handle long link names (symbolic links)
419 if ( length($hdr->{linkname}) > 99 ) {
421 my $data = $hdr->{linkname} . "\0";
422 $h{name} = "././\@LongLink";
424 $h{size} = length($data);
425 TarWriteHeader($fh, \%h);
426 TarWrite($fh, \$data);
427 TarWritePad($fh, length($data));
431 # Handle long file names
433 if ( length($hdr->{name}) > 99 ) {
435 my $data = $hdr->{name} . "\0";
436 $h{name} = "././\@LongLink";
438 $h{size} = length($data);
439 TarWriteHeader($fh, \%h);
440 TarWrite($fh, \$data);
441 TarWritePad($fh, length($data));
443 TarWriteHeader($fh, $hdr);
451 my($hdr, $fh, $tarPathOverride) = @_;
453 my $tarPath = $hdr->{relPath};
454 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
456 $tarPath =~ s{//+}{/}g;
457 if ( defined($PathRemove)
458 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
459 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
461 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
462 $tarPath =~ s{//+}{/}g;
463 $hdr->{name} = $tarPath;
465 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
467 # Directory: just write the header
469 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
470 TarWriteFileInfo($fh, $hdr);
472 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
475 # Regular file: write the header and file
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");
483 TarWriteFileInfo($fh, $hdr);
484 if ( $opts{l} || $opts{L} ) {
485 $size = $hdr->{size};
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);
494 TarWrite($fh, \$data);
495 $size += length($data);
498 if ( $size != $hdr->{size} ) {
499 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
500 . " bytes from $size bytes\n");
502 while ( $size < $hdr->{size} ) {
503 my $len = $hdr->{size} - $size;
504 $len = $BufSize if ( $len > $BufSize );
506 TarWrite($fh, \$data);
510 TarWritePad($fh, $size);
514 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
516 # Hardlink file: either write a hardlink or the complete file
517 # depending upon whether the linked-to file will be written
520 # Start by reading the contents of the link.
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");
529 while ( $f->read(\$data, $BufSize) > 0 ) {
530 $hdr->{linkname} .= $data;
534 # Check @ARGV and the list of hardlinked files we have explicity
535 # dumped to see if we have dumped this file or not
538 my $name = $hdr->{linkname};
540 if ( defined($HardLinkExtraFiles{$name}) ) {
543 foreach my $arg ( @ARGV ) {
544 $arg = "/" if ( $arg eq "." );
547 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
552 # Target file will be or was written, so just remember
553 # the hardlink so we can dump it later.
555 push(@HardLinks, $hdr);
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.
563 my $name = $hdr->{linkname};
565 $HardLinkExtraFiles{$name} = $hdr->{name};
566 archiveWrite($fh, $name, $hdr->{name});
568 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
570 # Symbolic link: read the symbolic link contents into the header
571 # and write the header.
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");
580 while ( $f->read(\$data, $BufSize) > 0 ) {
581 $hdr->{linkname} .= $data;
585 TarWriteFileInfo($fh, $hdr);
587 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
588 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
589 || $hdr->{type} == BPC_FTYPE_FIFO ) {
591 # Special files: for char and block special we read the
592 # major and minor numbers from a plain file.
594 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
595 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
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) );
606 if ( $data =~ /(\d+),(\d+)/ ) {
607 $hdr->{devmajor} = $1;
608 $hdr->{devminor} = $2;
612 TarWriteFileInfo($fh, $hdr);
614 } elsif ( $hdr->{type} == BPC_FTYPE_SOCKET
615 || $hdr->{type} == BPC_FTYPE_UNKNOWN ) {
617 # ignore these two file types - these are dynamic file types created
618 # by applications as needed
621 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");