* Various changes for 3.0.0beta1
[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.0beta1, released 30 Jul 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) = @_;
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     if ( $fileSize > 0 && $compress && $doCache >= 0 ) {
260         open(my $fh, "<", $fileName) || return -2;
261         binmode($fh);
262         return -3 if ( read($fh, $data, 1) != 1 );
263         my $ret;
264
265         if ( $data eq chr(0x78) && $doCache > 0
266                      && $checksumSeed == RSYNC_CSUMSEED_CACHE ) {
267             #
268             # RSYNC_CSUMSEED_CACHE (32761) is the magic number that
269             # rsync uses for checksumSeed with the --fixed-csum option.
270             #
271             # We now add the cached checksum data to the file.  There
272             # is a possible race condition here since two BackupPC_dump
273             # processes might call this function at the same time
274             # on the same file.  But this should be ok since both
275             # processes will write the same data, and the order
276             # in which they write it doesn't matter.
277             #
278             close($fh);
279             $ret = $dg->digestAdd($fileName,
280                             $blockSize
281                                 || BackupPC::Xfer::RsyncDigest->blockSize(
282                                                     $fileSize, $defBlkSize),
283                                 $checksumSeed);
284             if ( $ret < 0 ) {
285                 &$Log("digestAdd($fileName) failed ($ret)");
286             }
287             #
288             # now re-open the file and re-read the first byte
289             #
290             open($fh, "<", $fileName) || return -4;
291             binmode($fh);
292             return -5 if ( read($fh, $data, 1) != 1 );
293         }
294         if ( $ret >= 0 && $data eq chr(0xd6) ) {
295             #
296             # Looks like this file has cached checksums
297             # Read the last 48 bytes: that's 2 file MD4s (32 bytes)
298             # plus 4 words of meta data
299             #
300             return -6 if ( !defined(seek($fh, -48, 2)) ); 
301             return -7 if ( read($fh, $data, 48) != 48 );
302             ($dg->{md4DigestOld},
303              $dg->{md4Digest},
304              $dg->{blockSize},
305              $dg->{checksumSeed},
306              $dg->{nBlocks},
307              $dg->{magic}) = unpack("a16 a16 V V V V", $data);
308             if ( $dg->{magic} == 0x5fe3c289
309                     && $dg->{checksumSeed} == $checksumSeed
310                     && ($blockSize == 0 || $dg->{blockSize} == $blockSize) ) {
311                 $dg->{fh}     = $fh;
312                 $dg->{cached} = 1;
313                 #
314                 # position the file at the start of the rsync block checksums
315                 # (4 (adler) + 16 (md4) bytes each)
316                 #
317                 return -8
318                     if ( !defined(seek($fh, -$dg->{nBlocks}*20 - 48, 2)) );
319             } else {
320                 #
321                 # cached checksums are not valid, so we close the
322                 # file and treat it as uncached.
323                 #
324                 $dg->{cachedInvalid} = 1;
325                 close($fh);
326             }
327         }
328     }
329     if ( !$dg->{cached} ) {
330         #
331         # This file doesn't have cached checksums, or the checksumSeed
332         # or blocksize doesn't match.  Open the file and prepare to
333         # compute the checksums.
334         #
335         $blockSize
336             = BackupPC::Xfer::RsyncDigest->blockSize($fileSize, $defBlkSize)
337                                     if ( $blockSize == 0 );
338         $dg->{checksumSeed} = $checksumSeed;
339         $dg->{blockSize}    = $blockSize;
340         $dg->{fh} = BackupPC::FileZIO->open($fileName, 0, $compress);
341         return -9 if ( !defined($dg->{fh}) );
342         if ( $needMD4) {
343             $dg->{csumDigest} = File::RsyncP::Digest->new;
344             $dg->{csumDigest}->add(pack("V", $dg->{checksumSeed}));
345         }
346     }
347     return (undef, $dg, $dg->{blockSize});
348 }
349
350 sub digestGet
351 {
352     my($dg, $num, $csumLen, $noPad) = @_;
353     my($fileData);
354     my $blockSize = $dg->{blockSize};
355
356     if ( $dg->{cached} ) {
357         my $thisNum = $num;
358         $thisNum = $dg->{nBlocks} if ( $thisNum > $dg->{nBlocks} );
359         read($dg->{fh}, $fileData, 20 * $thisNum);
360         $dg->{nBlocks} -= $thisNum;
361         if ( $thisNum < $num && !$noPad) {
362             #
363             # unexpected shortfall of data; pad with zero digest
364             #
365             $fileData .= pack("c", 0) x (20 * ($num - $thisNum));
366         }
367         return $dg->{digest}->blockDigestExtract($fileData, $csumLen);
368     } else {
369         if ( $dg->{fh}->read(\$fileData, $blockSize * $num) <= 0 ) {
370             #
371             # unexpected shortfall of data; pad with zeros
372             #
373             $fileData = pack("c", 0) x ($blockSize * $num) if ( !$noPad );
374         }
375         $dg->{csumDigest}->add($fileData) if ( $dg->{needMD4} );
376         return $dg->{digest}->blockDigest($fileData, $blockSize,
377                                            $csumLen, $dg->{checksumSeed});
378     }
379 }
380
381 sub digestEnd
382 {
383     my($dg, $skipMD4) = @_;
384     my($fileData);
385
386     if ( $dg->{cached} ) {
387         close($dg->{fh});
388         return $dg->{md4DigestOld} if ( $dg->{needMD4} );
389     } else {
390         #
391         # make sure we read the entire file for the file MD4 digest
392         #
393         if ( $dg->{needMD4} && !$skipMD4 ) {
394             my $fileData;
395             while ( $dg->{fh}->read(\$fileData, 65536) > 0 ) {
396                 $dg->{csumDigest}->add($fileData);
397             }
398         }
399         $dg->{fh}->close();
400         return $dg->{csumDigest}->digest if ( $dg->{needMD4} );
401     }
402 }
403
404 sub isCached
405 {
406     my($dg) = @_;
407  
408     return wantarray ? ($dg->{cached}, $dg->{cachedInvalid}) : $dg->{cached};
409 }
410
411 sub blockSizeCurr
412 {
413     my($dg) = @_;
414  
415     return $dg->{blockSize};
416 }
417
418 #
419 # Default log handler
420 #
421 sub logHandler
422 {
423     my($str) = @_;
424
425     print(STDERR $str, "\n");
426 }
427
428 #
429 # Set log handler to a new subroutine.
430 #
431 sub logHandlerSet
432 {
433     my($sub) = @_;
434
435     $Log = $sub;
436 }
437
438 1;