48554b86b604876d98df1e3a93c3a83706066309
[BackupPC.git] / lib / BackupPC / FileZIO.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::FileZIO package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::FileZIO class for doing
8 #   compressed or normal file I/O.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001  Craig Barratt
15 #
16 #   This program is free software; you can redistribute it and/or modify
17 #   it under the terms of the GNU General Public License as published by
18 #   the Free Software Foundation; either version 2 of the License, or
19 #   (at your option) any later version.
20 #
21 #   This program is distributed in the hope that it will be useful,
22 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
23 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 #   GNU General Public License for more details.
25 #
26 #   You should have received a copy of the GNU General Public License
27 #   along with this program; if not, write to the Free Software
28 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 #
30 #========================================================================
31 #
32 # Version 2.0.0beta1, released 30 Mar 2003.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::FileZIO;
39
40 use strict;
41
42 use vars qw( $CompZlibOK );
43 use Carp;
44 use File::Path;
45 use File::Copy;
46
47 #
48 # For compressed files we have a to careful about running out of memory
49 # when we inflate a deflated file. For example, if a 500MB file of all
50 # zero-bytes is compressed, it will only occupy a few tens of kbytes. If
51 # we read the compressed file in decent-size chunks, a single inflate
52 # will try to allocate 500MB. Not a good idea.
53 #
54 # Instead, we compress the file in chunks of $CompMaxWrite. If a
55 # deflated chunk produces less than $CompMaxRead bytes, then we flush
56 # and continue. This adds a few bytes to the compressed output file, but
57 # only in extreme cases where the compression ratio is very close to
58 # 100%. The result is that, provided we read the compressed file in
59 # chunks of $CompMaxRead or less, the biggest inflated data will be
60 # $CompMaxWrite.
61 #
62 my $CompMaxRead  = 131072;          # 128K
63 my $CompMaxWrite = 6291456;         # 6MB
64
65 #
66 # We maintain a write buffer for small writes for both compressed and
67 # uncompressed files.  This is the size of the write buffer.
68 #
69 my $WriteBufSize = 65536;
70
71 BEGIN {
72     eval "use Compress::Zlib;";
73     if ( $@ ) {
74         #
75         # Compress::Zlib doesn't exist.  Define some dummy constant
76         # subs so that the code below doesn't barf.
77         #
78         eval {
79             sub Z_OK         { return 0; }
80             sub Z_STREAM_END { return 1; }
81         };
82         $CompZlibOK = 0;
83     } else {
84         $CompZlibOK = 1;
85     }
86 };
87
88 sub open
89 {
90     my($class, $fileName, $write, $compLevel) = @_;
91     local(*FH);
92     my($fh);
93
94     if ( ref(\$fileName) eq "GLOB" ) {
95         $fh = $fileName;
96     } else {
97         if ( $write ) {
98             open(FH, ">", $fileName) || return;
99         } else {
100             open(FH, "<", $fileName) || return;
101         }
102         $fh = *FH;
103     }
104     $compLevel = 0 if ( !$CompZlibOK );
105     my $self = bless {
106         fh           => $fh,
107         name         => $fileName,
108         write        => $write,
109         writeZeroCnt => 0,
110         compress     => $compLevel,
111     }, $class;
112     if ( $compLevel ) {
113         if ( $write ) {
114             $self->{deflate} = $self->myDeflateInit;
115         } else {
116             $self->{inflate} = $self->myInflateInit;
117         }
118     }
119     return $self;
120 }
121
122 sub compOk
123 {
124     return $CompZlibOK;
125 }
126
127 sub myDeflateInit
128 {
129     my $self = shift;
130
131     return deflateInit(
132                 -Bufsize => 65536,
133                 -Level   => $self->{compress},
134            );
135 }
136
137 sub myInflateInit
138 {
139     my $self = shift;
140
141     return inflateInit(
142                 -Bufsize => 65536,
143            );
144 }
145
146 sub read
147 {
148     my($self, $dataRef, $nRead) = @_;
149     my($n);
150
151     return if ( $self->{write} );
152     return sysread($self->{fh}, $$dataRef, $nRead) if ( !$self->{compress} );
153     while ( !$self->{eof} && $nRead > length($self->{dataOut}) ) {
154         if ( !length($self->{dataIn}) ) {
155             $n = sysread($self->{fh}, $self->{dataIn}, $CompMaxRead);
156             return $n if ( $n < 0 );
157             $self->{eof} = 1 if ( $n == 0 );
158         }
159         my($data, $err) = $self->{inflate}->inflate($self->{dataIn});
160         $self->{dataOut} .= $data;
161         if ( $err == Z_STREAM_END ) {
162             #print("R");
163             $self->{inflate} = $self->myInflateInit;
164         } elsif ( $err != Z_OK ) {
165             $$dataRef = "";
166             return -1;
167         }
168     }
169     if ( $nRead >= length($self->{dataOut}) ) {
170         $n = length($self->{dataOut});
171         $$dataRef = $self->{dataOut};
172         $self->{dataOut} = '';
173         return $n;
174     } else {
175         $$dataRef = substr($self->{dataOut}, 0, $nRead);
176         $self->{dataOut} = substr($self->{dataOut}, $nRead);
177         return $nRead;
178     }
179 }
180
181 #
182 # Provide a line-at-a-time interface.  This splits and buffers the
183 # lines, you cannot mix calls to read() and readLine().
184 #
185 sub readLine
186 {
187     my($self) = @_;
188     my $str;
189
190     while ( defined($self->{readLineBuf}) && !@{$self->{readLineBuf}} ) {
191         $self->read(\$str, $CompMaxRead);
192         if ( $str eq "" ) {
193             $str = $self->{readLineFrag};
194             $self->{readLineFrag} = "";
195             return $str;
196         }
197         @{$self->{readLineBuf}} = split(/\n/, $self->{readLineFrag} . $str);
198         if ( substr($str, -1, 1) ne "\n" ) {
199             $self->{readLineFrag} = pop(@{$self->{readLineBuf}});
200         } else {
201             $self->{readLineFrag} = "";
202         }
203     }
204     return shift(@{$self->{readLineBuf}}) . "\n";
205 }
206
207 sub rewind
208 {
209     my($self) = @_;
210
211     return if ( $self->{write} );
212     return sysseek($self->{fh}, 0, 0) if ( !$self->{compress} );
213     $self->{dataOut} = '';
214     $self->{dataIn}  = '';
215     $self->{eof}     = 0;
216     $self->{inflate} = $self->myInflateInit;
217     return sysseek($self->{fh}, 0, 0);
218 }
219
220 sub writeBuffered
221 {
222     my $self = shift;
223     my($data, $force) = @_;
224
225     #
226     # Buffer small writes using a buffer size of up to $WriteBufSize.
227     #
228     if ( $force || length($self->{writeBuf}) + length($data) > $WriteBufSize ) {
229         if ( length($self->{writeBuf}) ) {
230             my $wrData = $self->{writeBuf} . $data;
231             return -1 if ( syswrite($self->{fh}, $wrData) != length($wrData) );
232             $self->{writeBuf} = undef;
233         } else {
234             return if ( length($data) == 0 );
235             return -1 if ( syswrite($self->{fh}, $data) != length($data) );
236         }
237     } else {
238         $self->{writeBuf} .= $data;
239     }
240     return 0;
241 }
242
243 sub write
244 {
245     my($self, $dataRef) = @_;
246     my $n = length($$dataRef);
247
248     return if ( !$self->{write} );
249     print($$dataRef) if ( $self->{writeTeeStdout} );
250     return 0 if ( $n == 0 );
251     if ( !$self->{compress} ) {
252         #
253         # If smbclient gets a read error on the client (due to a file lock)
254         # it will write a dummy file of zeros.  We detect this so we can
255         # store the file efficiently as a sparse file.  writeZeroCnt is
256         # the number of consecutive 0 bytes at the start of the file.
257         #
258         my $skip = 0;
259         if ( $self->{writeZeroCnt} >= 0 && $$dataRef =~ /^(\0+)/s ) {
260             $skip = length($1);
261             $self->{writeZeroCnt} += $skip;
262             return $n if ( $skip == $n );
263         }
264         #
265         # We now have some non-zero bytes, so time to seek to the right
266         # place and turn off zero-byte detection.
267         #
268         if ( $self->{writeZeroCnt} > 0 ) {
269             sysseek($self->{fh}, $self->{writeZeroCnt}, 0);
270             $self->{writeZeroCnt} = -1;
271         } elsif ( $self->{writeZeroCnt} == 0 ) {
272             $self->{writeZeroCnt} = -1;
273         }
274         return -1 if ( $self->writeBuffered(substr($$dataRef, $skip)) < 0 );
275         return $n;
276     }
277     for ( my $i = 0 ; $i < $n ; $i += $CompMaxWrite ) {
278         my $dataIn  = substr($$dataRef, $i, $CompMaxWrite);
279         my $dataOut = $self->{deflate}->deflate($dataIn);
280         return -1 if ( $self->writeBuffered($dataOut) < 0 );
281         $self->{deflateIn}  += length($dataIn);
282         $self->{deflateOut} += length($dataOut);
283         if ( $self->{deflateIn} >= $CompMaxWrite ) {
284             if ( $self->{deflateOut} < $CompMaxRead ) {
285                 #
286                 # Compression is too high: to avoid huge memory requirements
287                 # on read we need to flush().
288                 #
289                 $dataOut = $self->{deflate}->flush();
290                 #print("F");
291                 $self->{deflate} = $self->myDeflateInit;
292                 return -1 if ( $self->writeBuffered($dataOut) < 0 );
293             }
294             $self->{deflateIn} = $self->{deflateOut} = 0;
295         }
296     }
297     return $n;
298 }
299
300 sub name
301 {
302     my($self) = @_;
303
304     return $self->{name};
305 }
306
307 sub writeTeeStdout
308 {
309     my($self, $param) = @_;
310
311     $self->{writeTeeStdout} = $param if ( defined($param) );
312     return $self->{writeTeeStdout};
313 }
314
315 sub close
316 {
317     my($self) = @_;
318     my $err = 0;
319
320     if ( $self->{write} && $self->{compress} ) {
321         my $data = $self->{deflate}->flush();
322         $err = 1 if ( $self->writeBuffered($data) < 0 );
323     } elsif ( $self->{write} && !$self->{compress} ) {
324         if ( $self->{writeZeroCnt} > 0 ) {
325             #
326             # We got a file of all zero bytes.  Write a single zero byte
327             # at the end of the file.  On most file systems this is an
328             # efficient way to store the file.
329             #
330             $err = 1 if ( sysseek($self->{fh}, $self->{writeZeroCnt} - 1, 0)
331                                             != $self->{writeZeroCnt} - 1
332                         || syswrite($self->{fh}, "\0") != 1 );
333         }
334     }
335     $self->writeBuffered(undef, 1);
336     close($self->{fh});
337     return $err ? -1 : 0;
338 }
339
340 #
341 # If $compress is >0, copy and compress $srcFile putting the output
342 # in $destFileZ.  Otherwise, copy the file to $destFileNoZ, or do
343 # nothing if $destFileNoZ is undef.  Finally, if rename is set, then
344 # the source file is removed.
345 #
346 sub compressCopy
347 {
348     my($class, $srcFile, $destFileZ, $destFileNoZ, $compress, $rmSrc) = @_;
349     my(@s) = stat($srcFile);
350     my $atime = $s[8] =~ /(.*)/ && $1;
351     my $mtime = $s[9] =~ /(.*)/ && $1;
352     if ( $CompZlibOK && $compress > 0 ) {
353         my $fh = BackupPC::FileZIO->open($destFileZ, 1, $compress);
354         my $data;
355         if ( defined($fh) && open(LOG, "<", $srcFile) ) {
356             while ( sysread(LOG, $data, 65536) > 0 ) {
357                 $fh->write(\$data);
358             }
359             close(LOG);
360             $fh->close();
361             unlink($srcFile) if ( $rmSrc );
362             utime($atime, $mtime, $destFileZ);
363             return 1;
364         } else {
365             $fh->close() if ( defined($fh) );
366             return 0;
367         }
368     }
369     return 0 if ( !defined($destFileNoZ) );
370     if ( $rmSrc ) {
371         return rename($srcFile, $destFileNoZ);
372     } else {
373         return 0 if ( !copy($srcFile, $destFileNoZ) );
374         utime($atime, $mtime, $destFileNoZ);
375     }
376 }
377
378 1;