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.0.0, released 28 Jan 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)
101 if ( $opts{h} !~ /^([\w\.\s-]+)$/
102 || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
103 print(STDERR "$0: bad host name '$opts{h}'\n");
108 if ( $opts{n} !~ /^(-?\d+)$/ ) {
109 print(STDERR "$0: bad dump number '$opts{n}'\n");
114 my @Backups = $bpc->BackupInfoRead($Host);
122 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
123 for ( $i = 0 ; $i < @Backups ; $i++ ) {
124 last if ( $Backups[$i]{num} == $Num );
126 if ( $i >= @Backups ) {
127 print(STDERR "$0: bad backup number $Num for host $Host\n");
131 my $Charset = $Backups[$i]{charset};
132 $Charset = $opts{e} if ( $opts{e} ne "" );
134 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
135 my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
136 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
137 print(STDERR "$0: bad share name '$opts{s}'\n");
141 our $ShareName = $opts{s};
142 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
145 # This constant and the line of code below that uses it are borrowed
146 # from Archive::Tar. Thanks to Calle Dybedahl and Stephen Zander.
149 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
150 # Copyright 1998 Stephen Zander. All rights reserved.
153 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
154 my $tar_header_length = 512;
156 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
158 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
160 my(%UidCache, %GidCache);
161 my(%HardLinkExtraFiles, @HardLinks);
164 # Write out all the requested files/directories
168 if ( $ShareName eq "*" ) {
169 my $PathRemoveOrig = $PathRemove;
170 my $PathAddOrig = $PathAdd;
171 foreach $ShareName ( $view->shareList($Num) ) {
172 #print(STDERR "Doing share ($ShareName)\n");
173 $PathRemove = "/" if ( !defined($PathRemoveOrig) );
174 ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
175 foreach my $dir ( @ARGV ) {
176 archiveWrite($fh, $dir);
178 archiveWriteHardLinks($fh);
181 foreach my $dir ( @ARGV ) {
182 archiveWrite($fh, $dir);
184 archiveWriteHardLinks($fh);
188 # Finish with two null 512 byte headers, and then round out a full
191 my $data = "\0" x ($tar_header_length * 2);
192 TarWrite($fh, \$data);
193 TarWrite($fh, undef);
196 # print out totals if requested
199 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
200 " $SpecialCnt specials, $ErrorCnt errors\n";
202 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
204 # Got errors, with no files or directories; exit with non-zero
211 ###########################################################################
213 ###########################################################################
217 my($fh, $dir, $tarPathOverride) = @_;
219 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
220 print(STDERR "$0: bad directory '$dir'\n");
224 $dir = "/" if ( $dir eq "." );
225 #print(STDERR "calling find with $Num, $ShareName, $dir\n");
226 if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
227 $fh, $tarPathOverride) < 0 ) {
228 print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
235 # Write out any hardlinks (if any)
237 sub archiveWriteHardLinks
240 foreach my $hdr ( @HardLinks ) {
242 my $name = $hdr->{linkname};
244 if ( defined($HardLinkExtraFiles{$name}) ) {
245 $hdr->{linkname} = $HardLinkExtraFiles{$name};
247 if ( defined($PathRemove)
248 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
249 eq ".$PathRemove" ) {
250 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
252 TarWriteFileInfo($fh, $hdr);
255 %HardLinkExtraFiles = ();
262 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
263 return $UidCache{$uid};
270 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
271 return $GidCache{$gid};
276 my($fh, $dataRef) = @_;
278 if ( !defined($dataRef) ) {
280 # do flush by padding to a full $WriteBufSz
282 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
285 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
287 # just buffer and return
289 $WriteBuf .= $$dataRef;
292 my $done = $WriteBufSz - length($WriteBuf);
293 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
295 print(STDERR "Unable to write to output file ($!)\n");
298 while ( $done + $WriteBufSz <= length($$dataRef) ) {
299 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
301 print(STDERR "Unable to write to output file ($!)\n");
304 $done += $WriteBufSz;
306 $WriteBuf = substr($$dataRef, $done);
313 if ( $size % $tar_header_length ) {
314 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
315 TarWrite($fh, \$data);
323 $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
324 $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
325 my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
327 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
330 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
332 # GNU extension for files >= 8GB: send size in big-endian binary
334 $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
335 $hdr->{size} / (65536 * 65536),
336 $hdr->{size} % (65536 * 65536));
337 } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
339 # sprintf octal only handles up to 2^32 - 1
341 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
342 . sprintf("%08o", $hdr->{size} % (1 << 24));
344 $sizeStr = sprintf("%011o", $hdr->{size});
346 my $data = pack($tar_pack_header,
347 substr($hdr->{name}, 0, 99),
348 sprintf("%07o", $hdr->{mode}),
349 sprintf("%07o", $hdr->{uid}),
350 sprintf("%07o", $hdr->{gid}),
352 sprintf("%011o", $hdr->{mtime}),
353 "", #checksum field - space padded by pack("A8")
355 substr($hdr->{linkname}, 0, 99),
356 $hdr->{magic} || 'ustar ',
357 $hdr->{version} || ' ',
364 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
365 TarWrite($fh, \$data);
373 # Convert path names to requested (eg: client) charset
375 if ( $Charset ne "" ) {
376 from_to($hdr->{name}, "utf8", $Charset);
377 from_to($hdr->{linkname}, "utf8", $Charset);
381 print($hdr->{name} . "\n");
383 } elsif ( $opts{L} ) {
384 my $owner = "$hdr->{uid}/$hdr->{gid}";
386 my $name = $hdr->{name};
388 if ( $hdr->{type} == BPC_FTYPE_SYMLINK
389 || $hdr->{type} == BPC_FTYPE_HARDLINK ) {
390 $name .= " -> $hdr->{linkname}";
394 printf("%6o %9s %11.0f %s\n",
403 # Handle long link names (symbolic links)
405 if ( length($hdr->{linkname}) > 99 ) {
407 my $data = $hdr->{linkname} . "\0";
408 $h{name} = "././\@LongLink";
410 $h{size} = length($data);
411 TarWriteHeader($fh, \%h);
412 TarWrite($fh, \$data);
413 TarWritePad($fh, length($data));
417 # Handle long file names
419 if ( length($hdr->{name}) > 99 ) {
421 my $data = $hdr->{name} . "\0";
422 $h{name} = "././\@LongLink";
424 $h{size} = length($data);
425 TarWriteHeader($fh, \%h);
426 TarWrite($fh, \$data);
427 TarWritePad($fh, length($data));
429 TarWriteHeader($fh, $hdr);
437 my($hdr, $fh, $tarPathOverride) = @_;
439 my $tarPath = $hdr->{relPath};
440 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
442 $tarPath =~ s{//+}{/}g;
443 if ( defined($PathRemove)
444 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
445 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
447 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
448 $tarPath =~ s{//+}{/}g;
449 $hdr->{name} = $tarPath;
451 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
453 # Directory: just write the header
455 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
456 TarWriteFileInfo($fh, $hdr);
458 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
461 # Regular file: write the header and file
463 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
464 if ( !defined($f) ) {
465 print(STDERR "Unable to open file $hdr->{fullPath}\n");
469 TarWriteFileInfo($fh, $hdr);
470 if ( $opts{l} || $opts{L} ) {
471 $size = $hdr->{size};
473 while ( $f->read(\$data, $BufSize) > 0 ) {
474 if ( $size + length($data) > $hdr->{size} ) {
475 print(STDERR "Error: truncating $hdr->{fullPath} to"
476 . " $hdr->{size} bytes\n");
477 $data = substr($data, 0, $hdr->{size} - $size);
480 TarWrite($fh, \$data);
481 $size += length($data);
484 if ( $size != $hdr->{size} ) {
485 print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
486 . " bytes from $size bytes\n");
488 while ( $size < $hdr->{size} ) {
489 my $len = $hdr->{size} - $size;
490 $len = $BufSize if ( $len > $BufSize );
492 TarWrite($fh, \$data);
496 TarWritePad($fh, $size);
500 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
502 # Hardlink file: either write a hardlink or the complete file
503 # depending upon whether the linked-to file will be written
506 # Start by reading the contents of the link.
508 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
509 if ( !defined($f) ) {
510 print(STDERR "Unable to open file $hdr->{fullPath}\n");
515 while ( $f->read(\$data, $BufSize) > 0 ) {
516 $hdr->{linkname} .= $data;
520 # Check @ARGV and the list of hardlinked files we have explicity
521 # dumped to see if we have dumped this file or not
524 my $name = $hdr->{linkname};
526 if ( defined($HardLinkExtraFiles{$name}) ) {
529 foreach my $arg ( @ARGV ) {
530 $arg = "/" if ( $arg eq "." );
533 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// || $arg eq "" );
538 # Target file will be or was written, so just remember
539 # the hardlink so we can dump it later.
541 push(@HardLinks, $hdr);
545 # Have to dump the original file. Just call the top-level
546 # routine, so that we save the hassle of dealing with
547 # mangling, merging and attributes.
549 my $name = $hdr->{linkname};
551 $HardLinkExtraFiles{$name} = $hdr->{name};
552 archiveWrite($fh, $name, $hdr->{name});
554 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
556 # Symbolic link: read the symbolic link contents into the header
557 # and write the header.
559 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
560 if ( !defined($f) ) {
561 print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
566 while ( $f->read(\$data, $BufSize) > 0 ) {
567 $hdr->{linkname} .= $data;
571 TarWriteFileInfo($fh, $hdr);
573 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
574 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
575 || $hdr->{type} == BPC_FTYPE_FIFO ) {
577 # Special files: for char and block special we read the
578 # major and minor numbers from a plain file.
580 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
581 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
584 if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
585 print(STDERR "Unable to open/read char/block special file"
586 . " $hdr->{fullPath}\n");
587 $f->close if ( defined($f) );
592 if ( $data =~ /(\d+),(\d+)/ ) {
593 $hdr->{devmajor} = $1;
594 $hdr->{devminor} = $2;
598 TarWriteFileInfo($fh, $hdr);
601 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");