Updates in preparation for 3.0.0beta2:
[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 #       -e charset      charset for encoding file names (default: value of
27 #                       $Conf{ClientCharset} when backup was done)
28 #
29 #     The -h, -n and -s options specify which dump is used to generate
30 #     the tar archive.  The -r and -p options can be used to relocate
31 #     the paths in the tar archive so extracted files can be placed
32 #     in a location different from their original location.
33 #
34 # AUTHOR
35 #   Craig Barratt  <cbarratt@users.sourceforge.net>
36 #
37 # COPYRIGHT
38 #   Copyright (C) 2001-2003  Craig Barratt
39 #
40 #   This program is free software; you can redistribute it and/or modify
41 #   it under the terms of the GNU General Public License as published by
42 #   the Free Software Foundation; either version 2 of the License, or
43 #   (at your option) any later version.
44 #
45 #   This program is distributed in the hope that it will be useful,
46 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
47 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
48 #   GNU General Public License for more details.
49 #
50 #   You should have received a copy of the GNU General Public License
51 #   along with this program; if not, write to the Free Software
52 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
53 #
54 #========================================================================
55 #
56 # Version 3.0.0beta2, released 11 Nov 2006.
57 #
58 # See http://backuppc.sourceforge.net.
59 #
60 #========================================================================
61
62 use strict;
63 no  utf8;
64 use lib "/usr/local/BackupPC/lib";
65 use File::Path;
66 use Getopt::Std;
67 use Encode qw/from_to/;
68 use BackupPC::Lib;
69 use BackupPC::Attrib qw(:all);
70 use BackupPC::FileZIO;
71 use BackupPC::View;
72
73 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
74
75 my %opts;
76
77 if ( !getopts("te:h: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      -e charset      charset for encoding file names (default: value of
94                      \$Conf{ClientCharset} when backup was done)
95 EOF
96     exit(1);
97 }
98
99 if ( $opts{h} !~ /^([\w\.\s-]+)$/
100         || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
101     print(STDERR "$0: bad host name '$opts{h}'\n");
102     exit(1);
103 }
104 my $Host = $opts{h};
105
106 if ( $opts{n} !~ /^(-?\d+)$/ ) {
107     print(STDERR "$0: bad dump number '$opts{n}'\n");
108     exit(1);
109 }
110 my $Num = $opts{n};
111
112 my @Backups = $bpc->BackupInfoRead($Host);
113 my $FileCnt = 0;
114 my $ByteCnt = 0;
115 my $DirCnt = 0;
116 my $SpecialCnt = 0;
117 my $ErrorCnt = 0;
118
119 my $i;
120 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
121 for ( $i = 0 ; $i < @Backups ; $i++ ) {
122     last if ( $Backups[$i]{num} == $Num );
123 }
124 if ( $i >= @Backups ) {
125     print(STDERR "$0: bad backup number $Num for host $Host\n");
126     exit(1);
127 }
128
129 my $Charset = $Backups[$i]{charset};
130 $Charset = $opts{e} if ( $opts{e} ne "" );
131
132 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
133 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
134 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
135     print(STDERR "$0: bad share name '$opts{s}'\n");
136     exit(1);
137 }
138
139 our $ShareName = $opts{s};
140 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
141
142 #
143 # This constant and the line of code below that uses it are borrowed
144 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
145 # See www.cpan.org.
146 #
147 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
148 #                 Copyright 1998 Stephen Zander. All rights reserved.
149 #
150 my $tar_pack_header
151     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
152 my $tar_header_length = 512;
153
154 my $BufSize    = $opts{w} || 1048576;     # 1MB or 2^20
155 my $WriteBuf   = "";
156 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
157
158 my(%UidCache, %GidCache);
159 my(%HardLinkExtraFiles, @HardLinks);
160
161 #
162 # Write out all the requested files/directories
163 #
164 binmode(STDOUT);
165 my $fh = *STDOUT;
166 if ( $ShareName eq "*" ) {
167     my $PathRemoveOrig = $PathRemove;
168     my $PathAddOrig    = $PathAdd;
169     foreach $ShareName ( $view->shareList($Num) ) {
170         #print(STDERR "Doing share ($ShareName)\n");
171         $PathRemove = "/" if ( !defined($PathRemoveOrig) );
172         ($PathAdd = "/$ShareName/$PathAddOrig") =~ s{//+}{/}g;
173         foreach my $dir ( @ARGV ) {
174             archiveWrite($fh, $dir);
175         }
176         archiveWriteHardLinks($fh);
177     }
178 } else {
179     foreach my $dir ( @ARGV ) {
180         archiveWrite($fh, $dir);
181     }
182     archiveWriteHardLinks($fh);
183 }
184
185 #
186 # Finish with two null 512 byte headers, and then round out a full
187 # block.
188
189 my $data = "\0" x ($tar_header_length * 2);
190 TarWrite($fh, \$data);
191 TarWrite($fh, undef);
192
193 #
194 # print out totals if requested
195 #
196 if ( $opts{t} ) {
197     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
198                  " $SpecialCnt specials, $ErrorCnt errors\n";
199 }
200 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
201     #
202     # Got errors, with no files or directories; exit with non-zero
203     # status
204     #
205     exit(1);
206 }
207 exit(0);
208
209 ###########################################################################
210 # Subroutines
211 ###########################################################################
212
213 sub archiveWrite
214 {
215     my($fh, $dir, $tarPathOverride) = @_;
216
217     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
218         print(STDERR "$0: bad directory '$dir'\n");
219         $ErrorCnt++;
220         return;
221     }
222     $dir = "/" if ( $dir eq "." );
223     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
224     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
225                 $fh, $tarPathOverride) < 0 ) {
226         print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
227         $ErrorCnt++;
228         return;
229     }
230 }
231
232 #
233 # Write out any hardlinks (if any)
234 #
235 sub archiveWriteHardLinks
236 {
237     my($fh) = @_;
238     foreach my $hdr ( @HardLinks ) {
239         $hdr->{size} = 0;
240         my $name = $hdr->{linkname};
241         $name =~ s{^\./}{/};
242         if ( defined($HardLinkExtraFiles{$name}) ) {
243             $hdr->{linkname} = $HardLinkExtraFiles{$name};
244         }
245         if ( defined($PathRemove)
246               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
247                         eq ".$PathRemove" ) {
248             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
249         }
250         TarWriteFileInfo($fh, $hdr);
251     }
252     @HardLinks = ();
253     %HardLinkExtraFiles = ();
254 }
255
256 sub UidLookup
257 {
258     my($uid) = @_;
259
260     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
261     return $UidCache{$uid};
262 }
263
264 sub GidLookup
265 {
266     my($gid) = @_;
267
268     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
269     return $GidCache{$gid};
270 }
271
272 sub TarWrite
273 {
274     my($fh, $dataRef) = @_;
275
276     if ( !defined($dataRef) ) {
277         #
278         # do flush by padding to a full $WriteBufSz
279         #
280         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
281         $dataRef = \$data;
282     }
283     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
284         #
285         # just buffer and return
286         #
287         $WriteBuf .= $$dataRef;
288         return;
289     }
290     my $done = $WriteBufSz - length($WriteBuf);
291     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
292                                 != $WriteBufSz ) {
293         print(STDERR "Unable to write to output file ($!)\n");
294         exit(1);
295     }
296     while ( $done + $WriteBufSz <= length($$dataRef) ) {
297         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
298                             != $WriteBufSz ) {
299             print(STDERR "Unable to write to output file ($!)\n");
300             exit(1);
301         }
302         $done += $WriteBufSz;
303     }
304     $WriteBuf = substr($$dataRef, $done);
305 }
306
307 sub TarWritePad
308 {
309     my($fh, $size) = @_;
310
311     if ( $size % $tar_header_length ) {
312         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
313         TarWrite($fh, \$data);
314     }
315 }
316
317 sub TarWriteHeader
318 {
319     my($fh, $hdr) = @_;
320
321     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
322     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
323     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
324                                              : "";
325     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
326                                              : "";
327     my $sizeStr;
328     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
329         #
330         # GNU extension for files >= 8GB: send size in big-endian binary
331         #
332         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
333                                   $hdr->{size} / (65536 * 65536),
334                                   $hdr->{size} % (65536 * 65536));
335     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
336         #
337         # sprintf octal only handles up to 2^32 - 1
338         #
339         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
340                  . sprintf("%08o", $hdr->{size} % (1 << 24));
341     } else {
342         $sizeStr = sprintf("%011o", $hdr->{size});
343     }
344     my $data = pack($tar_pack_header,
345                      substr($hdr->{name}, 0, 99),
346                      sprintf("%07o", $hdr->{mode}),
347                      sprintf("%07o", $hdr->{uid}),
348                      sprintf("%07o", $hdr->{gid}),
349                      $sizeStr,
350                      sprintf("%011o", $hdr->{mtime}),
351                      "",        #checksum field - space padded by pack("A8")
352                      $hdr->{type},
353                      substr($hdr->{linkname}, 0, 99),
354                      $hdr->{magic} || 'ustar ',
355                      $hdr->{version} || ' ',
356                      $hdr->{uname},
357                      $hdr->{gname},
358                      $devmajor,
359                      $devminor,
360                      ""         # prefix is empty
361                  );
362     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
363     TarWrite($fh, \$data);
364 }
365
366 sub TarWriteFileInfo
367 {
368     my($fh, $hdr) = @_;
369
370     #
371     # Convert path names to requested (eg: client) charset
372     #
373     if ( $Charset ne "" ) {
374         from_to($hdr->{name},     "utf8", $Charset);
375         from_to($hdr->{linkname}, "utf8", $Charset);
376     }
377
378     #
379     # Handle long link names (symbolic links)
380     #
381     if ( length($hdr->{linkname}) > 99 ) {
382         my %h;
383         my $data = $hdr->{linkname} . "\0";
384         $h{name} = "././\@LongLink";
385         $h{type} = "K";
386         $h{size} = length($data);
387         TarWriteHeader($fh, \%h);
388         TarWrite($fh, \$data);
389         TarWritePad($fh, length($data));
390     }
391
392     #
393     # Handle long file names
394     #
395     if ( length($hdr->{name}) > 99 ) {
396         my %h;
397         my $data = $hdr->{name} . "\0";
398         $h{name} = "././\@LongLink";
399         $h{type} = "L";
400         $h{size} = length($data);
401         TarWriteHeader($fh, \%h);
402         TarWrite($fh, \$data);
403         TarWritePad($fh, length($data));
404     }
405     TarWriteHeader($fh, $hdr);
406 }
407
408 my $Attr;
409 my $AttrDir;
410
411 sub TarWriteFile
412 {
413     my($hdr, $fh, $tarPathOverride) = @_;
414
415     my $tarPath = $hdr->{relPath};
416     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
417
418     $tarPath =~ s{//+}{/}g;
419     if ( defined($PathRemove)
420             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
421         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
422     }
423     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
424     $tarPath =~ s{//+}{/}g;
425     $hdr->{name} = $tarPath;
426
427     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
428         #
429         # Directory: just write the header
430         #
431         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
432         TarWriteFileInfo($fh, $hdr);
433         $DirCnt++;
434     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
435         #
436         # Regular file: write the header and file
437         #
438         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
439         if ( !defined($f) ) {
440             print(STDERR "Unable to open file $hdr->{fullPath}\n");
441             $ErrorCnt++;
442             return;
443         }
444         TarWriteFileInfo($fh, $hdr);
445         my($data, $size);
446         while ( $f->read(\$data, $BufSize) > 0 ) {
447             if ( $size + length($data) > $hdr->{size} ) {
448                 print(STDERR "Error: truncating $hdr->{fullPath} to"
449                            . " $hdr->{size} bytes\n");
450                 $data = substr($data, 0, $hdr->{size} - $size);
451                 $ErrorCnt++;
452             }
453             TarWrite($fh, \$data);
454             $size += length($data);
455         }
456         $f->close;
457         if ( $size != $hdr->{size} ) {
458             print(STDERR "Error: padding $hdr->{fullPath} to $hdr->{size}"
459                        . " bytes from $size bytes\n");
460             $ErrorCnt++;
461             while ( $size < $hdr->{size} ) {
462                 my $len = $hdr->{size} - $size;
463                 $len = $BufSize if ( $len > $BufSize );
464                 $data = "\0" x $len;
465                 TarWrite($fh, \$data);
466                 $size += $len;
467             }
468         }
469         TarWritePad($fh, $size);
470         $FileCnt++;
471         $ByteCnt += $size;
472     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
473         #
474         # Hardlink file: either write a hardlink or the complete file
475         # depending upon whether the linked-to file will be written
476         # to the archive.
477         #
478         # Start by reading the contents of the link.
479         #
480         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
481         if ( !defined($f) ) {
482             print(STDERR "Unable to open file $hdr->{fullPath}\n");
483             $ErrorCnt++;
484             return;
485         }
486         my $data;
487         while ( $f->read(\$data, $BufSize) > 0 ) {
488             $hdr->{linkname} .= $data;
489         }
490         $f->close;
491         #
492         # Check @ARGV and the list of hardlinked files we have explicity
493         # dumped to see if we have dumped this file or not
494         #
495         my $done = 0;
496         my $name = $hdr->{linkname};
497         $name =~ s{^\./}{/};
498         if ( defined($HardLinkExtraFiles{$name}) ) {
499             $done = 1;
500         } else {
501             foreach my $arg ( @ARGV ) {
502                 $arg = "/" if ( $arg eq "." );
503                 $arg =~ s{^\./+}{/};
504                 $arg =~ s{/+$}{};
505                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
506             }
507         }
508         if ( $done ) {
509             #
510             # Target file will be or was written, so just remember
511             # the hardlink so we can dump it later.
512             #
513             push(@HardLinks, $hdr);
514             $SpecialCnt++;
515         } else {
516             #
517             # Have to dump the original file.  Just call the top-level
518             # routine, so that we save the hassle of dealing with
519             # mangling, merging and attributes.
520             #
521             my $name = $hdr->{linkname};
522             $name =~ s{^\./}{/};
523             $HardLinkExtraFiles{$name} = $hdr->{name};
524             archiveWrite($fh, $name, $hdr->{name});
525         }
526     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
527         #
528         # Symbolic link: read the symbolic link contents into the header
529         # and write the header.
530         #
531         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
532         if ( !defined($f) ) {
533             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
534             $ErrorCnt++;
535             return;
536         }
537         my $data;
538         while ( $f->read(\$data, $BufSize) > 0 ) {
539             $hdr->{linkname} .= $data;
540         }
541         $f->close;
542         $hdr->{size} = 0;
543         TarWriteFileInfo($fh, $hdr);
544         $SpecialCnt++;
545     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
546            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
547            || $hdr->{type} == BPC_FTYPE_FIFO ) {
548         #
549         # Special files: for char and block special we read the
550         # major and minor numbers from a plain file.
551         #
552         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
553             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
554                                                 $hdr->{compress});
555             my $data;
556             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
557                 print(STDERR "Unable to open/read char/block special file"
558                            . " $hdr->{fullPath}\n");
559                 $f->close if ( defined($f) );
560                 $ErrorCnt++;
561                 return;
562             }
563             $f->close;
564             if ( $data =~ /(\d+),(\d+)/ ) {
565                 $hdr->{devmajor} = $1;
566                 $hdr->{devminor} = $2;
567             }
568         }
569         $hdr->{size} = 0;
570         TarWriteFileInfo($fh, $hdr);
571         $SpecialCnt++;
572     } else {
573         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
574         $ErrorCnt++;
575     }
576 }