1 #============================================================= -*-perl-*-
8 # Craig Barratt <cbarratt@users.sourceforge.net>
11 # Copyright (C) 2002-2007 Craig Barratt
13 #========================================================================
15 # Version 3.2.0, released 31 Dec 2008.
17 # See http://backuppc.sourceforge.net.
19 #========================================================================
21 package BackupPC::Xfer::RsyncFileIO;
25 use Encode qw/from_to/;
26 use BackupPC::Attrib qw(:all);
28 use BackupPC::Xfer::RsyncDigest qw(:all);
29 use BackupPC::PoolWrite;
31 use constant S_HLINK_TARGET => 0400000; # this file is hardlink target
32 use constant S_IFMT => 0170000; # type of file
33 use constant S_IFDIR => 0040000; # directory
34 use constant S_IFCHR => 0020000; # character special
35 use constant S_IFBLK => 0060000; # block special
36 use constant S_IFREG => 0100000; # regular
37 use constant S_IFLNK => 0120000; # symbolic link
38 use constant S_IFSOCK => 0140000; # socket
39 use constant S_IFIFO => 0010000; # fifo
41 use vars qw( $RsyncLibOK );
44 eval "use File::RsyncP::Digest";
47 # Rsync module doesn't exist.
57 my($class, $options) = @_;
59 return if ( !$RsyncLibOK );
64 digest => File::RsyncP::Digest->new(),
67 logHandler => \&logHandler,
74 ExistFileCompSize => 0,
79 $fio->{digest}->protocol($fio->{protocol_version});
80 $fio->{shareM} = $fio->{bpc}->fileNameEltMangle($fio->{share});
81 $fio->{outDir} = "$fio->{xfer}{outDir}/new/";
82 $fio->{outDirSh} = "$fio->{outDir}/$fio->{shareM}/";
83 $fio->{view} = BackupPC::View->new($fio->{bpc}, $fio->{client},
85 $fio->{full} = $fio->{xfer}{type} eq "full" ? 1 : 0;
86 $fio->{newFilesFH} = $fio->{xfer}{newFilesFH};
87 $fio->{partialNum} = undef if ( !$fio->{full} );
92 # We publish our version to File::RsyncP. This is so File::RsyncP
93 # can provide backward compatibility to older FileIO code.
97 # undef or 1: protocol version 26, no hardlinks
98 # 2: protocol version 28, supports hardlinks
107 my($fio, $value) = @_;
109 $fio->{blockSize} = $value if ( defined($value) );
110 return $fio->{blockSize};
115 my($fio, $value) = @_;
117 if ( defined($value) ) {
118 $fio->{protocol_version} = $value;
119 $fio->{digest}->protocol($fio->{protocol_version});
121 return $fio->{protocol_version};
124 sub preserve_hard_links
126 my($fio, $value) = @_;
128 $fio->{preserve_hard_links} = $value if ( defined($value) );
129 return $fio->{preserve_hard_links};
135 $fio->{logHandler} = $sub;
136 BackupPC::Xfer::RsyncDigest->logHandlerSet($sub);
140 # Setup rsync checksum computation for the given file.
144 my($fio, $f, $needMD4, $defBlkSize, $phase) = @_;
146 $defBlkSize ||= $fio->{blockSize};
147 my $attr = $fio->attribGet($f, 1);
149 $fio->csumEnd if ( defined($fio->{csum}) );
150 return -1 if ( $attr->{type} != BPC_FTYPE_FILE );
153 # Rsync uses short checksums on the first phase. If the whole-file
154 # checksum fails, then the file is repeated with full checksums.
155 # So on phase 2 we verify the checksums if they are cached.
157 if ( ($phase > 0 || rand(1) < $fio->{cacheCheckProb})
159 && $fio->{checksumSeed} == RSYNC_CSUMSEED_CACHE ) {
160 my($err, $d, $blkSize) = BackupPC::Xfer::RsyncDigest->digestStart(
161 $attr->{fullPath}, $attr->{size}, 0,
162 $defBlkSize, $fio->{checksumSeed},
163 0, $attr->{compress}, 0,
164 $fio->{protocol_version});
166 $fio->log("Can't get rsync digests from $attr->{fullPath}"
167 . " (err=$err, name=$f->{name})");
168 $fio->{stats}{errorCnt}++;
171 my($isCached, $isInvalid) = $d->isCached;
172 if ( $fio->{logLevel} >= 5 ) {
173 $fio->log("$attr->{fullPath} verify; cached = $isCached,"
174 . " invalid = $isInvalid, phase = $phase");
176 if ( $isCached || $isInvalid ) {
177 my $ret = BackupPC::Xfer::RsyncDigest->digestAdd(
178 $attr->{fullPath}, $blkSize,
179 $fio->{checksumSeed}, 1, # verify
180 $fio->{protocol_version}
183 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
185 $fio->{stats}{errorCnt}++;
187 $fio->log("$f->{name}: verified cached digest")
188 if ( $fio->{logLevel} >= 2 );
193 (my $err, $fio->{csum}, my $blkSize)
194 = BackupPC::Xfer::RsyncDigest->digestStart($attr->{fullPath},
195 $attr->{size}, 0, $defBlkSize, $fio->{checksumSeed},
196 $needMD4, $attr->{compress}, 1, $fio->{protocol_version});
198 $fio->log("Can't get rsync digests from $attr->{fullPath}"
199 . " (err=$err, name=$f->{name})");
200 $fio->{stats}{errorCnt}++;
203 if ( $fio->{logLevel} >= 5 ) {
204 my($isCached, $invalid) = $fio->{csum}->isCached;
205 $fio->log("$attr->{fullPath} cache = $isCached,"
206 . " invalid = $invalid, phase = $phase");
213 my($fio, $num, $csumLen, $blockSize) = @_;
218 return if ( !defined($fio->{csum}) );
219 return $fio->{csum}->digestGet($num, $csumLen);
226 return if ( !defined($fio->{csum}) );
227 return $fio->{csum}->digestEnd();
234 my $attr = $fio->attribGet($f, 1);
236 $fio->readEnd if ( defined($fio->{fh}) );
237 if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
239 $attr->{compress})) ) {
240 $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
241 $fio->{stats}{errorCnt}++;
244 $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
253 return if ( !defined($fio->{fh}) );
254 if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
255 return $fio->readEnd;
257 $fio->log(sprintf("read returns %d bytes", length($fileData)))
258 if ( $fio->{logLevel} >= 8 );
266 return if ( !defined($fio->{fh}) );
268 $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
275 my($fio, $checksumSeed) = @_;
277 $fio->{checksumSeed} = $checksumSeed;
278 $fio->log("Checksum caching enabled (checksumSeed = $checksumSeed)")
279 if ( $fio->{logLevel} >= 1 && $checksumSeed == RSYNC_CSUMSEED_CACHE );
280 $fio->log("Checksum seed is $checksumSeed")
281 if ( $fio->{logLevel} >= 2 && $checksumSeed != RSYNC_CSUMSEED_CACHE );
286 my($fio, $localDir, $remoteDir) = @_;
288 $fio->{localDir} = $localDir;
289 $fio->{remoteDir} = $remoteDir;
294 my($fio, $share, $dir) = @_;
297 #$fio->log("viewCacheDir($share, $dir)");
298 if ( !defined($share) ) {
299 $share = $fio->{share};
300 $shareM = $fio->{shareM};
302 $shareM = $fio->{bpc}->fileNameEltMangle($share);
304 $shareM = "$shareM/$dir" if ( $dir ne "" );
305 return if ( defined($fio->{viewCache}{$shareM}) );
307 # purge old cache entries (ie: those that don't match the
308 # first part of $dir).
310 foreach my $d ( keys(%{$fio->{viewCache}}) ) {
311 delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
314 # fetch new directory attributes
316 $fio->{viewCache}{$shareM}
317 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
319 # also cache partial backup attrib data too
321 if ( defined($fio->{partialNum}) ) {
322 foreach my $d ( keys(%{$fio->{partialCache}}) ) {
323 delete($fio->{partialCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
325 $fio->{partialCache}{$shareM}
326 = $fio->{view}->dirAttrib($fio->{partialNum}, $share, $dir);
332 my($fio, $f, $noCache, $fname) = @_;
333 my($dir, $share, $shareM, $partial, $attr);
335 if ( !defined($fname) ) {
337 $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
338 if ( defined($fio->{xfer}{pathHdrSrc}) );
340 $fname =~ s{//+}{/}g;
341 if ( $fname =~ m{(.*)/(.*)}s ) {
342 $shareM = $fio->{shareM};
345 } elsif ( $fname ne "." ) {
346 $shareM = $fio->{shareM};
352 $fname = $fio->{share};
354 $shareM .= "/$dir" if ( $dir ne "" );
357 $share = $fio->{share} if ( !defined($share) );
358 my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
359 $attr = $dirAttr->{$fname};
361 $fio->viewCacheDir($share, $dir);
362 if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
364 } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
369 if ( $attr->{mode} & S_HLINK_TARGET ) {
370 $attr->{hlink_self} = 1;
371 $attr->{mode} &= ~S_HLINK_TARGET;
374 return ($attr, $partial);
379 my($fio, $f, $doHardLink) = @_;
381 my($attr) = $fio->attribGetWhere($f);
382 if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
383 $fio->log("$attr->{fullPath}: opening for hardlink read"
384 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
385 my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
388 if ( defined($fh) ) {
389 $fh->read(\$target, 65536);
391 $target =~ s/^\.?\/+//;
393 $fio->log("$attr->{fullPath}: can't open for hardlink read");
394 $fio->{stats}{errorCnt}++;
395 $attr->{type} = BPC_FTYPE_FILE;
398 $target = "/$target" if ( $target !~ /^\// );
399 $fio->log("$attr->{fullPath}: redirecting to $target")
400 if ( $fio->{logLevel} >= 4 );
402 ($attr) = $fio->attribGetWhere($f, 1, $target);
403 $fio->log(" ... now got $attr->{fullPath}")
404 if ( $fio->{logLevel} >= 4 );
412 my $mode = $f->{mode};
414 if ( ($mode & S_IFMT) == S_IFREG ) {
415 if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
416 return BPC_FTYPE_HARDLINK;
418 return BPC_FTYPE_FILE;
420 } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
421 return BPC_FTYPE_DIR;
422 } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
423 return BPC_FTYPE_SYMLINK;
424 } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
425 return BPC_FTYPE_CHARDEV;
426 } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
427 return BPC_FTYPE_BLOCKDEV;
428 } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
429 return BPC_FTYPE_FIFO;
430 } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
431 return BPC_FTYPE_SOCKET;
433 return BPC_FTYPE_UNKNOWN;
438 # Set the attributes for a file. Returns non-zero on error.
442 my($fio, $f, $placeHolder) = @_;
445 return if ( $placeHolder && $fio->{phase} > 0 );
447 if ( $f->{name} =~ m{(.*)/(.*)}s ) {
449 $dir = "$fio->{shareM}/" . $1;
450 } elsif ( $f->{name} eq "." ) {
452 $file = $fio->{share};
454 $dir = $fio->{shareM};
459 && (!defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir) ) {
461 # Flush any directories that don't match the first part
462 # of the new directory. Don't flush the top-level directory
463 # (ie: $dir eq "") since the "." might get sorted in the middle
464 # of other top-level directories or files.
466 foreach my $d ( keys(%{$fio->{attrib}}) ) {
467 next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
468 $fio->attribWrite($d);
470 $fio->{attribLastDir} = $dir;
472 if ( !exists($fio->{attrib}{$dir}) ) {
473 $fio->log("attribSet: dir=$dir not found") if ( $fio->{logLevel} >= 4 );
474 $fio->{attrib}{$dir} = BackupPC::Attrib->new({
475 compress => $fio->{xfer}{compress},
478 $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
479 if ( $dirM =~ m{(.*?)/(.*)}s );
480 my $path = $fio->{outDir} . $dirM;
481 if ( -f $fio->{attrib}{$dir}->fileName($path) ) {
482 if ( !$fio->{attrib}{$dir}->read($path) ) {
483 $fio->log(sprintf("Unable to read attribute file %s",
484 $fio->{attrib}{$dir}->fileName($path)));
486 $fio->log(sprintf("attribRead file %s",
487 $fio->{attrib}{$dir}->fileName($path)))
488 if ( $fio->{logLevel} >= 4 );
492 $fio->log("attribSet: dir=$dir exists") if ( $fio->{logLevel} >= 4 );
494 $fio->log("attribSet(dir=$dir, file=$file, size=$f->{size}, placeholder=$placeHolder)")
495 if ( $fio->{logLevel} >= 4 );
497 my $mode = $f->{mode};
499 $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
500 $fio->{attrib}{$dir}->set($file, {
501 type => $fio->mode2type($f),
505 size => $placeHolder ? -1 : $f->{size},
506 mtime => $f->{mtime},
516 if ( !defined($d) ) {
518 # flush all entries (in reverse order)
520 foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
521 $fio->attribWrite($d);
525 return if ( !defined($fio->{attrib}{$d}) );
528 # Set deleted files in the attributes. Any file in the view
529 # that doesn't have attributes is flagged as deleted for
530 # incremental dumps. All files sent by rsync have attributes
531 # temporarily set so we can do deletion detection. We also
532 # prune these temporary attributes.
538 $dir = $1 if ( $d =~ m{.+?/(.*)}s );
539 $fio->viewCacheDir(undef, $dir);
540 ##print("attribWrite $d,$dir\n");
541 ##$Data::Dumper::Indent = 1;
542 ##$fio->log("attribWrite $d,$dir");
543 ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
544 ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
545 ##print "viewCache = ", Dumper($fio->{attrib});
546 ##print "attrib = ", Dumper($fio->{attrib});
547 if ( defined($fio->{viewCache}{$d}) ) {
548 foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
550 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
551 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
553 # delete temporary attributes (skipped files)
555 if ( $a->{size} < 0 ) {
556 $fio->{attrib}{$d}->set($f, undef);
557 $fio->logFileAction("skip", {
558 %{$fio->{viewCache}{$d}{$f}},
560 }) if ( $fio->{logLevel} >= 2
561 && $a->{type} == BPC_FTYPE_FILE );
563 } elsif ( $fio->{phase} == 0 && !$fio->{full} ) {
564 ##print("Delete file $f\n");
565 $fio->logFileAction("delete", {
566 %{$fio->{viewCache}{$d}{$f}},
568 }) if ( $fio->{logLevel} >= 1 );
569 $fio->{attrib}{$d}->set($f, {
570 type => BPC_FTYPE_DELETED,
581 if ( $fio->{attrib}{$d}->fileCount || $fio->{phase} > 0 ) {
582 my $data = $fio->{attrib}{$d}->writeData;
585 $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
586 if ( $dirM =~ m{(.*?)/(.*)}s );
587 my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
588 $fio->log("attribWrite(dir=$d) -> $fileName")
589 if ( $fio->{logLevel} >= 4 );
590 my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
591 length($data), $fio->{xfer}{compress});
592 $poolWrite->write(\$data);
593 $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
596 delete($fio->{attrib}{$d});
601 my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
602 my($exists, $digest, $outSize, $errs) = $poolWrite->close;
604 $fileName =~ s{^/+}{};
605 $fio->log(@$errs) if ( defined($errs) && @$errs );
607 $fio->{stats}{TotalFileCnt}++;
608 $fio->{stats}{TotalFileSize} += $origSize;
612 $fio->{stats}{ExistFileCnt}++;
613 $fio->{stats}{ExistFileSize} += $origSize;
614 $fio->{stats}{ExistFileCompSize} += $outSize;
616 } elsif ( $outSize > 0 ) {
617 my $fh = $fio->{newFilesFH};
618 print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
620 return $exists && $origSize > 0;
627 return $fio->{stats};
631 # Make a given directory. Returns non-zero on error.
636 my $name = $1 if ( $f->{name} =~ /(.*)/s );
639 if ( $name eq "." ) {
640 $path = $fio->{outDirSh};
642 $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
644 $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
645 $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
646 $path = $1 if ( $path =~ /(.*)/s );
647 File::Path::mkpath($path, 0, 0777) if ( !-d $path );
648 return $fio->attribSet($f) if ( -d $path );
649 $fio->log("Can't create directory $path");
650 $fio->{stats}{errorCnt}++;
655 # Make a special file. Returns non-zero on error.
660 my $name = $1 if ( $f->{name} =~ /(.*)/s );
661 my $fNameM = $fio->{bpc}->fileNameMangle($name);
662 my $path = $fio->{outDirSh} . $fNameM;
663 my $attr = $fio->attribGet($f);
665 my $type = $fio->mode2type($f);
667 $fio->log("makeSpecial($path, $type, $f->{mode})")
668 if ( $fio->{logLevel} >= 5 );
669 if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
670 my($major, $minor, $fh, $fileData);
672 if ( defined($f->{rdev_major}) ) {
673 $major = $f->{rdev_major};
674 $minor = $f->{rdev_minor};
676 $major = $f->{rdev} >> 8;
677 $minor = $f->{rdev} & 0xff;
679 $str = "$major,$minor";
680 } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
682 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
686 if ( !defined($f->{hlink}) ) {
687 $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
688 . " on a regular non-hardlink file");
694 # Now see if the file is different, or this is a full, in which
695 # case we create the new file.
700 || $attr->{type} != $type
701 || $attr->{mtime} != $f->{mtime}
702 || $attr->{size} != $f->{size}
703 || $attr->{uid} != $f->{uid}
704 || $attr->{gid} != $f->{gid}
705 || $attr->{mode} != $f->{mode}
706 || $attr->{hlink_self} != $f->{hlink_self}
707 || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
709 || $fh->read(\$fileData, length($str) + 1) != length($str)
710 || $fileData ne $str ) {
711 $fh->close if ( defined($fh) );
712 $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
713 length($str), $fio->{xfer}{compress});
715 my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
717 $fio->logFileAction($exist ? "pool" : "create", $f)
718 if ( $fio->{logLevel} >= 1 );
719 return $fio->attribSet($f);
721 $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
723 $fh->close if ( defined($fh) );
727 # Make a hardlink. Returns non-zero on error.
728 # This actually gets called twice for each hardlink.
729 # Once as the file list is processed, and again at
730 # the end. BackupPC does them as it goes (since it is
731 # just saving the hardlink info and not actually making
736 my($fio, $f, $end) = @_;
739 return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
744 my($fio, $path) = @_;
746 $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)");
750 # Default log handler
756 print(STDERR $str, "\n");
760 # Handle one or more log messages
764 my($fio, @logStr) = @_;
766 foreach my $str ( @logStr ) {
767 next if ( $str eq "" );
768 $fio->{logHandler}($str);
773 # Generate a log file message for a completed file
777 my($fio, $action, $f) = @_;
778 my $owner = "$f->{uid}/$f->{gid}";
779 my $type = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
780 [($f->{mode} & S_IFMT) >> 12];
781 my $name = $f->{name};
783 if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
784 $name .= " -> $f->{link}";
785 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
786 && defined($f->{hlink}) && !$f->{hlink_self} ) {
787 $name .= " -> $f->{hlink}";
791 $fio->log(sprintf(" %-6s %1s%4o %9s %11.0f %s",
801 # If there is a partial and we are doing a full, we do an incremental
802 # against the partial and a full against the rest. This subroutine
803 # is how we tell File::RsyncP which files to ignore attributes on
804 # (ie: against the partial dump we do consider the attributes, but
805 # otherwise we ignore attributes).
811 return if ( !defined($fio->{partialNum}) );
812 my($attr, $isPartial) = $fio->attribGetWhere($f);
813 $fio->log("$f->{name}: just checking attributes from partial")
814 if ( $isPartial && $fio->{logLevel} >= 5 );
819 # This is called by File::RsyncP when a file is skipped because the
824 my($fio, $f, $attr) = @_;
827 # Unless this is a partial, this is normal so ignore it.
829 return if ( !defined($fio->{partialNum}) );
831 $fio->log("$f->{name}: skipped in partial; adding link")
832 if ( $fio->{logLevel} >= 5 );
833 $fio->{rxLocalAttr} = $attr;
835 $fio->{rxSize} = $attr->{size};
836 delete($fio->{rxInFd});
837 delete($fio->{rxOutFd});
838 delete($fio->{rxDigest});
839 delete($fio->{rxInData});
840 return $fio->fileDeltaRxDone();
844 # Start receive of file deltas for a particular file.
848 my($fio, $f, $cnt, $size, $remainder) = @_;
850 $fio->{rxFile} = $f; # remote file attributes
851 $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
852 $fio->{rxBlkCnt} = $cnt; # how many blocks we will receive
853 $fio->{rxBlkSize} = $size; # block size
854 $fio->{rxRemainder} = $remainder; # size of the last block
855 $fio->{rxMatchBlk} = 0; # current start of match
856 $fio->{rxMatchNext} = 0; # current next block of match
857 $fio->{rxSize} = 0; # size of received file
858 my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
859 if ( $fio->{rxFile}{size} != $rxSize ) {
860 $fio->{rxMatchBlk} = undef; # size different, so no file match
861 $fio->log("$fio->{rxFile}{name}: size doesn't match"
862 . " ($fio->{rxFile}{size} vs $rxSize)")
863 if ( $fio->{logLevel} >= 5 );
866 # If compression was off and now on, or on and now off, then
867 # don't do an exact match.
869 if ( defined($fio->{rxLocalAttr})
870 && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
871 $fio->{rxMatchBlk} = undef; # compression changed, so no file match
872 $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
873 . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
874 if ( $fio->{logLevel} >= 4 );
877 # If the local file is a hardlink then no match
879 if ( defined($fio->{rxLocalAttr})
880 && $fio->{rxLocalAttr}{type} == BPC_FTYPE_HARDLINK ) {
881 $fio->{rxMatchBlk} = undef;
882 $fio->log("$fio->{rxFile}{name}: no match on hardlinks")
883 if ( $fio->{logLevel} >= 4 );
885 # need to copy since hardlink attribGet overwrites the name
887 $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
889 delete($fio->{rxHLinkAttr});
891 delete($fio->{rxInFd});
892 delete($fio->{rxOutFd});
893 delete($fio->{rxDigest});
894 delete($fio->{rxInData});
898 # Process the next file delta for the current file. Returns 0 if ok,
899 # -1 if not. Must be called with either a block number, $blk, or new data,
900 # $newData, (not both) defined.
904 my($fio, $blk, $newData) = @_;
906 if ( defined($blk) ) {
907 if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
909 # got the next block in order; just keep track.
911 $fio->{rxMatchNext}++;
915 my $newDataLen = length($newData);
916 $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
917 if ( $fio->{logLevel} >= 8 );
918 if ( !defined($fio->{rxOutFd}) ) {
920 # maybe the file has no changes
922 if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
923 && !defined($blk) && !defined($newData) ) {
924 #$fio->log("$fio->{rxFile}{name}: file is unchanged");
925 # if ( $fio->{logLevel} >= 8 );
930 # need to open an output file where we will build the
933 $fio->{rxFile}{name} =~ /(.*)/s;
934 my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
935 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
936 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
937 $rxOutFile, $fio->{rxFile}{size},
938 $fio->{xfer}{compress});
939 $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
940 if ( $fio->{logLevel} >= 9 );
941 $fio->{rxOutFile} = $rxOutFile;
942 $fio->{rxOutFileRel} = $rxOutFileRel;
943 $fio->{rxDigest} = File::RsyncP::Digest->new();
944 $fio->{rxDigest}->protocol($fio->{protocol_version});
945 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
947 if ( defined($fio->{rxMatchBlk})
948 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
950 # Need to copy the sequence of blocks that matched. If the file
951 # is compressed we need to make a copy of the uncompressed file,
952 # since the compressed file is not seekable. Future optimizations
953 # could include only creating an uncompressed copy if the matching
954 # blocks were not monotonic, and to only do this if there are
955 # matching blocks (eg, maybe the entire file is new).
957 my $attr = $fio->{rxLocalAttr};
959 if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
960 my $inPath = $attr->{fullPath};
961 $inPath = $fio->{rxHLinkAttr}{fullPath}
962 if ( defined($fio->{rxHLinkAttr}) );
963 if ( $attr->{compress} ) {
964 if ( !defined($fh = BackupPC::FileZIO->open(
967 $attr->{compress})) ) {
968 $fio->log("Can't open $inPath");
969 $fio->{stats}{errorCnt}++;
972 if ( $attr->{size} < 16 * 1024 * 1024 ) {
974 # Cache the entire old file if it is less than 16MB
977 $fio->{rxInData} = "";
978 while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
979 $fio->{rxInData} .= $data;
981 $fio->log("$attr->{fullPath}: cached all $attr->{size}"
983 if ( $fio->{logLevel} >= 9 );
986 # Create and write a temporary output file
988 unlink("$fio->{outDirSh}RStmp")
989 if ( -f "$fio->{outDirSh}RStmp" );
990 if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
994 while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
995 if ( syswrite(F, $data) != length($data) ) {
996 $fio->log(sprintf("Can't write len=%d to %s",
997 length($data) , "$fio->{outDirSh}RStmp"));
999 $fio->{stats}{errorCnt}++;
1002 $byteCnt += length($data);
1004 $fio->{rxInFd} = *F;
1005 $fio->{rxInName} = "$fio->{outDirSh}RStmp";
1006 sysseek($fio->{rxInFd}, 0, 0);
1007 $fio->log("$attr->{fullPath}: copied $byteCnt,"
1008 . "$attr->{size} bytes to $fio->{rxInName}")
1009 if ( $fio->{logLevel} >= 9 );
1011 $fio->log("Unable to open $fio->{outDirSh}RStmp");
1013 $fio->{stats}{errorCnt}++;
1019 if ( open(F, "<", $inPath) ) {
1021 $fio->{rxInFd} = *F;
1022 $fio->{rxInName} = $attr->{fullPath};
1024 $fio->log("Unable to open $inPath");
1025 $fio->{stats}{errorCnt}++;
1030 my $lastBlk = $fio->{rxMatchNext} - 1;
1031 $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1033 if ( $fio->{logLevel} >= 9 );
1034 my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
1035 if ( defined($fio->{rxInFd})
1036 && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
1037 $fio->log("Unable to seek $fio->{rxInName} to $seekPosn");
1038 $fio->{stats}{errorCnt}++;
1041 my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
1042 my($thisCnt, $len, $data);
1043 for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
1044 $thisCnt = $cnt - $i;
1045 $thisCnt = 512 if ( $thisCnt > 512 );
1046 if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
1047 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
1049 $len = $thisCnt * $fio->{rxBlkSize};
1051 if ( defined($fio->{rxInData}) ) {
1052 $data = substr($fio->{rxInData}, $seekPosn, $len);
1055 my $got = sysread($fio->{rxInFd}, $data, $len);
1056 if ( $got != $len ) {
1057 my $inFileSize = -s $fio->{rxInName};
1058 $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1059 . " got=$got, seekPosn=$seekPosn"
1060 . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1061 . ",$attr->{size})");
1062 $fio->{stats}{errorCnt}++;
1067 $fio->{rxOutFd}->write(\$data);
1068 $fio->{rxDigest}->add($data);
1069 $fio->{rxSize} += length($data);
1071 $fio->{rxMatchBlk} = undef;
1073 if ( defined($blk) ) {
1075 # Remember the new block number
1077 $fio->{rxMatchBlk} = $blk;
1078 $fio->{rxMatchNext} = $blk + 1;
1080 if ( defined($newData) ) {
1082 # Write the new chunk
1084 my $len = length($newData);
1085 $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1086 if ( $fio->{logLevel} >= 9 );
1087 $fio->{rxOutFd}->write(\$newData);
1088 $fio->{rxDigest}->add($newData);
1089 $fio->{rxSize} += length($newData);
1094 # Finish up the current receive file. Returns undef if ok, -1 if not.
1095 # Returns 1 if the md4 digest doesn't match.
1099 my($fio, $md4, $phase) = @_;
1100 my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1103 close($fio->{rxInFd}) if ( defined($fio->{rxInFd}) );
1104 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1105 $fio->{phase} = $phase;
1108 # Check the final md4 digest
1110 if ( defined($md4) ) {
1112 if ( !defined($fio->{rxDigest}) ) {
1114 # File was exact match, but we still need to verify the
1115 # MD4 checksum. Compute the md4 digest (or fetch the
1118 if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1120 # block size doesn't matter: we're only going to
1121 # fetch the md4 file digest, not the block digests.
1123 my($err, $csum, $blkSize)
1124 = BackupPC::Xfer::RsyncDigest->digestStart(
1125 $attr->{fullPath}, $attr->{size},
1126 0, 2048, $fio->{checksumSeed}, 1,
1127 $attr->{compress}, 1,
1128 $fio->{protocol_version});
1130 $fio->log("Can't open $attr->{fullPath} for MD4"
1131 . " check (err=$err, $name)");
1132 $fio->{stats}{errorCnt}++;
1134 if ( $fio->{logLevel} >= 5 ) {
1135 my($isCached, $invalid) = $csum->isCached;
1136 $fio->log("MD4 $attr->{fullPath} cache = $isCached,"
1137 . " invalid = $invalid");
1139 $newDigest = $csum->digestEnd;
1141 $fio->{rxSize} = $attr->{size};
1144 # Empty file; just create an empty file digest
1146 $fio->{rxDigest} = File::RsyncP::Digest->new();
1147 $fio->{rxDigest}->protocol($fio->{protocol_version});
1148 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
1149 $newDigest = $fio->{rxDigest}->digest;
1151 $fio->log("$name got exact match") if ( $fio->{logLevel} >= 5 );
1153 $newDigest = $fio->{rxDigest}->digest;
1155 if ( $fio->{logLevel} >= 3 ) {
1156 my $md4Str = unpack("H*", $md4);
1157 my $newStr = unpack("H*", $newDigest);
1158 $fio->log("$name got digests $md4Str vs $newStr")
1160 if ( $md4 ne $newDigest ) {
1162 $fio->log("$name: fatal error: md4 doesn't match on retry;"
1164 $fio->{stats}{errorCnt}++;
1166 $fio->log("$name: md4 doesn't match: will retry in phase 1;"
1169 if ( defined($fio->{rxOutFd}) ) {
1170 $fio->{rxOutFd}->close;
1171 unlink($fio->{rxOutFile});
1173 delete($fio->{rxFile});
1174 delete($fio->{rxOutFile});
1180 # One special case is an empty file: if the file size is
1181 # zero we need to open the output file to create it.
1183 if ( $fio->{rxSize} == 0 ) {
1184 my $rxOutFileRel = "$fio->{shareM}/"
1185 . $fio->{bpc}->fileNameMangle($name);
1186 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
1187 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
1188 $rxOutFile, $fio->{rxSize},
1189 $fio->{xfer}{compress});
1191 if ( !defined($fio->{rxOutFd}) ) {
1193 # No output file, meaning original was an exact match.
1195 $fio->log("$name: nothing to do")
1196 if ( $fio->{logLevel} >= 5 );
1197 my $attr = $fio->{rxLocalAttr};
1198 my $f = $fio->{rxFile};
1199 $fio->logFileAction("same", $f) if ( $fio->{logLevel} >= 1 );
1201 || $attr->{type} != $f->{type}
1202 || $attr->{mtime} != $f->{mtime}
1203 || $attr->{size} != $f->{size}
1204 || $attr->{uid} != $f->{uid}
1205 || $attr->{gid} != $f->{gid}
1206 || $attr->{mode} != $f->{mode}
1207 || $attr->{hlink_self} != $f->{hlink_self} ) {
1209 # In the full case, or if the attributes are different,
1210 # we need to make a link from the previous file and
1211 # set the attributes.
1213 my $rxOutFile = $fio->{outDirSh}
1214 . $fio->{bpc}->fileNameMangle($name);
1215 my($exists, $digest, $origSize, $outSize, $errs)
1216 = BackupPC::PoolWrite::LinkOrCopy(
1221 $fio->{xfer}{compress});
1223 # Cumulate the stats
1225 $fio->{stats}{TotalFileCnt}++;
1226 $fio->{stats}{TotalFileSize} += $fio->{rxSize};
1227 $fio->{stats}{ExistFileCnt}++;
1228 $fio->{stats}{ExistFileSize} += $fio->{rxSize};
1229 $fio->{stats}{ExistFileCompSize} += -s $rxOutFile;
1230 $fio->{rxFile}{size} = $fio->{rxSize};
1231 $ret = $fio->attribSet($fio->{rxFile});
1232 $fio->log(@$errs) if ( defined($errs) && @$errs );
1234 if ( !$exists && $outSize > 0 ) {
1236 # the hard link failed, most likely because the target
1237 # file has too many links. We have copied the file
1238 # instead, so add this to the new file list.
1240 my $rxOutFileRel = "$fio->{shareM}/"
1241 . $fio->{bpc}->fileNameMangle($name);
1242 $rxOutFileRel =~ s{^/+}{};
1243 my $fh = $fio->{newFilesFH};
1244 print($fh "$digest $origSize $rxOutFileRel\n")
1245 if ( defined($fh) );
1249 my $exist = $fio->processClose($fio->{rxOutFd},
1250 $fio->{rxOutFileRel},
1252 $fio->logFileAction($exist ? "pool" : "create", $fio->{rxFile})
1253 if ( $fio->{logLevel} >= 1 );
1254 $fio->{rxFile}{size} = $fio->{rxSize};
1255 $ret = $fio->attribSet($fio->{rxFile});
1257 delete($fio->{rxDigest});
1258 delete($fio->{rxInData});
1259 delete($fio->{rxFile});
1260 delete($fio->{rxOutFile});
1265 # Callback function for BackupPC::View->find. Note the order of the
1266 # first two arguments.
1270 my($a, $fio, $fList, $outputFunc) = @_;
1271 my $name = $a->{relPath};
1273 my $type = $a->{type};
1274 my $extraAttribs = {};
1276 if ( $a->{mode} & S_HLINK_TARGET ) {
1277 $a->{hlink_self} = 1;
1278 $a->{mode} &= ~S_HLINK_TARGET;
1280 $n =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
1281 $fio->log("Sending $name (remote=$n) type = $type") if ( $fio->{logLevel} >= 1 );
1282 if ( $type == BPC_FTYPE_CHARDEV
1283 || $type == BPC_FTYPE_BLOCKDEV
1284 || $type == BPC_FTYPE_SYMLINK ) {
1285 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1287 if ( defined($fh) ) {
1288 $rdSize = $fh->read(\$str, $a->{size} + 1024);
1289 if ( $type == BPC_FTYPE_SYMLINK ) {
1291 # Reconstruct symbolic link
1293 $extraAttribs = { link => $str };
1294 if ( $rdSize != $a->{size} ) {
1296 $fio->log("$name: can't read exactly $a->{size} bytes");
1297 $fio->{stats}{errorCnt}++;
1299 } elsif ( $str =~ /(\d*),(\d*)/ ) {
1301 # Reconstruct char or block special major/minor device num
1303 # Note: char/block devices have $a->{size} = 0, so we
1304 # can't do an error check on $rdSize.
1307 rdev => $1 * 256 + $2,
1312 $fio->log("$name: unexpected special file contents $str");
1313 $fio->{stats}{errorCnt}++;
1318 $fio->log("$name: can't open");
1319 $fio->{stats}{errorCnt}++;
1321 } elsif ( $fio->{preserve_hard_links}
1322 && ($type == BPC_FTYPE_HARDLINK || $type == BPC_FTYPE_FILE)
1323 && ($type == BPC_FTYPE_HARDLINK
1324 || $fio->{protocol_version} < 27
1325 || $a->{hlink_self}) ) {
1327 # Fill in fake inode information so that the remote rsync
1328 # can correctly create hardlinks.
1330 $name =~ s/^\.?\/+//;
1331 my($target, $inode);
1333 if ( $type == BPC_FTYPE_HARDLINK ) {
1334 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0,
1336 if ( defined($fh) ) {
1337 $fh->read(\$target, 65536);
1339 $target =~ s/^\.?\/+//;
1340 if ( defined($fio->{hlinkFile2Num}{$target}) ) {
1341 $inode = $fio->{hlinkFile2Num}{$target};
1343 $inode = $fio->{fileListCnt};
1344 $fio->{hlinkFile2Num}{$target} = $inode;
1347 $fio->log("$a->{fullPath}: can't open for hardlink");
1348 $fio->{stats}{errorCnt}++;
1350 } elsif ( $a->{hlink_self} ) {
1351 if ( defined($fio->{hlinkFile2Num}{$name}) ) {
1352 $inode = $fio->{hlinkFile2Num}{$name};
1354 $inode = $fio->{fileListCnt};
1355 $fio->{hlinkFile2Num}{$name} = $inode;
1358 $inode = $fio->{fileListCnt} if ( !defined($inode) );
1359 $fio->log("$name: setting inode to $inode");
1368 mode => $a->{mode} & ~S_HLINK_TARGET,
1371 mtime => $a->{mtime},
1375 my $logName = $f->{name};
1376 from_to($f->{name}, "utf8", $fio->{clientCharset})
1377 if ( $fio->{clientCharset} ne "" );
1380 $logName = "$fio->{xfer}{pathHdrDest}/$logName";
1381 $logName =~ s{//+}{/}g;
1382 $f->{name} = $logName;
1383 $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1385 &$outputFunc($fList->encodeData);
1389 $fio->{fileListCnt}++;
1390 if ( $type != BPC_FTYPE_DIR ) {
1391 $fio->{stats}{TotalFileCnt}++;
1392 $fio->{stats}{TotalFileSize} += $a->{size};
1398 my($fio, $flist, $outputFunc) = @_;
1401 # Populate the file list with the files requested by the user.
1402 # Since some might be directories so we call BackupPC::View::find.
1404 $fio->log("fileListSend: sending file list: "
1405 . join(" ", @{$fio->{fileList}})) if ( $fio->{logLevel} >= 4 );
1406 $fio->{fileListCnt} = 0;
1407 $fio->{hlinkFile2Num} = {};
1408 foreach my $name ( @{$fio->{fileList}} ) {
1409 $fio->{view}->find($fio->{xfer}{bkupSrcNum},
1410 $fio->{xfer}{bkupSrcShare},
1412 \&fileListEltSend, $fio, $flist, $outputFunc);
1418 my($fio, $isChild) = @_;
1421 # If we are aborting early, remove the last file since
1422 # it was not complete
1424 if ( $isChild && defined($fio->{rxFile}) ) {
1425 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1426 if ( defined($fio->{rxFile}) ) {
1427 unlink($fio->{rxOutFile});
1428 $fio->log("finish: removing in-process file $fio->{rxFile}{name}");
1433 # Flush the attributes if this is the child
1435 $fio->attribWrite(undef) if ( $isChild );
1441 # join('',@_), kill 0;