- 2.0.0 release. Minor tweaks to disable utf8.
[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.0, released 14 Jun 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         binmode(FH);
103         $fh = *FH;
104     }
105     $compLevel = 0 if ( !$CompZlibOK );
106     my $self = bless {
107         fh           => $fh,
108         name         => $fileName,
109         write        => $write,
110         writeZeroCnt => 0,
111         compress     => $compLevel,
112     }, $class;
113     if ( $compLevel ) {
114         if ( $write ) {
115             $self->{deflate} = $self->myDeflateInit;
116         } else {
117             $self->{inflate} = $self->myInflateInit;
118         }
119     }
120     return $self;
121 }
122
123 sub compOk
124 {
125     return $CompZlibOK;
126 }
127
128 sub myDeflateInit
129 {
130     my $self = shift;
131
132     return deflateInit(
133                 -Bufsize => 65536,
134                 -Level   => $self->{compress},
135            );
136 }
137
138 sub myInflateInit
139 {
140     my $self = shift;
141
142     return inflateInit(
143                 -Bufsize => 65536,
144            );
145 }
146
147 sub read
148 {
149     my($self, $dataRef, $nRead) = @_;
150     my($n);
151
152     return if ( $self->{write} );
153     return sysread($self->{fh}, $$dataRef, $nRead) if ( !$self->{compress} );
154     while ( !$self->{eof} && $nRead > length($self->{dataOut}) ) {
155         if ( !length($self->{dataIn}) ) {
156             $n = sysread($self->{fh}, $self->{dataIn}, $CompMaxRead);
157             return $n if ( $n < 0 );
158             $self->{eof} = 1 if ( $n == 0 );
159         }
160         my($data, $err) = $self->{inflate}->inflate($self->{dataIn});
161         $self->{dataOut} .= $data;
162         if ( $err == Z_STREAM_END ) {
163             #print("R");
164             $self->{inflate} = $self->myInflateInit;
165         } elsif ( $err != Z_OK ) {
166             $$dataRef = "";
167             return -1;
168         }
169     }
170     if ( $nRead >= length($self->{dataOut}) ) {
171         $n = length($self->{dataOut});
172         $$dataRef = $self->{dataOut};
173         $self->{dataOut} = '';
174         return $n;
175     } else {
176         $$dataRef = substr($self->{dataOut}, 0, $nRead);
177         $self->{dataOut} = substr($self->{dataOut}, $nRead);
178         return $nRead;
179     }
180 }
181
182 #
183 # Provide a line-at-a-time interface.  This splits and buffers the
184 # lines, you cannot mix calls to read() and readLine().
185 #
186 sub readLine
187 {
188     my($self) = @_;
189     my $str;
190
191     while ( defined($self->{readLineBuf}) && !@{$self->{readLineBuf}} ) {
192         $self->read(\$str, $CompMaxRead);
193         if ( $str eq "" ) {
194             $str = $self->{readLineFrag};
195             $self->{readLineFrag} = "";
196             return $str;
197         }
198         @{$self->{readLineBuf}} = split(/\n/, $self->{readLineFrag} . $str);
199         if ( substr($str, -1, 1) ne "\n" ) {
200             $self->{readLineFrag} = pop(@{$self->{readLineBuf}});
201         } else {
202             $self->{readLineFrag} = "";
203         }
204     }
205     return shift(@{$self->{readLineBuf}}) . "\n";
206 }
207
208 sub rewind
209 {
210     my($self) = @_;
211
212     return if ( $self->{write} );
213     return sysseek($self->{fh}, 0, 0) if ( !$self->{compress} );
214     $self->{dataOut} = '';
215     $self->{dataIn}  = '';
216     $self->{eof}     = 0;
217     $self->{inflate} = $self->myInflateInit;
218     return sysseek($self->{fh}, 0, 0);
219 }
220
221 sub writeBuffered
222 {
223     my $self = shift;
224     my($data, $force) = @_;
225
226     #
227     # Buffer small writes using a buffer size of up to $WriteBufSize.
228     #
229     if ( $force || length($self->{writeBuf}) + length($data) > $WriteBufSize ) {
230         if ( length($self->{writeBuf}) ) {
231             my $wrData = $self->{writeBuf} . $data;
232             return -1 if ( syswrite($self->{fh}, $wrData) != length($wrData) );
233             $self->{writeBuf} = undef;
234         } else {
235             return if ( length($data) == 0 );
236             return -1 if ( syswrite($self->{fh}, $data) != length($data) );
237         }
238     } else {
239         $self->{writeBuf} .= $data;
240     }
241     return 0;
242 }
243
244 sub write
245 {
246     my($self, $dataRef) = @_;
247     my $n = length($$dataRef);
248
249     return if ( !$self->{write} );
250     print($$dataRef) if ( $self->{writeTeeStdout} );
251     return 0 if ( $n == 0 );
252     if ( !$self->{compress} ) {
253         #
254         # If smbclient gets a read error on the client (due to a file lock)
255         # it will write a dummy file of zeros.  We detect this so we can
256         # store the file efficiently as a sparse file.  writeZeroCnt is
257         # the number of consecutive 0 bytes at the start of the file.
258         #
259         my $skip = 0;
260         if ( $self->{writeZeroCnt} >= 0 && $$dataRef =~ /^(\0+)/s ) {
261             $skip = length($1);
262             $self->{writeZeroCnt} += $skip;
263             return $n if ( $skip == $n );
264         }
265         #
266         # We now have some non-zero bytes, so time to seek to the right
267         # place and turn off zero-byte detection.
268         #
269         if ( $self->{writeZeroCnt} > 0 ) {
270             sysseek($self->{fh}, $self->{writeZeroCnt}, 0);
271             $self->{writeZeroCnt} = -1;
272         } elsif ( $self->{writeZeroCnt} == 0 ) {
273             $self->{writeZeroCnt} = -1;
274         }
275         return -1 if ( $self->writeBuffered(substr($$dataRef, $skip)) < 0 );
276         return $n;
277     }
278     for ( my $i = 0 ; $i < $n ; $i += $CompMaxWrite ) {
279         my $dataIn  = substr($$dataRef, $i, $CompMaxWrite);
280         my $dataOut = $self->{deflate}->deflate($dataIn);
281         return -1 if ( $self->writeBuffered($dataOut) < 0 );
282         $self->{deflateIn}  += length($dataIn);
283         $self->{deflateOut} += length($dataOut);
284         if ( $self->{deflateIn} >= $CompMaxWrite ) {
285             if ( $self->{deflateOut} < $CompMaxRead ) {
286                 #
287                 # Compression is too high: to avoid huge memory requirements
288                 # on read we need to flush().
289                 #
290                 $dataOut = $self->{deflate}->flush();
291                 #print("F");
292                 $self->{deflate} = $self->myDeflateInit;
293                 return -1 if ( $self->writeBuffered($dataOut) < 0 );
294             }
295             $self->{deflateIn} = $self->{deflateOut} = 0;
296         }
297     }
298     return $n;
299 }
300
301 sub name
302 {
303     my($self) = @_;
304
305     return $self->{name};
306 }
307
308 sub writeTeeStdout
309 {
310     my($self, $param) = @_;
311
312     $self->{writeTeeStdout} = $param if ( defined($param) );
313     return $self->{writeTeeStdout};
314 }
315
316 sub close
317 {
318     my($self) = @_;
319     my $err = 0;
320
321     if ( $self->{write} && $self->{compress} ) {
322         my $data = $self->{deflate}->flush();
323         $err = 1 if ( $self->writeBuffered($data) < 0 );
324     } elsif ( $self->{write} && !$self->{compress} ) {
325         if ( $self->{writeZeroCnt} > 0 ) {
326             #
327             # We got a file of all zero bytes.  Write a single zero byte
328             # at the end of the file.  On most file systems this is an
329             # efficient way to store the file.
330             #
331             $err = 1 if ( sysseek($self->{fh}, $self->{writeZeroCnt} - 1, 0)
332                                             != $self->{writeZeroCnt} - 1
333                         || syswrite($self->{fh}, "\0") != 1 );
334         }
335     }
336     $self->writeBuffered(undef, 1);
337     close($self->{fh});
338     return $err ? -1 : 0;
339 }
340
341 #
342 # If $compress is >0, copy and compress $srcFile putting the output
343 # in $destFileZ.  Otherwise, copy the file to $destFileNoZ, or do
344 # nothing if $destFileNoZ is undef.  Finally, if rename is set, then
345 # the source file is removed.
346 #
347 sub compressCopy
348 {
349     my($class, $srcFile, $destFileZ, $destFileNoZ, $compress, $rmSrc) = @_;
350     my(@s) = stat($srcFile);
351     my $atime = $s[8] =~ /(.*)/ && $1;
352     my $mtime = $s[9] =~ /(.*)/ && $1;
353     if ( $CompZlibOK && $compress > 0 ) {
354         my $fh = BackupPC::FileZIO->open($destFileZ, 1, $compress);
355         my $data;
356         if ( defined($fh) && open(LOG, "<", $srcFile) ) {
357             binmode(LOG);
358             while ( sysread(LOG, $data, 65536) > 0 ) {
359                 $fh->write(\$data);
360             }
361             close(LOG);
362             $fh->close();
363             unlink($srcFile) if ( $rmSrc );
364             utime($atime, $mtime, $destFileZ);
365             return 1;
366         } else {
367             $fh->close() if ( defined($fh) );
368             return 0;
369         }
370     }
371     return 0 if ( !defined($destFileNoZ) );
372     if ( $rmSrc ) {
373         return rename($srcFile, $destFileNoZ);
374     } else {
375         return 0 if ( !copy($srcFile, $destFileNoZ) );
376         utime($atime, $mtime, $destFileNoZ);
377     }
378 }
379
380 1;