- allow PingCmd and Nmb commands to be empty strings, allowing these
[BackupPC.git] / bin / BackupPC_tarCreate
1 #!/bin/perl -T
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 [-t] [-h host] [-n dumpNum] [-s shareName]
10 #                   [-r pathRemove] [-p pathAdd] files/directories...
11 #
12 #   Flags:
13 #     Required options:
14 #
15 #       -h host         host from which the tar archive is created
16 #       -n dumpNum      dump number from which the tar archive is created
17 #       -s shareName    share name from which the tar archive is created
18 #
19 #     Other options:
20 #       -t              print summary totals
21 #       -r pathRemove   path prefix that will be replaced with pathAdd
22 #       -p pathAdd      new path prefix
23 #
24 #     The -h, -n and -s options specify which dump is used to generate
25 #     the tar archive.  The -r and -p options can be used to relocate
26 #     the paths in the tar archive so extracted files can be placed
27 #     in a location different from their original location.
28 #
29 # AUTHOR
30 #   Craig Barratt  <cbarratt@users.sourceforge.net>
31 #
32 # COPYRIGHT
33 #   Copyright (C) 2001  Craig Barratt
34 #
35 #   This program is free software; you can redistribute it and/or modify
36 #   it under the terms of the GNU General Public License as published by
37 #   the Free Software Foundation; either version 2 of the License, or
38 #   (at your option) any later version.
39 #
40 #   This program is distributed in the hope that it will be useful,
41 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
42 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
43 #   GNU General Public License for more details.
44 #
45 #   You should have received a copy of the GNU General Public License
46 #   along with this program; if not, write to the Free Software
47 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
48 #
49 #========================================================================
50 #
51 # Version 2.0.0_CVS, released 3 Feb 2003.
52 #
53 # See http://backuppc.sourceforge.net.
54 #
55 #========================================================================
56
57 use strict;
58 use lib "/usr/local/BackupPC/lib";
59 use File::Path;
60 use Getopt::Std;
61 use BackupPC::Lib;
62 use BackupPC::Attrib qw(:all);
63 use BackupPC::FileZIO;
64 use BackupPC::View;
65
66 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
67 my $TopDir = $bpc->TopDir();
68 my $BinDir = $bpc->BinDir();
69 my %Conf   = $bpc->Conf();
70
71 my %opts;
72 getopts("th:n:p:r:s:", \%opts);
73
74 if ( @ARGV < 1 ) {
75     print(STDERR "usage: $0 [-t] [-h host] [-n dumpNum] [-s shareName]"
76                . " [-r pathRemove] [-p pathAdd]"
77                . " files/directories...\n");
78     exit(1);
79 }
80
81 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
82     print(STDERR "$0: bad host name '$opts{h}'\n");
83     exit(1);
84 }
85 my $Host = $opts{h};
86
87 if ( $opts{n} !~ /^(\d+)$/ ) {
88     print(STDERR "$0: bad dump number '$opts{n}'\n");
89     exit(1);
90 }
91 my $Num = $opts{n};
92
93 my @Backups = $bpc->BackupInfoRead($Host);
94 my $FileCnt = 0;
95 my $ByteCnt = 0;
96 my $DirCnt = 0;
97 my $SpecialCnt = 0;
98 my $ErrorCnt = 0;
99
100 my $i;
101 for ( $i = 0 ; $i < @Backups ; $i++ ) {
102     last if ( $Backups[$i]{num} == $Num );
103 }
104 if ( $i >= @Backups ) {
105     print(STDERR "$0: bad backup number $Num for host $Host\n");
106     exit(1);
107 }
108
109 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
110 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
111 if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ ) {
112     print(STDERR "$0: bad share name '$opts{s}'\n");
113     exit(1);
114 }
115 my $ShareName = $opts{s};
116
117 #
118 # This constant and the line of code below that uses it are borrowed
119 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
120 # See www.cpan.org.
121 #
122 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
123 #                 Copyright 1998 Stephen Zander. All rights reserved.
124 #
125 my $tar_pack_header
126     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
127 my $tar_header_length = 512;
128
129 my $BufSize    = 1048576;     # 1MB or 2^20
130 my $WriteBuf   = "";
131 my $WriteBufSz = 20 * $tar_header_length;
132
133 my(%UidCache, %GidCache);
134 my(%HardLinkExtraFiles, @HardLinks);
135
136 #
137 # Write out all the requested files/directories
138 #
139 my $fh = *STDOUT;
140 foreach my $dir ( @ARGV ) {
141     archiveWrite($fh, $dir);
142 }
143
144 #
145 # Write out any hardlinks (if any)
146 #
147 foreach my $hdr ( @HardLinks ) {
148     $hdr->{size} = 0;
149     if ( defined($PathRemove)
150           && substr($hdr->{linkname}, 0, length($PathRemove)+1)
151                     eq ".$PathRemove" ) {
152         substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
153     }
154     TarWriteFileInfo($fh, $hdr);
155 }
156
157 #
158 # Finish with two null 512 byte headers, and then round out a full
159 # block.
160
161 my $data = "\0" x ($tar_header_length * 2);
162 TarWrite($fh, \$data);
163 TarWrite($fh, undef);
164
165 #
166 # print out totals if requested
167 #
168 if ( $opts{t} ) {
169     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
170                  " $SpecialCnt specials, $ErrorCnt errors\n";
171 }
172 exit(0);
173
174 ###########################################################################
175 # Subroutines
176 ###########################################################################
177
178 sub archiveWrite
179 {
180     my($fh, $dir, $tarPathOverride) = @_;
181
182     my $view = BackupPC::View->new($bpc, $Host, \@Backups);
183
184     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
185         print(STDERR "$0: bad directory '$dir'\n");
186         $ErrorCnt++;
187         return;
188     }
189     $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
190                 $fh, $tarPathOverride);
191 }
192
193 sub UidLookup
194 {
195     my($uid) = @_;
196
197     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
198     return $UidCache{$uid};
199 }
200
201 sub GidLookup
202 {
203     my($gid) = @_;
204
205     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
206     return $GidCache{$gid};
207 }
208
209 sub TarWrite
210 {
211     my($fh, $dataRef) = @_;
212
213     if ( !defined($dataRef) ) {
214         #
215         # do flush by padding to a full $WriteBufSz
216         #
217         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
218         $dataRef = \$data;
219     }
220     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
221         #
222         # just buffer and return
223         #
224         $WriteBuf .= $$dataRef;
225         return;
226     }
227     my $done = $WriteBufSz - length($WriteBuf);
228     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
229                                 != $WriteBufSz ) {
230         print(STDERR "Unable to write to output file\n");
231         exit(1);
232     }
233     while ( $done + $WriteBufSz <= length($$dataRef) ) {
234         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
235                             != $WriteBufSz ) {
236             print(STDERR "Unable to write to output file\n");
237             exit(1);
238         }
239         $done += $WriteBufSz;
240     }
241     $WriteBuf = substr($$dataRef, $done);
242 }
243
244 sub TarWritePad
245 {
246     my($fh, $size) = @_;
247
248     if ( $size % $tar_header_length ) {
249         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
250         TarWrite($fh, \$data);
251     }
252 }
253
254 sub TarWriteHeader
255 {
256     my($fh, $hdr) = @_;
257
258     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
259     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
260     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
261                                              : "";
262     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
263                                              : "";
264     my $data = pack($tar_pack_header,
265                      substr($hdr->{name}, 0, 99),
266                      sprintf("%07o", $hdr->{mode}),
267                      sprintf("%07o", $hdr->{uid}),
268                      sprintf("%07o", $hdr->{gid}),
269                      sprintf("%011o", $hdr->{size}),
270                      sprintf("%011o", $hdr->{mtime}),
271                      "",        #checksum field - space padded by pack("A8")
272                      $hdr->{type},
273                      substr($hdr->{linkname}, 0, 99),
274                      $hdr->{magic} || 'ustar ',
275                      $hdr->{version} || ' ',
276                      $hdr->{uname},
277                      $hdr->{gname},
278                      $devmajor,
279                      $devminor,
280                      ""         # prefix is empty
281                  );
282     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
283     TarWrite($fh, \$data);
284 }
285
286 sub TarWriteFileInfo
287 {
288     my($fh, $hdr) = @_;
289
290     #
291     # Handle long link names (symbolic links)
292     #
293     if ( length($hdr->{linkname}) > 99 ) {
294         my %h;
295         my $data = $hdr->{linkname} . "\0";
296         $h{name} = "././\@LongLink";
297         $h{type} = "K";
298         $h{size} = length($data);
299         TarWriteHeader($fh, \%h);
300         TarWrite($fh, \$data);
301         TarWritePad($fh, length($data));
302     }
303     #
304     # Handle long file names
305     #
306     if ( length($hdr->{name}) > 99 ) {
307         my %h;
308         my $data = $hdr->{name} . "\0";
309         $h{name} = "././\@LongLink";
310         $h{type} = "L";
311         $h{size} = length($data);
312         TarWriteHeader($fh, \%h);
313         TarWrite($fh, \$data);
314         TarWritePad($fh, length($data));
315     }
316     TarWriteHeader($fh, $hdr);
317 }
318
319 my $Attr;
320 my $AttrDir;
321
322 sub TarWriteFile
323 {
324     my($hdr, $fh, $tarPathOverride) = @_;
325
326     my $tarPath = $hdr->{relPath};
327     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
328
329     if ( defined($PathRemove)
330             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
331         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
332     }
333     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
334     $tarPath =~ s{//+}{/}g;
335     $hdr->{name} = $tarPath;
336
337     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
338         #
339         # Directory: just write the header
340         #
341         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
342         TarWriteFileInfo($fh, $hdr);
343         $DirCnt++;
344     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
345         #
346         # Regular file: write the header and file
347         #
348         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
349         if ( !defined($f) ) {
350             print(STDERR "Unable to open file $hdr->{fullPath}\n");
351             $ErrorCnt++;
352             return;
353         }
354         TarWriteFileInfo($fh, $hdr);
355         my($data, $size);
356         while ( $f->read(\$data, $BufSize) > 0 ) {
357             TarWrite($fh, \$data);
358             $size += length($data);
359         }
360         $f->close;
361         TarWritePad($fh, $size);
362         $FileCnt++;
363         $ByteCnt += $size;
364     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
365         #
366         # Hardlink file: either write a hardlink or the complete file
367         # depending upon whether the linked-to file will be written
368         # to the archive.
369         #
370         # Start by reading the contents of the link.
371         #
372         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
373         if ( !defined($f) ) {
374             print(STDERR "Unable to open file $hdr->{fullPath}\n");
375             $ErrorCnt++;
376             return;
377         }
378         my $data;
379         while ( $f->read(\$data, $BufSize) > 0 ) {
380             $hdr->{linkname} .= $data;
381         }
382         $f->close;
383         #
384         # Check @ARGV and the list of hardlinked files we have explicity
385         # dumped to see if we have dumped this file or not
386         #
387         my $done = 0;
388         my $name = $hdr->{linkname};
389         $name =~ s{^\./}{/};
390         if ( $HardLinkExtraFiles{$name} ) {
391             $done = 1;
392         } else {
393             foreach my $arg ( @ARGV ) {
394                 $arg =~ s{^\./+}{/};
395                 $arg =~ s{/+$}{};
396                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
397             }
398         }
399         if ( $done ) {
400             #
401             # Target file will be or was written, so just remember
402             # the hardlink so we can dump it later.
403             #
404             push(@HardLinks, $hdr);
405             $SpecialCnt++;
406         } else {
407             #
408             # Have to dump the original file.  Just call the top-level
409             # routine, so that we save the hassle of dealing with
410             # mangling, merging and attributes.
411             #
412             $HardLinkExtraFiles{$hdr->{linkname}} = 1;
413             archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
414         }
415     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
416         #
417         # Symbolic link: read the symbolic link contents into the header
418         # and write the header.
419         #
420         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
421         if ( !defined($f) ) {
422             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
423             $ErrorCnt++;
424             return;
425         }
426         my $data;
427         while ( $f->read(\$data, $BufSize) > 0 ) {
428             $hdr->{linkname} .= $data;
429         }
430         $f->close;
431         $hdr->{size} = 0;
432         TarWriteFileInfo($fh, $hdr);
433         $SpecialCnt++;
434     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
435            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
436            || $hdr->{type} == BPC_FTYPE_FIFO ) {
437         #
438         # Special files: for char and block special we read the
439         # major and minor numbers from a plain file.
440         #
441         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
442             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
443                                                 $hdr->{compress});
444             my $data;
445             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
446                 print(STDERR "Unable to open/read char/block special file"
447                            . " $hdr->{fullPath}\n");
448                 $f->close if ( defined($f) );
449                 $ErrorCnt++;
450                 return;
451             }
452             $f->close;
453             if ( $data =~ /(\d+),(\d+)/ ) {
454                 $hdr->{devmajor} = $1;
455                 $hdr->{devminor} = $2;
456             }
457         }
458         $hdr->{size} = 0;
459         TarWriteFileInfo($fh, $hdr);
460         $SpecialCnt++;
461     } else {
462         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
463         $ErrorCnt++;
464     }
465 }