43240d33c8b7f22f35922e927f444434f54eeb90
[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.0beta1, released 30 Mar 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
73 if ( !getopts("th:n:p:r:s:", \%opts) || @ARGV < 1 ) {
74     print(STDERR "usage: $0 [-t] [-h host] [-n dumpNum] [-s shareName]"
75                . " [-r pathRemove] [-p pathAdd]"
76                . " files/directories...\n");
77     exit(1);
78 }
79
80 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
81     print(STDERR "$0: bad host name '$opts{h}'\n");
82     exit(1);
83 }
84 my $Host = $opts{h};
85
86 if ( $opts{n} !~ /^(\d+)$/ ) {
87     print(STDERR "$0: bad dump number '$opts{n}'\n");
88     exit(1);
89 }
90 my $Num = $opts{n};
91
92 my @Backups = $bpc->BackupInfoRead($Host);
93 my $FileCnt = 0;
94 my $ByteCnt = 0;
95 my $DirCnt = 0;
96 my $SpecialCnt = 0;
97 my $ErrorCnt = 0;
98
99 my $i;
100 for ( $i = 0 ; $i < @Backups ; $i++ ) {
101     last if ( $Backups[$i]{num} == $Num );
102 }
103 if ( $i >= @Backups ) {
104     print(STDERR "$0: bad backup number $Num for host $Host\n");
105     exit(1);
106 }
107
108 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
109 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
110 if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ ) {
111     print(STDERR "$0: bad share name '$opts{s}'\n");
112     exit(1);
113 }
114 my $ShareName = $opts{s};
115
116 #
117 # This constant and the line of code below that uses it are borrowed
118 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
119 # See www.cpan.org.
120 #
121 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
122 #                 Copyright 1998 Stephen Zander. All rights reserved.
123 #
124 my $tar_pack_header
125     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
126 my $tar_header_length = 512;
127
128 my $BufSize    = 1048576;     # 1MB or 2^20
129 my $WriteBuf   = "";
130 my $WriteBufSz = 20 * $tar_header_length;
131
132 my(%UidCache, %GidCache);
133 my(%HardLinkExtraFiles, @HardLinks);
134
135 #
136 # Write out all the requested files/directories
137 #
138 my $fh = *STDOUT;
139 foreach my $dir ( @ARGV ) {
140     archiveWrite($fh, $dir);
141 }
142
143 #
144 # Write out any hardlinks (if any)
145 #
146 foreach my $hdr ( @HardLinks ) {
147     $hdr->{size} = 0;
148     if ( defined($PathRemove)
149           && substr($hdr->{linkname}, 0, length($PathRemove)+1)
150                     eq ".$PathRemove" ) {
151         substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
152     }
153     TarWriteFileInfo($fh, $hdr);
154 }
155
156 #
157 # Finish with two null 512 byte headers, and then round out a full
158 # block.
159
160 my $data = "\0" x ($tar_header_length * 2);
161 TarWrite($fh, \$data);
162 TarWrite($fh, undef);
163
164 #
165 # print out totals if requested
166 #
167 if ( $opts{t} ) {
168     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
169                  " $SpecialCnt specials, $ErrorCnt errors\n";
170 }
171 exit(0);
172
173 ###########################################################################
174 # Subroutines
175 ###########################################################################
176
177 sub archiveWrite
178 {
179     my($fh, $dir, $tarPathOverride) = @_;
180
181     my $view = BackupPC::View->new($bpc, $Host, \@Backups);
182
183     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
184         print(STDERR "$0: bad directory '$dir'\n");
185         $ErrorCnt++;
186         return;
187     }
188     $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
189                 $fh, $tarPathOverride);
190 }
191
192 sub UidLookup
193 {
194     my($uid) = @_;
195
196     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
197     return $UidCache{$uid};
198 }
199
200 sub GidLookup
201 {
202     my($gid) = @_;
203
204     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
205     return $GidCache{$gid};
206 }
207
208 sub TarWrite
209 {
210     my($fh, $dataRef) = @_;
211
212     if ( !defined($dataRef) ) {
213         #
214         # do flush by padding to a full $WriteBufSz
215         #
216         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
217         $dataRef = \$data;
218     }
219     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
220         #
221         # just buffer and return
222         #
223         $WriteBuf .= $$dataRef;
224         return;
225     }
226     my $done = $WriteBufSz - length($WriteBuf);
227     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
228                                 != $WriteBufSz ) {
229         print(STDERR "Unable to write to output file ($!)\n");
230         exit(1);
231     }
232     while ( $done + $WriteBufSz <= length($$dataRef) ) {
233         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
234                             != $WriteBufSz ) {
235             print(STDERR "Unable to write to output file ($!)\n");
236             exit(1);
237         }
238         $done += $WriteBufSz;
239     }
240     $WriteBuf = substr($$dataRef, $done);
241 }
242
243 sub TarWritePad
244 {
245     my($fh, $size) = @_;
246
247     if ( $size % $tar_header_length ) {
248         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
249         TarWrite($fh, \$data);
250     }
251 }
252
253 sub TarWriteHeader
254 {
255     my($fh, $hdr) = @_;
256
257     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
258     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
259     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
260                                              : "";
261     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
262                                              : "";
263     my $data = pack($tar_pack_header,
264                      substr($hdr->{name}, 0, 99),
265                      sprintf("%07o", $hdr->{mode}),
266                      sprintf("%07o", $hdr->{uid}),
267                      sprintf("%07o", $hdr->{gid}),
268                      sprintf("%011o", $hdr->{size}),
269                      sprintf("%011o", $hdr->{mtime}),
270                      "",        #checksum field - space padded by pack("A8")
271                      $hdr->{type},
272                      substr($hdr->{linkname}, 0, 99),
273                      $hdr->{magic} || 'ustar ',
274                      $hdr->{version} || ' ',
275                      $hdr->{uname},
276                      $hdr->{gname},
277                      $devmajor,
278                      $devminor,
279                      ""         # prefix is empty
280                  );
281     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
282     TarWrite($fh, \$data);
283 }
284
285 sub TarWriteFileInfo
286 {
287     my($fh, $hdr) = @_;
288
289     #
290     # Handle long link names (symbolic links)
291     #
292     if ( length($hdr->{linkname}) > 99 ) {
293         my %h;
294         my $data = $hdr->{linkname} . "\0";
295         $h{name} = "././\@LongLink";
296         $h{type} = "K";
297         $h{size} = length($data);
298         TarWriteHeader($fh, \%h);
299         TarWrite($fh, \$data);
300         TarWritePad($fh, length($data));
301     }
302     #
303     # Handle long file names
304     #
305     if ( length($hdr->{name}) > 99 ) {
306         my %h;
307         my $data = $hdr->{name} . "\0";
308         $h{name} = "././\@LongLink";
309         $h{type} = "L";
310         $h{size} = length($data);
311         TarWriteHeader($fh, \%h);
312         TarWrite($fh, \$data);
313         TarWritePad($fh, length($data));
314     }
315     TarWriteHeader($fh, $hdr);
316 }
317
318 my $Attr;
319 my $AttrDir;
320
321 sub TarWriteFile
322 {
323     my($hdr, $fh, $tarPathOverride) = @_;
324
325     my $tarPath = $hdr->{relPath};
326     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
327
328     if ( defined($PathRemove)
329             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
330         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
331     }
332     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
333     $tarPath =~ s{//+}{/}g;
334     $hdr->{name} = $tarPath;
335
336     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
337         #
338         # Directory: just write the header
339         #
340         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
341         TarWriteFileInfo($fh, $hdr);
342         $DirCnt++;
343     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
344         #
345         # Regular file: write the header and file
346         #
347         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
348         if ( !defined($f) ) {
349             print(STDERR "Unable to open file $hdr->{fullPath}\n");
350             $ErrorCnt++;
351             return;
352         }
353         TarWriteFileInfo($fh, $hdr);
354         my($data, $size);
355         while ( $f->read(\$data, $BufSize) > 0 ) {
356             TarWrite($fh, \$data);
357             $size += length($data);
358         }
359         $f->close;
360         TarWritePad($fh, $size);
361         $FileCnt++;
362         $ByteCnt += $size;
363     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
364         #
365         # Hardlink file: either write a hardlink or the complete file
366         # depending upon whether the linked-to file will be written
367         # to the archive.
368         #
369         # Start by reading the contents of the link.
370         #
371         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
372         if ( !defined($f) ) {
373             print(STDERR "Unable to open file $hdr->{fullPath}\n");
374             $ErrorCnt++;
375             return;
376         }
377         my $data;
378         while ( $f->read(\$data, $BufSize) > 0 ) {
379             $hdr->{linkname} .= $data;
380         }
381         $f->close;
382         #
383         # Check @ARGV and the list of hardlinked files we have explicity
384         # dumped to see if we have dumped this file or not
385         #
386         my $done = 0;
387         my $name = $hdr->{linkname};
388         $name =~ s{^\./}{/};
389         if ( $HardLinkExtraFiles{$name} ) {
390             $done = 1;
391         } else {
392             foreach my $arg ( @ARGV ) {
393                 $arg =~ s{^\./+}{/};
394                 $arg =~ s{/+$}{};
395                 $done = 1 if ( $name eq $arg || $name =~ /^\Q$arg\// );
396             }
397         }
398         if ( $done ) {
399             #
400             # Target file will be or was written, so just remember
401             # the hardlink so we can dump it later.
402             #
403             push(@HardLinks, $hdr);
404             $SpecialCnt++;
405         } else {
406             #
407             # Have to dump the original file.  Just call the top-level
408             # routine, so that we save the hassle of dealing with
409             # mangling, merging and attributes.
410             #
411             $HardLinkExtraFiles{$hdr->{linkname}} = 1;
412             archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
413         }
414     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
415         #
416         # Symbolic link: read the symbolic link contents into the header
417         # and write the header.
418         #
419         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
420         if ( !defined($f) ) {
421             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
422             $ErrorCnt++;
423             return;
424         }
425         my $data;
426         while ( $f->read(\$data, $BufSize) > 0 ) {
427             $hdr->{linkname} .= $data;
428         }
429         $f->close;
430         $hdr->{size} = 0;
431         TarWriteFileInfo($fh, $hdr);
432         $SpecialCnt++;
433     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
434            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
435            || $hdr->{type} == BPC_FTYPE_FIFO ) {
436         #
437         # Special files: for char and block special we read the
438         # major and minor numbers from a plain file.
439         #
440         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
441             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
442                                                 $hdr->{compress});
443             my $data;
444             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
445                 print(STDERR "Unable to open/read char/block special file"
446                            . " $hdr->{fullPath}\n");
447                 $f->close if ( defined($f) );
448                 $ErrorCnt++;
449                 return;
450             }
451             $f->close;
452             if ( $data =~ /(\d+),(\d+)/ ) {
453                 $hdr->{devmajor} = $1;
454                 $hdr->{devminor} = $2;
455             }
456         }
457         $hdr->{size} = 0;
458         TarWriteFileInfo($fh, $hdr);
459         $SpecialCnt++;
460     } else {
461         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
462         $ErrorCnt++;
463     }
464 }