added numeric padding to appropriate query values
[BackupPC.git] / bin / BackupPC_zipCreate
1 #!/usr/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_zipCreate: create a zip archive of an existing dump
5 # for restore on a client.
6 #
7 # DESCRIPTION
8 #  
9 #   Usage: BackupPC_zipCreate [options] files/directories...
10 #
11 #   Flags:
12 #     Required options:
13 #       -h host         host from which the zip archive is created
14 #       -n dumpNum      dump number from which the zip archive is created
15 #                       A negative number means relative to the end (eg -1
16 #                       means the most recent dump, -2 2nd most recent etc).
17 #       -s shareName    share name from which the zip 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 #       -c level        compression level (default is 0, no compression)
24 #       -e charset      charset for encoding file names (default: cp1252)
25 #
26 #     The -h, -n and -s options specify which dump is used to generate
27 #     the zip archive.  The -r and -p options can be used to relocate
28 #     the paths in the zip archive so extracted files can be placed
29 #     in a location different from their original location.
30 #
31 # AUTHOR
32 #   Guillaume Filion <gfk@users.sourceforge.net>
33 #   Based on Backup_tarCreate by Craig Barratt <cbarratt@users.sourceforge.net>
34 #
35 # COPYRIGHT
36 #   Copyright (C) 2002-2009  Craig Barratt and Guillaume Filion
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 3.2.0, released 31 Jul 2010.
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 Archive::Zip qw(:ERROR_CODES);
64 use File::Path;
65 use Getopt::Std;
66 use Encode qw/from_to/;
67 use IO::Handle;
68 use BackupPC::Lib;
69 use BackupPC::Attrib qw(:all);
70 use BackupPC::FileZIO;
71 use BackupPC::Zip::FileMember;
72 use BackupPC::View;
73
74 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
75 my $TopDir = $bpc->TopDir();
76 my $BinDir = $bpc->BinDir();
77 my %Conf   = $bpc->Conf();
78
79 my %opts;
80
81 if ( !getopts("te:h:n:p:r:s:c:", \%opts) || @ARGV < 1 ) {
82     print STDERR <<EOF;
83 usage: $0 [options] files/directories...
84   Required options:
85      -h host         host from which the zip archive is created
86      -n dumpNum      dump number from which the tar archive is created
87                      A negative number means relative to the end (eg -1
88                      means the most recent dump, -2 2nd most recent etc).
89      -s shareName    share name from which the zip archive is created
90
91   Other options:
92      -t              print summary totals
93      -r pathRemove   path prefix that will be replaced with pathAdd
94      -p pathAdd      new path prefix
95      -c level        compression level (default is 0, no compression)
96      -e charset      charset for encoding file names (default: cp1252)
97 EOF
98     exit(1);
99 }
100
101 if ( $opts{h} !~ /^([\w\.\s-]+)$/
102         || $opts{h} =~ m{(^|/)\.\.(/|$)} ) {
103     print(STDERR "$0: bad host name '$opts{h}'\n");
104     exit(1);
105 }
106 my $Host = $opts{h};
107
108 if ( $opts{n} !~ /^(-?\d+)$/ ) {
109     print(STDERR "$0: bad dump number '$opts{n}'\n");
110     exit(1);
111 }
112 my $Num = $opts{n};
113
114 $opts{c} = 0 if ( $opts{c} eq "" );
115 if ( $opts{c} !~ /^(\d+)$/ ) {
116     print(STDERR "$0: invalid compression level '$opts{c}'. 0=none, 9=max\n");
117     exit(1);
118 }
119 my $compLevel = $opts{c};
120
121 my @Backups = $bpc->BackupInfoRead($Host);
122 my $FileCnt = 0;
123 my $ByteCnt = 0;
124 my $DirCnt = 0;
125 my $SpecialCnt = 0;
126 my $ErrorCnt = 0;
127
128 my $i;
129 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
130 for ( $i = 0 ; $i < @Backups ; $i++ ) {
131     last if ( $Backups[$i]{num} == $Num );
132 }
133 if ( $i >= @Backups ) {
134     print(STDERR "$0: bad backup number $Num for host $Host\n");
135     exit(1);
136 }
137
138 my $Charset = "cp1252";
139 $Charset = $opts{e} if ( $opts{e} ne "" );
140
141 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
142 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
143 if ( $opts{s} =~ m{(^|/)\.\.(/|$)} ) {
144     print(STDERR "$0: bad share name '$opts{s}'\n");
145     exit(1);
146 }
147 my $ShareName = $opts{s};
148
149 my $BufSize    = 1048576;     # 1MB or 2^20
150 my(%UidCache, %GidCache);
151 #my $fh = *STDOUT;
152 my $fh = new IO::Handle;      
153 $fh->fdopen(fileno(STDOUT),"w");
154 my $zipfh = Archive::Zip->new();
155
156 binmode(STDOUT);
157 foreach my $dir ( @ARGV ) {
158     archiveWrite($zipfh, $dir);
159 }
160
161 sub archiveWrite
162 {
163     my($zipfh, $dir, $zipPathOverride) = @_;
164
165     my $view = BackupPC::View->new($bpc, $Host, \@Backups);
166
167     if ( $dir =~ m{(^|/)\.\.(/|$)} || $dir !~ /^(.*)$/ ) {
168         print(STDERR "$0: bad directory '$dir'\n");
169         $ErrorCnt++;
170         return;
171     }
172     $dir = "/" if ( $dir eq "." );
173     $view->find($Num, $ShareName, $dir, 0, \&ZipWriteFile,
174                 $zipfh, $zipPathOverride);
175 }
176
177 # Create Zip file
178 print STDERR "Can't write Zip file\n"
179      unless $zipfh->writeToFileHandle($fh, 0) == Archive::Zip::AZ_OK;
180
181 #
182 # print out totals if requested
183 #
184 if ( $opts{t} ) {
185     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
186                  " $SpecialCnt specials ignored, $ErrorCnt errors\n";
187 }
188 exit(0);
189
190 ###########################################################################
191 # Subroutines
192 ###########################################################################
193
194 sub UidLookup
195 {
196     my($uid) = @_;
197
198     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
199     return $UidCache{$uid};
200 }
201
202 sub GidLookup
203 {
204     my($gid) = @_;
205
206     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
207     return $GidCache{$gid};
208 }
209
210 my $Attr;
211 my $AttrDir;
212
213 sub ZipWriteFile
214 {
215     my($hdr, $zipfh, $zipPathOverride) = @_;
216
217     my $tarPath = $hdr->{relPath};
218     $tarPath = $zipPathOverride if ( defined($zipPathOverride) );
219
220     if ( defined($PathRemove)
221             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
222         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
223     }
224     $tarPath = $1 if ( $tarPath =~ m{^\.?/+(.*)} );
225     $tarPath =~ s{//+}{/}g;
226     $hdr->{name} = $tarPath;
227     return if ( $tarPath eq "." || $tarPath eq "./" || $tarPath eq "" );
228
229     my $zipmember; # Container to hold the file/directory to zip.
230
231     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
232         #
233         # Directory: just write the header
234         #
235         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
236         from_to($hdr->{name}, "utf8", $Charset) if ( $Charset ne "" );
237         $zipmember = Archive::Zip::Member->newDirectoryNamed($hdr->{name});
238         $DirCnt++;
239     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
240         #
241         # Regular file: write the header and file
242         #
243         from_to($hdr->{name}, "utf8", $Charset) if ( $Charset ne "" );
244         $zipmember = BackupPC::Zip::FileMember->newFromFileNamed(
245                                             $hdr->{fullPath},
246                                             $hdr->{name},
247                                             $hdr->{size},
248                                             $hdr->{compress}
249                                     );
250         $FileCnt++;
251         $ByteCnt += $hdr->{size};
252     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
253         #
254         # Hardlink file: not supported by Zip, so just make a copy
255         # of the pointed-to file.
256         #
257         # Start by reading the contents of the link.
258         #
259         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
260         if ( !defined($f) ) {
261             print(STDERR "Unable to open file $hdr->{fullPath}\n");
262             $ErrorCnt++;
263             return;
264         }
265         my $data;
266         while ( $f->read(\$data, $BufSize) > 0 ) {
267             $hdr->{linkname} .= $data;
268         }
269         $f->close;
270         #
271         # Dump the original file.  Just call the top-level
272         # routine, so that we save the hassle of dealing with
273         # mangling, merging and attributes.
274         #
275         archiveWrite($zipfh, $hdr->{linkname}, $hdr->{name});
276     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
277         #
278         # Symlinks can't be Zipped. 8(
279         # We could zip the pointed-to dir/file (just like hardlink), but we
280         # have to avoid the infinite-loop case of a symlink pointed to a
281         # directory above us.  Ignore for now.  Could be a comand-line
282         # option later.
283         #
284         $SpecialCnt++;
285     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
286            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
287            || $hdr->{type} == BPC_FTYPE_FIFO ) {
288         #
289         # Special files can't be Zipped. 8(
290         #
291         $SpecialCnt++;
292     } else {
293         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
294         $ErrorCnt++;
295     }
296     return if ( !$zipmember );
297     
298     #
299     # Set the attributes and permissions.  The standard zip file
300     # header cannot handle dates prior to 1/1/1980, or 315561600
301     # unix seconds, so we round up the mtime.
302     #
303     my $mtime = $hdr->{mtime};
304     $mtime = 315561600 if ( $mtime < 315561600 );
305     $zipmember->setLastModFileDateTimeFromUnix($mtime);
306     $zipmember->unixFileAttributes($hdr->{mode});
307     # Zip files don't accept uid and gid, so we put them in the comment field.
308     $zipmember->fileComment("uid=".$hdr->{uid}." gid=".$hdr->{gid})
309             if ( $hdr->{uid} || $hdr->{gid} );
310     
311     # Specify the compression level for this member
312     $zipmember->desiredCompressionLevel($compLevel) if ($compLevel =~ /[0-9]/);
313     
314     # Finally Zip the member
315     $zipfh->addMember($zipmember);
316 }