additional changes to it.pm (post 3.0.0beta2)
[BackupPC.git] / lib / BackupPC / Xfer / RsyncDigest.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Xfer::RsyncDigest package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Xfer::RsyncDigest class for computing
8 #   and caching rsync checksums.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001-2003  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 3.0.0beta2, released 11 Nov 2006.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Xfer::RsyncDigest;
39
40 use strict;
41 use BackupPC::FileZIO;
42
43 use vars qw( $RsyncLibOK );
44 use Carp;
45 use Fcntl;
46 require Exporter;
47 use vars qw( @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS );
48
49 my $Log = \&logHandler;
50
51 #
52 # Magic value for checksum seed.  We only cache block and file digests
53 # when the checksum seed matches this value.
54 #
55 use constant RSYNC_CSUMSEED_CACHE     => 32761;
56
57 @ISA = qw(Exporter);
58
59 @EXPORT    = qw( );
60
61 @EXPORT_OK = qw(
62                   RSYNC_CSUMSEED_CACHE
63              );
64
65 %EXPORT_TAGS = (
66     'all'    => [ @EXPORT_OK ],
67 );
68
69 BEGIN {
70     eval "use File::RsyncP;";
71     if ( $@ ) {
72         #
73         # File::RsyncP doesn't exist.  Define some dummy constant
74         # subs so that the code below doesn't barf.
75         #
76         $RsyncLibOK = 0;
77     } else {
78         $RsyncLibOK = 1;
79     }
80 };
81
82 #
83 # Return the rsync block size based on the file size.
84 # We also make sure the block size plus 4 (ie: cheeksumSeed)
85 # is not a multiple of 64 - otherwise the cached checksums
86 # will not be the same for protocol versions <= 26 and > 26.
87 #
88 sub blockSize
89 {
90     my($class, $fileSize, $defaultBlkSize) = @_;
91
92     my $blkSize = int($fileSize / 10000);
93     $blkSize = $defaultBlkSize if ( $blkSize < $defaultBlkSize );
94     $blkSize = 16384 if ( $blkSize > 16384 );
95     $blkSize += 4 if ( (($blkSize + 4) % 64) == 0 );
96     return $blkSize;
97 }
98
99 sub fileDigestIsCached
100 {
101     my($class, $file) = @_;
102     my $data;
103
104     sysopen(my $fh, $file, O_RDONLY) || return -1;
105     binmode($fh);
106     return -2 if ( sysread($fh, $data, 1) != 1 );
107     close($fh);
108     return $data eq chr(0xd6) ? 1 : 0;
109 }
110
111 #
112 # Compute and add rsync block and file digests to the given file.
113 #
114 # Empty files don't get cached checksums.
115 #
116 # If verify is set then existing cached checksums are checked.
117 # If verify == 2 then only a verify is done; no fixes are applied.
118
119 # Returns 0 on success.  Returns 1 on good verify and 2 on bad verify.
120 # Returns a variety of negative values on error.
121 #
122 sub digestAdd
123 {
124     my($class, $file, $blockSize, $checksumSeed, $verify) = @_;
125     my $retValue = 0;
126
127     #
128     # Don't cache checksums if the checksumSeed is not RSYNC_CSUMSEED_CACHE
129     # or if the file is empty.
130     #
131     return -100 if ( $checksumSeed != RSYNC_CSUMSEED_CACHE || !-s $file );
132
133     if ( $blockSize == 0 ) {
134         &$Log("digestAdd: bad blockSize ($file, $blockSize, $checksumSeed)");
135         $blockSize = 2048;
136     }
137     my $nBlks = int(65536 * 16 / $blockSize) + 1;
138     my($data, $blockDigest, $fileDigest);
139
140     return -101 if ( !$RsyncLibOK );
141
142     my $digest = File::RsyncP::Digest->new;
143     $digest->add(pack("V", $checksumSeed)) if ( $checksumSeed );
144
145     return -102 if ( !defined(my $fh = BackupPC::FileZIO->open($file, 0, 1)) );
146
147     my $fileSize;
148     while ( 1 ) {
149         $fh->read(\$data, $nBlks * $blockSize);
150         $fileSize += length($data);
151         last if ( $data eq "" );
152         $blockDigest .= $digest->blockDigest($data, $blockSize, 16,
153                                              $checksumSeed);
154         $digest->add($data);
155     }
156     $fileDigest = $digest->digest2;
157     my $eofPosn = sysseek($fh->{fh}, 0, 1);
158     $fh->close;
159     my $rsyncData = $blockDigest . $fileDigest;
160     my $metaData  = pack("VVVV", $blockSize,
161                                  $checksumSeed,
162                                  length($blockDigest) / 20,
163                                  0x5fe3c289,                # magic number
164                         );
165     my $data2 = chr(0xb3) . $rsyncData . $metaData;
166 #    printf("appending %d+%d bytes to %s at offset %d\n",
167 #                                            length($rsyncData),
168 #                                            length($metaData),
169 #                                            $file,
170 #                                            $eofPosn);
171     sysopen(my $fh2, $file, O_RDWR) || return -103;
172     binmode($fh2);
173     return -104 if ( sysread($fh2, $data, 1) != 1 );
174     if ( $data ne chr(0x78) && $data ne chr(0xd6) ) {
175         &$Log(sprintf("digestAdd: $file has unexpected first char 0x%x",
176                              ord($data)));
177         return -105;
178     }
179     return -106 if ( sysseek($fh2, $eofPosn, 0) != $eofPosn );
180     if ( $verify ) {
181         my $data3;
182
183         #
184         # Verify the cached checksums
185         #
186         return -107 if ( $data ne chr(0xd6) );
187         return -108 if ( sysread($fh2, $data3, length($data2) + 1) < 0 );
188         if ( $data2 eq $data3 ) {
189             return 1;
190         }
191         #
192         # Checksums don't agree - fall through so we rewrite the data
193         #
194         &$Log(sprintf("digestAdd: %s verify failed; redoing checksums; len = %d,%d; eofPosn = %d, fileSize = %d",
195                 $file, length($data2), length($data3), $eofPosn, $fileSize));
196         #&$Log(sprintf("dataNew  = %s", unpack("H*", $data2)));
197         #&$Log(sprintf("dataFile = %s", unpack("H*", $data3)));
198         return -109 if ( sysseek($fh2, $eofPosn, 0) != $eofPosn );
199         $retValue = 2;
200         return $retValue if ( $verify == 2 );
201     }
202     return -110 if ( syswrite($fh2, $data2) != length($data2) );
203     if ( $verify ) {
204         #
205         # Make sure there is no extraneous data on the end of
206         # the file.  Seek to the end and truncate if it doesn't
207         # match our expected length.
208         #
209         return -111 if ( !defined(sysseek($fh2, 0, 2)) );
210         if ( sysseek($fh2, 0, 1) != $eofPosn + length($data2) ) {
211             if ( !truncate($fh2, $eofPosn + length($data2)) ) {
212                 &$Log(sprintf("digestAdd: $file truncate from %d to %d failed",
213                                 sysseek($fh2, 0, 1), $eofPosn + length($data2)));
214                 return -112;
215             } else {
216                 &$Log(sprintf("digestAdd: %s truncated from %d to %d",
217                                 $file,
218                                 sysseek($fh2, 0, 1), $eofPosn + length($data2)));
219             }
220         }
221     }
222     return -113 if ( !defined(sysseek($fh2, 0, 0)) );
223     return -114 if ( syswrite($fh2, chr(0xd6)) != 1 );
224     close($fh2);
225     return $retValue;
226 }
227
228 #
229 # Return rsync checksums for the given file.  We read the cached checksums
230 # if they exist and the block size and checksum seed match.  Otherwise
231 # we compute the checksums from the file contents.
232 #
233 # The doCache flag can take three ranges:
234 #
235 #  - doCache <  0: don't generate/use cached checksums
236 #  - doCache == 0: don't generate, but do use cached checksums if available
237 #  - doCache >  0: generate (if necessary) and use cached checksums
238 #
239 # Note: caching is only enabled when compression is on and the
240 # checksum seed is RSYNC_CSUMSEED_CACHE (32761).
241 #
242 # Returns 0 on success.  Returns a variety of negative values on error.
243 #
244 sub digestStart
245 {
246     my($class, $fileName, $fileSize, $blockSize, $defBlkSize,
247        $checksumSeed, $needMD4, $compress, $doCache, $protocol_version) = @_;
248
249     return -1 if ( !$RsyncLibOK );
250
251     my $data;
252
253     my $dg = bless {
254         name     => $fileName,
255         needMD4  => $needMD4,
256         digest   => File::RsyncP::Digest->new,
257     }, $class;
258
259     $dg->{digest}->protocol($protocol_version);
260
261     if ( $fileSize > 0 && $compress && $doCache >= 0 ) {
262         open(my $fh, "<", $fileName) || return -2;
263         binmode($fh);
264         return -3 if ( read($fh, $data, 1) != 1 );
265         my $ret;
266
267         if ( $data eq chr(0x78) && $doCache > 0
268                      && $checksumSeed == RSYNC_CSUMSEED_CACHE ) {
269             #
270             # RSYNC_CSUMSEED_CACHE (32761) is the magic number that
271             # rsync uses for checksumSeed with the --fixed-csum option.
272             #
273             # We now add the cached checksum data to the file.  There
274             # is a possible race condition here since two BackupPC_dump
275             # processes might call this function at the same time
276             # on the same file.  But this should be ok since both
277             # processes will write the same data, and the order
278             # in which they write it doesn't matter.
279             #
280             close($fh);
281             $ret = $dg->digestAdd($fileName,
282                             $blockSize
283                                 || BackupPC::Xfer::RsyncDigest->blockSize(
284                                                     $fileSize, $defBlkSize),
285                                 $checksumSeed);
286             if ( $ret < 0 ) {
287                 &$Log("digestAdd($fileName) failed ($ret)");
288             }
289             #
290             # now re-open the file and re-read the first byte
291             #
292             open($fh, "<", $fileName) || return -4;
293             binmode($fh);
294             return -5 if ( read($fh, $data, 1) != 1 );
295         }
296         if ( $ret >= 0 && $data eq chr(0xd6) ) {
297             #
298             # Looks like this file has cached checksums
299             # Read the last 48 bytes: that's 2 file MD4s (32 bytes)
300             # plus 4 words of meta data
301             #
302             return -6 if ( !defined(seek($fh, -48, 2)) ); 
303             return -7 if ( read($fh, $data, 48) != 48 );
304             ($dg->{md4DigestOld},
305              $dg->{md4Digest},
306              $dg->{blockSize},
307              $dg->{checksumSeed},
308              $dg->{nBlocks},
309              $dg->{magic}) = unpack("a16 a16 V V V V", $data);
310             if ( $dg->{magic} == 0x5fe3c289
311                     && $dg->{checksumSeed} == $checksumSeed
312                     && ($blockSize == 0 || $dg->{blockSize} == $blockSize) ) {
313                 $dg->{fh}     = $fh;
314                 $dg->{cached} = 1;
315                 #
316                 # position the file at the start of the rsync block checksums
317                 # (4 (adler) + 16 (md4) bytes each)
318                 #
319                 return -8
320                     if ( !defined(seek($fh, -$dg->{nBlocks}*20 - 48, 2)) );
321             } else {
322                 #
323                 # cached checksums are not valid, so we close the
324                 # file and treat it as uncached.
325                 #
326                 $dg->{cachedInvalid} = 1;
327                 close($fh);
328             }
329         }
330     }
331     if ( !$dg->{cached} ) {
332         #
333         # This file doesn't have cached checksums, or the checksumSeed
334         # or blocksize doesn't match.  Open the file and prepare to
335         # compute the checksums.
336         #
337         $blockSize
338             = BackupPC::Xfer::RsyncDigest->blockSize($fileSize, $defBlkSize)
339                                     if ( $blockSize == 0 );
340         $dg->{checksumSeed} = $checksumSeed;
341         $dg->{blockSize}    = $blockSize;
342         $dg->{fh} = BackupPC::FileZIO->open($fileName, 0, $compress);
343         return -9 if ( !defined($dg->{fh}) );
344         if ( $needMD4) {
345             $dg->{csumDigest} = File::RsyncP::Digest->new;
346             $dg->{csumDigest}->add(pack("V", $dg->{checksumSeed}));
347         }
348     }
349     return (undef, $dg, $dg->{blockSize});
350 }
351
352 sub digestGet
353 {
354     my($dg, $num, $csumLen, $noPad) = @_;
355     my($fileData);
356     my $blockSize = $dg->{blockSize};
357
358     if ( $dg->{cached} ) {
359         my $thisNum = $num;
360         $thisNum = $dg->{nBlocks} if ( $thisNum > $dg->{nBlocks} );
361         read($dg->{fh}, $fileData, 20 * $thisNum);
362         $dg->{nBlocks} -= $thisNum;
363         if ( $thisNum < $num && !$noPad) {
364             #
365             # unexpected shortfall of data; pad with zero digest
366             #
367             $fileData .= pack("c", 0) x (20 * ($num - $thisNum));
368         }
369         return $dg->{digest}->blockDigestExtract($fileData, $csumLen);
370     } else {
371         if ( $dg->{fh}->read(\$fileData, $blockSize * $num) <= 0 ) {
372             #
373             # unexpected shortfall of data; pad with zeros
374             #
375             $fileData = pack("c", 0) x ($blockSize * $num) if ( !$noPad );
376         }
377         $dg->{csumDigest}->add($fileData) if ( $dg->{needMD4} );
378         return $dg->{digest}->blockDigest($fileData, $blockSize,
379                                            $csumLen, $dg->{checksumSeed});
380     }
381 }
382
383 sub digestEnd
384 {
385     my($dg, $skipMD4) = @_;
386     my($fileData);
387
388     if ( $dg->{cached} ) {
389         close($dg->{fh});
390         return $dg->{md4DigestOld} if ( $dg->{needMD4} );
391     } else {
392         #
393         # make sure we read the entire file for the file MD4 digest
394         #
395         if ( $dg->{needMD4} && !$skipMD4 ) {
396             my $fileData;
397             while ( $dg->{fh}->read(\$fileData, 65536) > 0 ) {
398                 $dg->{csumDigest}->add($fileData);
399             }
400         }
401         $dg->{fh}->close();
402         return $dg->{csumDigest}->digest if ( $dg->{needMD4} );
403     }
404 }
405
406 sub isCached
407 {
408     my($dg) = @_;
409  
410     return wantarray ? ($dg->{cached}, $dg->{cachedInvalid}) : $dg->{cached};
411 }
412
413 sub blockSizeCurr
414 {
415     my($dg) = @_;
416  
417     return $dg->{blockSize};
418 }
419
420 #
421 # Default log handler
422 #
423 sub logHandler
424 {
425     my($str) = @_;
426
427     print(STDERR $str, "\n");
428 }
429
430 #
431 # Set log handler to a new subroutine.
432 #
433 sub logHandlerSet
434 {
435     my($sub) = @_;
436
437     $Log = $sub;
438 }
439
440 1;