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)
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-2003 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.1.0beta0, released 3 Sep 2007.
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 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
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);
190 # Finish with two null 512 byte headers, and then round out a full
193 my $data = "\0" x ($tar_header_length * 2);
194 TarWrite($fh, \$data);
195 TarWrite($fh, undef);
198 # print out totals if requested
201 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
202 " $SpecialCnt specials, $ErrorCnt errors\n";
204 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
206 # Got errors, with no files or directories; exit with non-zero
213 ###########################################################################
215 ###########################################################################
219 my($fh, $dir, $tarPathOverride) = @_;
221 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
222 print(STDERR "$0: bad directory '$dir'\n");
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");
237 # Write out any hardlinks (if any)
239 sub archiveWriteHardLinks
242 foreach my $hdr ( @HardLinks ) {
244 my $name = $hdr->{linkname};
246 if ( defined($HardLinkExtraFiles{$name}) ) {
247 $hdr->{linkname} = $HardLinkExtraFiles{$name};
249 if ( defined($PathRemove)
250 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
251 eq ".$PathRemove" ) {
252 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
254 TarWriteFileInfo($fh, $hdr);
257 %HardLinkExtraFiles = ();
264 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
265 return $UidCache{$uid};
272 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
273 return $GidCache{$gid};
278 my($fh, $dataRef) = @_;
280 if ( !defined($dataRef) ) {
282 # do flush by padding to a full $WriteBufSz
284 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
287 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
289 # just buffer and return
291 $WriteBuf .= $$dataRef;
294 my $done = $WriteBufSz - length($WriteBuf);
295 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
297 print(STDERR "Unable to write to output file ($!)\n");
300 while ( $done + $WriteBufSz <= length($$dataRef) ) {
301 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
303 print(STDERR "Unable to write to output file ($!)\n");
306 $done += $WriteBufSz;
308 $WriteBuf = substr($$dataRef, $done);
315 if ( $size % $tar_header_length ) {
316 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
317 TarWrite($fh, \$data);
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})
329 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
332 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
334 # GNU extension for files >= 8GB: send size in big-endian binary
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 ) {
341 # sprintf octal only handles up to 2^32 - 1
343 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
344 . sprintf("%08o", $hdr->{size} % (1 << 24));
346 $sizeStr = sprintf("%011o", $hdr->{size});
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}),
354 sprintf("%011o", $hdr->{mtime}),
355 "", #checksum field - space padded by pack("A8")
357 substr($hdr->{linkname}, 0, 99),
358 $hdr->{magic} || 'ustar ',
359 $hdr->{version} || ' ',
366 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
367 TarWrite($fh, \$data);
375 # Convert path names to requested (eg: client) charset
377 if ( $Charset ne "" ) {
378 from_to($hdr->{name}, "utf8", $Charset);
379 from_to($hdr->{linkname}, "utf8", $Charset);
383 print($hdr->{name} . "\n");
385 } elsif ( $opts{L} ) {
386 my $owner = "$hdr->{uid}/$hdr->{gid}";
388 my $name = $hdr->{name};
390 if ( $hdr->{type} == BPC_FTYPE_SYMLINK
391 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
392 $name .= " -> $hdr->{linkname}";
396 printf("%6o %9s %11.0f %s\n",
405 # Handle long link names (symbolic links)
407 if ( length($hdr->{linkname}) > 99 ) {
409 my $data = $hdr->{linkname} . "\0";
410 $h{name} = "././\@LongLink";
412 $h{size} = length($data);
413 TarWriteHeader($fh, \%h);
414 TarWrite($fh, \$data);
415 TarWritePad($fh, length($data));
419 # Handle long file names
421 if ( length($hdr->{name}) > 99 ) {
423 my $data = $hdr->{name} . "\0";
424 $h{name} = "././\@LongLink";
426 $h{size} = length($data);
427 TarWriteHeader($fh, \%h);
428 TarWrite($fh, \$data);
429 TarWritePad($fh, length($data));
431 TarWriteHeader($fh, $hdr);
439 my($hdr, $fh, $tarPathOverride) = @_;
441 my $tarPath = $hdr->{relPath};
442 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
444 $tarPath =~ s{//+}{/}g;
445 if ( defined($PathRemove)
446 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
447 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
449 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
450 $tarPath =~ s{//+}{/}g;
451 $hdr->{name} = $tarPath;
453 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
455 # Directory: just write the header
457 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
458 TarWriteFileInfo($fh, $hdr);
460 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
463 # Regular file: write the header and file
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");
471 TarWriteFileInfo($fh, $hdr);
472 if ( $opts{l} || $opts{L} ) {
473 $size = $hdr->{size};
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);
482 TarWrite($fh, \$data);
483 $size += length($data);
486 if ( $size != $hdr->{size} ) {
487 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
488 . " bytes from $size bytes\n");
490 while ( $size < $hdr->{size} ) {
491 my $len = $hdr->{size} - $size;
492 $len = $BufSize if ( $len > $BufSize );
494 TarWrite($fh, \$data);
498 TarWritePad($fh, $size);
502 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
504 # Hardlink file: either write a hardlink or the complete file
505 # depending upon whether the linked-to file will be written
508 # Start by reading the contents of the link.
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");
517 while ( $f->read(\$data, $BufSize) > 0 ) {
518 $hdr->{linkname} .= $data;
522 # Check @ARGV and the list of hardlinked files we have explicity
523 # dumped to see if we have dumped this file or not
526 my $name = $hdr->{linkname};
528 if ( defined($HardLinkExtraFiles{$name}) ) {
531 foreach my $arg ( @ARGV ) {
532 $arg = "/" if ( $arg eq "." );
535 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
540 # Target file will be or was written, so just remember
541 # the hardlink so we can dump it later.
543 push(@HardLinks, $hdr);
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.
551 my $name = $hdr->{linkname};
553 $HardLinkExtraFiles{$name} = $hdr->{name};
554 archiveWrite($fh, $name, $hdr->{name});
556 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
558 # Symbolic link: read the symbolic link contents into the header
559 # and write the header.
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");
568 while ( $f->read(\$data, $BufSize) > 0 ) {
569 $hdr->{linkname} .= $data;
573 TarWriteFileInfo($fh, $hdr);
575 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
576 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
577 || $hdr->{type} == BPC_FTYPE_FIFO ) {
579 # Special files: for char and block special we read the
580 # major and minor numbers from a plain file.
582 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
583 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
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) );
594 if ( $data =~ /(\d+),(\d+)/ ) {
595 $hdr->{devmajor} = $1;
596 $hdr->{devminor} = $2;
600 TarWriteFileInfo($fh, $hdr);
603 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");