* Commit for 2.1.0.
[BackupPC.git] / bin / BackupPC_tarCreate
1 #!/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_tarCreate: create a tar archive of an existing dump
5 # for restore on a client.
6 #
7 # DESCRIPTION
8 #  
9 #   Usage: BackupPC_tarCreate [options] files/directories...
10 #
11 #   Flags:
12 #     Required options:
13 #
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.
19 #
20 #     Other options:
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 #
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.
31 #
32 # AUTHOR
33 #   Craig Barratt  <cbarratt@users.sourceforge.net>
34 #
35 # COPYRIGHT
36 #   Copyright (C) 2001-2003  Craig Barratt
37 #
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.
42 #
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.
47 #
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
51 #
52 #========================================================================
53 #
54 # Version 2.1.0, released 20 Jun 2004.
55 #
56 # See http://backuppc.sourceforge.net.
57 #
58 #========================================================================
59
60 use strict;
61 no  utf8;
62 use lib "/usr/local/BackupPC/lib";
63 use File::Path;
64 use Getopt::Std;
65 use BackupPC::Lib;
66 use BackupPC::Attrib qw(:all);
67 use BackupPC::FileZIO;
68 use BackupPC::View;
69
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();
74
75 my %opts;
76
77 if ( !getopts("th:n:p:r:s:b:w:", \%opts) || @ARGV < 1 ) {
78     print STDERR <<EOF;
79 usage: $0 [options] files/directories...
80   Required options:
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
86
87   Other options:
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)
93 EOF
94     exit(1);
95 }
96
97 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
98     print(STDERR "$0: bad host name '$opts{h}'\n");
99     exit(1);
100 }
101 my $Host = $opts{h};
102
103 if ( $opts{n} !~ /^(-?\d+)$/ ) {
104     print(STDERR "$0: bad dump number '$opts{n}'\n");
105     exit(1);
106 }
107 my $Num = $opts{n};
108
109 my @Backups = $bpc->BackupInfoRead($Host);
110 my $FileCnt = 0;
111 my $ByteCnt = 0;
112 my $DirCnt = 0;
113 my $SpecialCnt = 0;
114 my $ErrorCnt = 0;
115
116 my $i;
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 );
120 }
121 if ( $i >= @Backups ) {
122     print(STDERR "$0: bad backup number $Num for host $Host\n");
123     exit(1);
124 }
125
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");
130     exit(1);
131 }
132 our $ShareName = $opts{s};
133 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
134
135 #
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.
138 # See www.cpan.org.
139 #
140 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
141 #                 Copyright 1998 Stephen Zander. All rights reserved.
142 #
143 my $tar_pack_header
144     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
145 my $tar_header_length = 512;
146
147 my $BufSize    = $opts{w} || 1048576;     # 1MB or 2^20
148 my $WriteBuf   = "";
149 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
150
151 my(%UidCache, %GidCache);
152 my(%HardLinkExtraFiles, @HardLinks);
153
154 #
155 # Write out all the requested files/directories
156 #
157 binmode(STDOUT);
158 my $fh = *STDOUT;
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);
168         }
169         archiveWriteHardLinks($fh);
170     }
171 } else {
172     foreach my $dir ( @ARGV ) {
173         archiveWrite($fh, $dir);
174     }
175     archiveWriteHardLinks($fh);
176 }
177
178 #
179 # Finish with two null 512 byte headers, and then round out a full
180 # block.
181
182 my $data = "\0" x ($tar_header_length * 2);
183 TarWrite($fh, \$data);
184 TarWrite($fh, undef);
185
186 #
187 # print out totals if requested
188 #
189 if ( $opts{t} ) {
190     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
191                  " $SpecialCnt specials, $ErrorCnt errors\n";
192 }
193 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
194     #
195     # Got errors, with no files or directories; exit with non-zero
196     # status
197     #
198     exit(1);
199 }
200 exit(0);
201
202 ###########################################################################
203 # Subroutines
204 ###########################################################################
205
206 sub archiveWrite
207 {
208     my($fh, $dir, $tarPathOverride) = @_;
209
210     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
211         print(STDERR "$0: bad directory '$dir'\n");
212         $ErrorCnt++;
213         return;
214     }
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");
220         $ErrorCnt++;
221         return;
222     }
223 }
224
225 #
226 # Write out any hardlinks (if any)
227 #
228 sub archiveWriteHardLinks
229 {
230     my $fh = @_;
231     foreach my $hdr ( @HardLinks ) {
232         $hdr->{size} = 0;
233         if ( defined($PathRemove)
234               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
235                         eq ".$PathRemove" ) {
236             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
237         }
238         TarWriteFileInfo($fh, $hdr);
239     }
240     @HardLinks = ();
241     %HardLinkExtraFiles = ();
242 }
243
244 sub UidLookup
245 {
246     my($uid) = @_;
247
248     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
249     return $UidCache{$uid};
250 }
251
252 sub GidLookup
253 {
254     my($gid) = @_;
255
256     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
257     return $GidCache{$gid};
258 }
259
260 sub TarWrite
261 {
262     my($fh, $dataRef) = @_;
263
264     if ( !defined($dataRef) ) {
265         #
266         # do flush by padding to a full $WriteBufSz
267         #
268         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
269         $dataRef = \$data;
270     }
271     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
272         #
273         # just buffer and return
274         #
275         $WriteBuf .= $$dataRef;
276         return;
277     }
278     my $done = $WriteBufSz - length($WriteBuf);
279     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
280                                 != $WriteBufSz ) {
281         print(STDERR "Unable to write to output file ($!)\n");
282         exit(1);
283     }
284     while ( $done + $WriteBufSz <= length($$dataRef) ) {
285         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
286                             != $WriteBufSz ) {
287             print(STDERR "Unable to write to output file ($!)\n");
288             exit(1);
289         }
290         $done += $WriteBufSz;
291     }
292     $WriteBuf = substr($$dataRef, $done);
293 }
294
295 sub TarWritePad
296 {
297     my($fh, $size) = @_;
298
299     if ( $size % $tar_header_length ) {
300         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
301         TarWrite($fh, \$data);
302     }
303 }
304
305 sub TarWriteHeader
306 {
307     my($fh, $hdr) = @_;
308
309     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
310     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
311     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
312                                              : "";
313     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
314                                              : "";
315     my $sizeStr;
316     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
317         #
318         # GNU extension for files >= 8GB: send size in big-endian binary
319         #
320         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
321                                   $hdr->{size} / (65536 * 65536),
322                                   $hdr->{size} % (65536 * 65536));
323     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
324         #
325         # sprintf octal only handles up to 2^32 - 1
326         #
327         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
328                  . sprintf("%08o", $hdr->{size} % (1 << 24));
329     } else {
330         $sizeStr = sprintf("%011o", $hdr->{size});
331     }
332     my $data = pack($tar_pack_header,
333                      substr($hdr->{name}, 0, 99),
334                      sprintf("%07o", $hdr->{mode}),
335                      sprintf("%07o", $hdr->{uid}),
336                      sprintf("%07o", $hdr->{gid}),
337                      $sizeStr,
338                      sprintf("%011o", $hdr->{mtime}),
339                      "",        #checksum field - space padded by pack("A8")
340                      $hdr->{type},
341                      substr($hdr->{linkname}, 0, 99),
342                      $hdr->{magic} || 'ustar ',
343                      $hdr->{version} || ' ',
344                      $hdr->{uname},
345                      $hdr->{gname},
346                      $devmajor,
347                      $devminor,
348                      ""         # prefix is empty
349                  );
350     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
351     TarWrite($fh, \$data);
352 }
353
354 sub TarWriteFileInfo
355 {
356     my($fh, $hdr) = @_;
357
358     #
359     # Handle long link names (symbolic links)
360     #
361     if ( length($hdr->{linkname}) > 99 ) {
362         my %h;
363         my $data = $hdr->{linkname} . "\0";
364         $h{name} = "././\@LongLink";
365         $h{type} = "K";
366         $h{size} = length($data);
367         TarWriteHeader($fh, \%h);
368         TarWrite($fh, \$data);
369         TarWritePad($fh, length($data));
370     }
371     #
372     # Handle long file names
373     #
374     if ( length($hdr->{name}) > 99 ) {
375         my %h;
376         my $data = $hdr->{name} . "\0";
377         $h{name} = "././\@LongLink";
378         $h{type} = "L";
379         $h{size} = length($data);
380         TarWriteHeader($fh, \%h);
381         TarWrite($fh, \$data);
382         TarWritePad($fh, length($data));
383     }
384     TarWriteHeader($fh, $hdr);
385 }
386
387 my $Attr;
388 my $AttrDir;
389
390 sub TarWriteFile
391 {
392     my($hdr, $fh, $tarPathOverride) = @_;
393
394     my $tarPath = $hdr->{relPath};
395     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
396
397     $tarPath =~ s{//+}{/}g;
398     if ( defined($PathRemove)
399             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
400         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
401     }
402     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
403     $tarPath =~ s{//+}{/}g;
404     $hdr->{name} = $tarPath;
405
406     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
407         #
408         # Directory: just write the header
409         #
410         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
411         TarWriteFileInfo($fh, $hdr);
412         $DirCnt++;
413     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
414         #
415         # Regular file: write the header and file
416         #
417         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
418         if ( !defined($f) ) {
419             print(STDERR "Unable to open file $hdr->{fullPath}\n");
420             $ErrorCnt++;
421             return;
422         }
423         TarWriteFileInfo($fh, $hdr);
424         my($data, $size);
425         while ( $f->read(\$data, $BufSize) > 0 ) {
426             TarWrite($fh, \$data);
427             $size += length($data);
428         }
429         $f->close;
430         TarWritePad($fh, $size);
431         $FileCnt++;
432         $ByteCnt += $size;
433     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
434         #
435         # Hardlink file: either write a hardlink or the complete file
436         # depending upon whether the linked-to file will be written
437         # to the archive.
438         #
439         # Start by reading the contents of the link.
440         #
441         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
442         if ( !defined($f) ) {
443             print(STDERR "Unable to open file $hdr->{fullPath}\n");
444             $ErrorCnt++;
445             return;
446         }
447         my $data;
448         while ( $f->read(\$data, $BufSize) > 0 ) {
449             $hdr->{linkname} .= $data;
450         }
451         $f->close;
452         #
453         # Check @ARGV and the list of hardlinked files we have explicity
454         # dumped to see if we have dumped this file or not
455         #
456         my $done = 0;
457         my $name = $hdr->{linkname};
458         $name =~ s{^\./}{/};
459         if ( $HardLinkExtraFiles{$name} ) {
460             $done = 1;
461         } else {
462             foreach my $arg ( @ARGV ) {
463                 $arg =~ s{^\./+}{/};
464                 $arg =~ s{/+$}{};
465                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
466             }
467         }
468         if ( $done ) {
469             #
470             # Target file will be or was written, so just remember
471             # the hardlink so we can dump it later.
472             #
473             push(@HardLinks, $hdr);
474             $SpecialCnt++;
475         } else {
476             #
477             # Have to dump the original file.  Just call the top-level
478             # routine, so that we save the hassle of dealing with
479             # mangling, merging and attributes.
480             #
481             $HardLinkExtraFiles{$hdr->{linkname}} = 1;
482             archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
483         }
484     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
485         #
486         # Symbolic link: read the symbolic link contents into the header
487         # and write the header.
488         #
489         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
490         if ( !defined($f) ) {
491             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
492             $ErrorCnt++;
493             return;
494         }
495         my $data;
496         while ( $f->read(\$data, $BufSize) > 0 ) {
497             $hdr->{linkname} .= $data;
498         }
499         $f->close;
500         $hdr->{size} = 0;
501         TarWriteFileInfo($fh, $hdr);
502         $SpecialCnt++;
503     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
504            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
505            || $hdr->{type} == BPC_FTYPE_FIFO ) {
506         #
507         # Special files: for char and block special we read the
508         # major and minor numbers from a plain file.
509         #
510         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
511             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
512                                                 $hdr->{compress});
513             my $data;
514             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
515                 print(STDERR "Unable to open/read char/block special file"
516                            . " $hdr->{fullPath}\n");
517                 $f->close if ( defined($f) );
518                 $ErrorCnt++;
519                 return;
520             }
521             $f->close;
522             if ( $data =~ /(\d+),(\d+)/ ) {
523                 $hdr->{devmajor} = $1;
524                 $hdr->{devminor} = $2;
525             }
526         }
527         $hdr->{size} = 0;
528         TarWriteFileInfo($fh, $hdr);
529         $SpecialCnt++;
530     } else {
531         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
532         $ErrorCnt++;
533     }
534 }