1 #============================================================= -*-perl-*-
8 # Craig Barratt <cbarratt@users.sourceforge.net>
11 # Copyright (C) 2002-2003 Craig Barratt
13 #========================================================================
15 # Version 3.0.0beta2, released 11 Nov 2006.
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 my($isCached, $isInvalid) = $d->isCached;
165 if ( $fio->{logLevel} >= 5 ) {
166 $fio->log("$attr->{fullPath} verify; cached = $isCached,"
167 . " invalid = $isInvalid, phase = $phase");
169 if ( $isCached || $isInvalid ) {
170 my $ret = BackupPC::Xfer::RsyncDigest->digestAdd(
171 $attr->{fullPath}, $blkSize,
172 $fio->{checksumSeed}, 1 # verify
175 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
177 $fio->{stats}{errorCnt}++;
179 $fio->log("$f->{name}: verified cached digest")
180 if ( $fio->{logLevel} >= 2 );
185 (my $err, $fio->{csum}, my $blkSize)
186 = BackupPC::Xfer::RsyncDigest->digestStart($attr->{fullPath},
187 $attr->{size}, 0, $defBlkSize, $fio->{checksumSeed},
188 $needMD4, $attr->{compress}, 1);
189 if ( $fio->{logLevel} >= 5 ) {
190 my($isCached, $invalid) = $fio->{csum}->isCached;
191 $fio->log("$attr->{fullPath} cache = $isCached,"
192 . " invalid = $invalid, phase = $phase");
195 $fio->log("Can't get rsync digests from $attr->{fullPath}"
196 . " (err=$err, name=$f->{name})");
197 $fio->{stats}{errorCnt}++;
205 my($fio, $num, $csumLen, $blockSize) = @_;
210 return if ( !defined($fio->{csum}) );
211 return $fio->{csum}->digestGet($num, $csumLen);
218 return if ( !defined($fio->{csum}) );
219 return $fio->{csum}->digestEnd();
226 my $attr = $fio->attribGet($f, 1);
228 $fio->readEnd if ( defined($fio->{fh}) );
229 if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
231 $attr->{compress})) ) {
232 $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
233 $fio->{stats}{errorCnt}++;
236 $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
245 return if ( !defined($fio->{fh}) );
246 if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
247 return $fio->readEnd;
249 $fio->log(sprintf("read returns %d bytes", length($fileData)))
250 if ( $fio->{logLevel} >= 8 );
258 return if ( !defined($fio->{fh}) );
260 $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
267 my($fio, $checksumSeed) = @_;
269 $fio->{checksumSeed} = $checksumSeed;
270 $fio->log("Checksum caching enabled (checksumSeed = $checksumSeed)")
271 if ( $fio->{logLevel} >= 1 && $checksumSeed == RSYNC_CSUMSEED_CACHE );
272 $fio->log("Checksum seed is $checksumSeed")
273 if ( $fio->{logLevel} >= 2 && $checksumSeed != RSYNC_CSUMSEED_CACHE );
278 my($fio, $localDir, $remoteDir) = @_;
280 $fio->{localDir} = $localDir;
281 $fio->{remoteDir} = $remoteDir;
286 my($fio, $share, $dir) = @_;
289 #$fio->log("viewCacheDir($share, $dir)");
290 if ( !defined($share) ) {
291 $share = $fio->{share};
292 $shareM = $fio->{shareM};
294 $shareM = $fio->{bpc}->fileNameEltMangle($share);
296 $shareM = "$shareM/$dir" if ( $dir ne "" );
297 return if ( defined($fio->{viewCache}{$shareM}) );
299 # purge old cache entries (ie: those that don't match the
300 # first part of $dir).
302 foreach my $d ( keys(%{$fio->{viewCache}}) ) {
303 delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
306 # fetch new directory attributes
308 $fio->{viewCache}{$shareM}
309 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
311 # also cache partial backup attrib data too
313 if ( defined($fio->{partialNum}) ) {
314 foreach my $d ( keys(%{$fio->{partialCache}}) ) {
315 delete($fio->{partialCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
317 $fio->{partialCache}{$shareM}
318 = $fio->{view}->dirAttrib($fio->{partialNum}, $share, $dir);
324 my($fio, $f, $noCache) = @_;
325 my($dir, $fname, $share, $shareM, $partial, $attr);
328 $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
329 if ( defined($fio->{xfer}{pathHdrSrc}) );
330 $fname =~ s{//+}{/}g;
331 if ( $fname =~ m{(.*)/(.*)}s ) {
332 $shareM = $fio->{shareM};
335 } elsif ( $fname ne "." ) {
336 $shareM = $fio->{shareM};
342 $fname = $fio->{share};
344 $shareM .= "/$dir" if ( $dir ne "" );
347 $share = $fio->{share} if ( !defined($share) );
348 my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
349 $attr = $dirAttr->{$fname};
351 $fio->viewCacheDir($share, $dir);
352 if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
354 } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
359 if ( $attr->{mode} & S_HLINK_TARGET ) {
360 $attr->{hlink_self} = 1;
361 $attr->{mode} &= ~S_HLINK_TARGET;
364 return ($attr, $partial);
369 my($fio, $f, $doHardLink) = @_;
371 my($attr) = $fio->attribGetWhere($f);
372 if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
373 $fio->log("$attr->{fullPath}: opening for hardlink read"
374 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
375 my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
378 if ( defined($fh) ) {
379 $fh->read(\$target, 65536);
381 $target =~ s/^\.?\/+//;
383 $fio->log("$attr->{fullPath}: can't open for hardlink read");
384 $fio->{stats}{errorCnt}++;
385 $attr->{type} = BPC_FTYPE_FILE;
388 $target = "/$target" if ( $target !~ /^\// );
389 $fio->log("$attr->{fullPath}: redirecting to $target (will trim "
390 . "$fio->{xfer}{pathHdrSrc})") if ( $fio->{logLevel} >= 4 );
391 $target =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
394 # Note: overwrites name to point to real file
396 $f->{name} = $target;
397 ($attr) = $fio->attribGetWhere($f, 1);
398 $fio->log(" ... now got $attr->{fullPath}")
399 if ( $fio->{logLevel} >= 4 );
407 my $mode = $f->{mode};
409 if ( ($mode & S_IFMT) == S_IFREG ) {
410 if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
411 return BPC_FTYPE_HARDLINK;
413 return BPC_FTYPE_FILE;
415 } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
416 return BPC_FTYPE_DIR;
417 } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
418 return BPC_FTYPE_SYMLINK;
419 } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
420 return BPC_FTYPE_CHARDEV;
421 } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
422 return BPC_FTYPE_BLOCKDEV;
423 } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
424 return BPC_FTYPE_FIFO;
425 } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
426 return BPC_FTYPE_SOCKET;
428 return BPC_FTYPE_UNKNOWN;
433 # Set the attributes for a file. Returns non-zero on error.
437 my($fio, $f, $placeHolder) = @_;
440 if ( $f->{name} =~ m{(.*)/(.*)}s ) {
442 $dir = "$fio->{shareM}/" . $1;
443 } elsif ( $f->{name} eq "." ) {
445 $file = $fio->{share};
447 $dir = $fio->{shareM};
451 if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
453 # Flush any directories that don't match the first part
454 # of the new directory
456 foreach my $d ( keys(%{$fio->{attrib}}) ) {
457 next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
458 $fio->attribWrite($d);
460 $fio->{attribLastDir} = $dir;
462 if ( !exists($fio->{attrib}{$dir}) ) {
463 $fio->{attrib}{$dir} = BackupPC::Attrib->new({
464 compress => $fio->{xfer}{compress},
466 my $path = $fio->{outDir} . $dir;
467 if ( -f $fio->{attrib}{$dir}->fileName($path)
468 && !$fio->{attrib}{$dir}->read($path) ) {
469 $fio->log(sprintf("Unable to read attribute file %s",
470 $fio->{attrib}{$dir}->fileName($path)));
473 $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
475 my $mode = $f->{mode};
477 $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
478 $fio->{attrib}{$dir}->set($file, {
479 type => $fio->mode2type($f),
483 size => $placeHolder ? -1 : $f->{size},
484 mtime => $f->{mtime},
495 # Don't write attributes on 2nd phase - they're already
496 # taken care of during the first phase.
498 return if ( $fio->{phase} > 0 );
499 if ( !defined($d) ) {
501 # flush all entries (in reverse order)
503 foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
504 $fio->attribWrite($d);
508 return if ( !defined($fio->{attrib}{$d}) );
510 # Set deleted files in the attributes. Any file in the view
511 # that doesn't have attributes is flagged as deleted for
512 # incremental dumps. All files sent by rsync have attributes
513 # temporarily set so we can do deletion detection. We also
514 # prune these temporary attributes.
520 $dir = $1 if ( $d =~ m{.+?/(.*)}s );
521 $fio->viewCacheDir(undef, $dir);
522 ##print("attribWrite $d,$dir\n");
523 ##$Data::Dumper::Indent = 1;
524 ##$fio->log("attribWrite $d,$dir");
525 ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
526 ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
527 ##print "viewCache = ", Dumper($fio->{attrib});
528 ##print "attrib = ", Dumper($fio->{attrib});
529 if ( defined($fio->{viewCache}{$d}) ) {
530 foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
532 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
533 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
535 # delete temporary attributes (skipped files)
537 if ( $a->{size} < 0 ) {
538 $fio->{attrib}{$d}->set($f, undef);
539 $fio->logFileAction("skip", {
540 %{$fio->{viewCache}{$d}{$f}},
542 }) if ( $fio->{logLevel} >= 2
543 && $a->{type} == BPC_FTYPE_FILE );
545 } elsif ( !$fio->{full} ) {
546 ##print("Delete file $f\n");
547 $fio->logFileAction("delete", {
548 %{$fio->{viewCache}{$d}{$f}},
550 }) if ( $fio->{logLevel} >= 1 );
551 $fio->{attrib}{$d}->set($f, {
552 type => BPC_FTYPE_DELETED,
563 if ( $fio->{attrib}{$d}->fileCount ) {
564 my $data = $fio->{attrib}{$d}->writeData;
567 $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
568 if ( $dirM =~ m{(.*?)/(.*)}s );
569 my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
570 $fio->log("attribWrite(dir=$d) -> $fileName")
571 if ( $fio->{logLevel} >= 4 );
572 my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
573 length($data), $fio->{xfer}{compress});
574 $poolWrite->write(\$data);
575 $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
578 delete($fio->{attrib}{$d});
583 my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
584 my($exists, $digest, $outSize, $errs) = $poolWrite->close;
586 $fileName =~ s{^/+}{};
587 $fio->log(@$errs) if ( defined($errs) && @$errs );
589 $fio->{stats}{TotalFileCnt}++;
590 $fio->{stats}{TotalFileSize} += $origSize;
594 $fio->{stats}{ExistFileCnt}++;
595 $fio->{stats}{ExistFileSize} += $origSize;
596 $fio->{stats}{ExistFileCompSize} += $outSize;
598 } elsif ( $outSize > 0 ) {
599 my $fh = $fio->{newFilesFH};
600 print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
602 return $exists && $origSize > 0;
609 return $fio->{stats};
613 # Make a given directory. Returns non-zero on error.
618 my $name = $1 if ( $f->{name} =~ /(.*)/s );
621 if ( $name eq "." ) {
622 $path = $fio->{outDirSh};
624 $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
626 $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
627 $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
628 $path = $1 if ( $path =~ /(.*)/s );
629 File::Path::mkpath($path, 0, 0777) if ( !-d $path );
630 return $fio->attribSet($f) if ( -d $path );
631 $fio->log("Can't create directory $path");
632 $fio->{stats}{errorCnt}++;
637 # Make a special file. Returns non-zero on error.
642 my $name = $1 if ( $f->{name} =~ /(.*)/s );
643 my $fNameM = $fio->{bpc}->fileNameMangle($name);
644 my $path = $fio->{outDirSh} . $fNameM;
645 my $attr = $fio->attribGet($f);
647 my $type = $fio->mode2type($f);
649 $fio->log("makeSpecial($path, $type, $f->{mode})")
650 if ( $fio->{logLevel} >= 5 );
651 if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
652 my($major, $minor, $fh, $fileData);
654 if ( defined($f->{rdev_major}) ) {
655 $major = $f->{rdev_major};
656 $minor = $f->{rdev_minor};
658 $major = $f->{rdev} >> 8;
659 $minor = $f->{rdev} & 0xff;
661 $str = "$major,$minor";
662 } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
664 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
668 if ( !defined($f->{hlink}) ) {
669 $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
670 . " on a regular non-hardlink file");
676 # Now see if the file is different, or this is a full, in which
677 # case we create the new file.
682 || $attr->{type} != $type
683 || $attr->{mtime} != $f->{mtime}
684 || $attr->{size} != $f->{size}
685 || $attr->{uid} != $f->{uid}
686 || $attr->{gid} != $f->{gid}
687 || $attr->{mode} != $f->{mode}
688 || $attr->{hlink_self} != $f->{hlink_self}
689 || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
691 || $fh->read(\$fileData, length($str) + 1) != length($str)
692 || $fileData ne $str ) {
693 $fh->close if ( defined($fh) );
694 $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
695 length($str), $fio->{xfer}{compress});
697 my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
699 $fio->logFileAction($exist ? "pool" : "create", $f)
700 if ( $fio->{logLevel} >= 1 );
701 return $fio->attribSet($f);
703 $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
705 $fh->close if ( defined($fh) );
709 # Make a hardlink. Returns non-zero on error.
710 # This actually gets called twice for each hardlink.
711 # Once as the file list is processed, and again at
712 # the end. BackupPC does them as it goes (since it is
713 # just saving the hardlink info and not actually making
718 my($fio, $f, $end) = @_;
721 return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
726 my($fio, $path) = @_;
728 $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)");
732 # Default log handler
738 print(STDERR $str, "\n");
742 # Handle one or more log messages
746 my($fio, @logStr) = @_;
748 foreach my $str ( @logStr ) {
749 next if ( $str eq "" );
750 $fio->{logHandler}($str);
755 # Generate a log file message for a completed file
759 my($fio, $action, $f) = @_;
760 my $owner = "$f->{uid}/$f->{gid}";
761 my $type = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
762 [($f->{mode} & S_IFMT) >> 12];
763 my $name = $f->{name};
765 if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
766 $name .= " -> $f->{link}";
767 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
768 && defined($f->{hlink}) && !$f->{hlink_self} ) {
769 $name .= " -> $f->{hlink}";
773 $fio->log(sprintf(" %-6s %1s%4o %9s %11.0f %s",
783 # If there is a partial and we are doing a full, we do an incremental
784 # against the partial and a full against the rest. This subroutine
785 # is how we tell File::RsyncP which files to ignore attributes on
786 # (ie: against the partial dump we do consider the attributes, but
787 # otherwise we ignore attributes).
793 return if ( !defined($fio->{partialNum}) );
794 my($attr, $isPartial) = $fio->attribGetWhere($f);
795 $fio->log("$f->{name}: just checking attributes from partial")
796 if ( $isPartial && $fio->{logLevel} >= 5 );
801 # This is called by File::RsyncP when a file is skipped because the
806 my($fio, $f, $attr) = @_;
809 # Unless this is a partial, this is normal so ignore it.
811 return if ( !defined($fio->{partialNum}) );
813 $fio->log("$f->{name}: skipped in partial; adding link")
814 if ( $fio->{logLevel} >= 5 );
815 $fio->{rxLocalAttr} = $attr;
817 $fio->{rxSize} = $attr->{size};
818 delete($fio->{rxInFd});
819 delete($fio->{rxOutFd});
820 delete($fio->{rxDigest});
821 delete($fio->{rxInData});
822 return $fio->fileDeltaRxDone();
826 # Start receive of file deltas for a particular file.
830 my($fio, $f, $cnt, $size, $remainder) = @_;
832 $fio->{rxFile} = $f; # remote file attributes
833 $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
834 $fio->{rxBlkCnt} = $cnt; # how many blocks we will receive
835 $fio->{rxBlkSize} = $size; # block size
836 $fio->{rxRemainder} = $remainder; # size of the last block
837 $fio->{rxMatchBlk} = 0; # current start of match
838 $fio->{rxMatchNext} = 0; # current next block of match
839 $fio->{rxSize} = 0; # size of received file
840 my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
841 if ( $fio->{rxFile}{size} != $rxSize ) {
842 $fio->{rxMatchBlk} = undef; # size different, so no file match
843 $fio->log("$fio->{rxFile}{name}: size doesn't match"
844 . " ($fio->{rxFile}{size} vs $rxSize)")
845 if ( $fio->{logLevel} >= 5 );
848 # If compression was off and now on, or on and now off, then
849 # don't do an exact match.
851 if ( defined($fio->{rxLocalAttr})
852 && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
853 $fio->{rxMatchBlk} = undef; # compression changed, so no file match
854 $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
855 . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
856 if ( $fio->{logLevel} >= 4 );
859 # If the local file is a hardlink then no match
861 if ( defined($fio->{rxLocalAttr})
862 && $fio->{rxLocalAttr}{type} == BPC_FTYPE_HARDLINK ) {
863 $fio->{rxMatchBlk} = undef;
864 $fio->log("$fio->{rxFile}{name}: no match on hardlinks")
865 if ( $fio->{logLevel} >= 4 );
867 # need to copy since hardlink attribGet overwrites the name
869 $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
871 delete($fio->{rxHLinkAttr});
873 delete($fio->{rxInFd});
874 delete($fio->{rxOutFd});
875 delete($fio->{rxDigest});
876 delete($fio->{rxInData});
880 # Process the next file delta for the current file. Returns 0 if ok,
881 # -1 if not. Must be called with either a block number, $blk, or new data,
882 # $newData, (not both) defined.
886 my($fio, $blk, $newData) = @_;
888 if ( defined($blk) ) {
889 if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
891 # got the next block in order; just keep track.
893 $fio->{rxMatchNext}++;
897 my $newDataLen = length($newData);
898 $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
899 if ( $fio->{logLevel} >= 8 );
900 if ( !defined($fio->{rxOutFd}) ) {
902 # maybe the file has no changes
904 if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
905 && !defined($blk) && !defined($newData) ) {
906 #$fio->log("$fio->{rxFile}{name}: file is unchanged");
907 # if ( $fio->{logLevel} >= 8 );
912 # need to open an output file where we will build the
915 $fio->{rxFile}{name} =~ /(.*)/s;
916 my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
917 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
918 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
919 $rxOutFile, $fio->{rxFile}{size},
920 $fio->{xfer}{compress});
921 $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
922 if ( $fio->{logLevel} >= 9 );
923 $fio->{rxOutFile} = $rxOutFile;
924 $fio->{rxOutFileRel} = $rxOutFileRel;
925 $fio->{rxDigest} = File::RsyncP::Digest->new();
926 $fio->{rxDigest}->protocol($fio->{protocol_version});
927 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
929 if ( defined($fio->{rxMatchBlk})
930 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
932 # Need to copy the sequence of blocks that matched. If the file
933 # is compressed we need to make a copy of the uncompressed file,
934 # since the compressed file is not seekable. Future optimizations
935 # could include only creating an uncompressed copy if the matching
936 # blocks were not monotonic, and to only do this if there are
937 # matching blocks (eg, maybe the entire file is new).
939 my $attr = $fio->{rxLocalAttr};
941 if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
942 my $inPath = $attr->{fullPath};
943 $inPath = $fio->{rxHLinkAttr}{fullPath}
944 if ( defined($fio->{rxHLinkAttr}) );
945 if ( $attr->{compress} ) {
946 if ( !defined($fh = BackupPC::FileZIO->open(
949 $attr->{compress})) ) {
950 $fio->log("Can't open $inPath");
951 $fio->{stats}{errorCnt}++;
954 if ( $attr->{size} < 16 * 1024 * 1024 ) {
956 # Cache the entire old file if it is less than 16MB
959 $fio->{rxInData} = "";
960 while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
961 $fio->{rxInData} .= $data;
963 $fio->log("$attr->{fullPath}: cached all $attr->{size}"
965 if ( $fio->{logLevel} >= 9 );
968 # Create and write a temporary output file
970 unlink("$fio->{outDirSh}RStmp")
971 if ( -f "$fio->{outDirSh}RStmp" );
972 if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
976 while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
977 if ( syswrite(F, $data) != length($data) ) {
978 $fio->log(sprintf("Can't write len=%d to %s",
979 length($data) , "$fio->{outDirSh}RStmp"));
981 $fio->{stats}{errorCnt}++;
984 $byteCnt += length($data);
987 $fio->{rxInName} = "$fio->{outDirSh}RStmp";
988 sysseek($fio->{rxInFd}, 0, 0);
989 $fio->log("$attr->{fullPath}: copied $byteCnt,"
990 . "$attr->{size} bytes to $fio->{rxInName}")
991 if ( $fio->{logLevel} >= 9 );
993 $fio->log("Unable to open $fio->{outDirSh}RStmp");
995 $fio->{stats}{errorCnt}++;
1001 if ( open(F, "<", $inPath) ) {
1003 $fio->{rxInFd} = *F;
1004 $fio->{rxInName} = $attr->{fullPath};
1006 $fio->log("Unable to open $inPath");
1007 $fio->{stats}{errorCnt}++;
1012 my $lastBlk = $fio->{rxMatchNext} - 1;
1013 $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1015 if ( $fio->{logLevel} >= 9 );
1016 my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
1017 if ( defined($fio->{rxInFd})
1018 && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
1019 $fio->log("Unable to seek $fio->{rxInName} to $seekPosn");
1020 $fio->{stats}{errorCnt}++;
1023 my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
1024 my($thisCnt, $len, $data);
1025 for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
1026 $thisCnt = $cnt - $i;
1027 $thisCnt = 512 if ( $thisCnt > 512 );
1028 if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
1029 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
1031 $len = $thisCnt * $fio->{rxBlkSize};
1033 if ( defined($fio->{rxInData}) ) {
1034 $data = substr($fio->{rxInData}, $seekPosn, $len);
1037 my $got = sysread($fio->{rxInFd}, $data, $len);
1038 if ( $got != $len ) {
1039 my $inFileSize = -s $fio->{rxInName};
1040 $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1041 . " got=$got, seekPosn=$seekPosn"
1042 . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1043 . ",$attr->{size})");
1044 $fio->{stats}{errorCnt}++;
1049 $fio->{rxOutFd}->write(\$data);
1050 $fio->{rxDigest}->add($data);
1051 $fio->{rxSize} += length($data);
1053 $fio->{rxMatchBlk} = undef;
1055 if ( defined($blk) ) {
1057 # Remember the new block number
1059 $fio->{rxMatchBlk} = $blk;
1060 $fio->{rxMatchNext} = $blk + 1;
1062 if ( defined($newData) ) {
1064 # Write the new chunk
1066 my $len = length($newData);
1067 $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1068 if ( $fio->{logLevel} >= 9 );
1069 $fio->{rxOutFd}->write(\$newData);
1070 $fio->{rxDigest}->add($newData);
1071 $fio->{rxSize} += length($newData);
1076 # Finish up the current receive file. Returns undef if ok, -1 if not.
1077 # Returns 1 if the md4 digest doesn't match.
1081 my($fio, $md4, $phase) = @_;
1082 my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1085 close($fio->{rxInFd}) if ( defined($fio->{rxInFd}) );
1086 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1087 $fio->{phase} = $phase;
1090 # Check the final md4 digest
1092 if ( defined($md4) ) {
1094 if ( !defined($fio->{rxDigest}) ) {
1096 # File was exact match, but we still need to verify the
1097 # MD4 checksum. Compute the md4 digest (or fetch the
1100 if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1102 # block size doesn't matter: we're only going to
1103 # fetch the md4 file digest, not the block digests.
1105 my($err, $csum, $blkSize)
1106 = BackupPC::Xfer::RsyncDigest->digestStart(
1107 $attr->{fullPath}, $attr->{size},
1108 0, 2048, $fio->{checksumSeed}, 1,
1109 $attr->{compress}, 1);
1111 $fio->log("Can't open $attr->{fullPath} for MD4"
1112 . " check (err=$err, $name)");
1113 $fio->{stats}{errorCnt}++;
1115 if ( $fio->{logLevel} >= 5 ) {
1116 my($isCached, $invalid) = $csum->isCached;
1117 $fio->log("MD4 $attr->{fullPath} cache = $isCached,"
1118 . " invalid = $invalid");
1120 $newDigest = $csum->digestEnd;
1122 $fio->{rxSize} = $attr->{size};
1125 # Empty file; just create an empty file digest
1127 $fio->{rxDigest} = File::RsyncP::Digest->new();
1128 $fio->{rxDigest}->protocol($fio->{protocol_version});
1129 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
1130 $newDigest = $fio->{rxDigest}->digest;
1132 $fio->log("$name got exact match") if ( $fio->{logLevel} >= 5 );
1134 $newDigest = $fio->{rxDigest}->digest;
1136 if ( $fio->{logLevel} >= 3 ) {
1137 my $md4Str = unpack("H*", $md4);
1138 my $newStr = unpack("H*", $newDigest);
1139 $fio->log("$name got digests $md4Str vs $newStr")
1141 if ( $md4 ne $newDigest ) {
1143 $fio->log("$name: fatal error: md4 doesn't match on retry;"
1146 $fio->log("$name: md4 doesn't match: will retry in phase 1;"
1149 $fio->{stats}{errorCnt}++;
1150 if ( defined($fio->{rxOutFd}) ) {
1151 $fio->{rxOutFd}->close;
1152 unlink($fio->{rxOutFile});
1154 delete($fio->{rxFile});
1155 delete($fio->{rxOutFile});
1161 # One special case is an empty file: if the file size is
1162 # zero we need to open the output file to create it.
1164 if ( $fio->{rxSize} == 0 ) {
1165 my $rxOutFileRel = "$fio->{shareM}/"
1166 . $fio->{bpc}->fileNameMangle($name);
1167 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
1168 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
1169 $rxOutFile, $fio->{rxSize},
1170 $fio->{xfer}{compress});
1172 if ( !defined($fio->{rxOutFd}) ) {
1174 # No output file, meaning original was an exact match.
1176 $fio->log("$name: nothing to do")
1177 if ( $fio->{logLevel} >= 5 );
1178 my $attr = $fio->{rxLocalAttr};
1179 my $f = $fio->{rxFile};
1180 $fio->logFileAction("same", $f) if ( $fio->{logLevel} >= 1 );
1182 || $attr->{type} != $f->{type}
1183 || $attr->{mtime} != $f->{mtime}
1184 || $attr->{size} != $f->{size}
1185 || $attr->{uid} != $f->{uid}
1186 || $attr->{gid} != $f->{gid}
1187 || $attr->{mode} != $f->{mode}
1188 || $attr->{hlink_self} != $f->{hlink_self} ) {
1190 # In the full case, or if the attributes are different,
1191 # we need to make a link from the previous file and
1192 # set the attributes.
1194 my $rxOutFile = $fio->{outDirSh}
1195 . $fio->{bpc}->fileNameMangle($name);
1196 my($exists, $digest, $origSize, $outSize, $errs)
1197 = BackupPC::PoolWrite::LinkOrCopy(
1202 $fio->{xfer}{compress});
1204 # Cumulate the stats
1206 $fio->{stats}{TotalFileCnt}++;
1207 $fio->{stats}{TotalFileSize} += $fio->{rxSize};
1208 $fio->{stats}{ExistFileCnt}++;
1209 $fio->{stats}{ExistFileSize} += $fio->{rxSize};
1210 $fio->{stats}{ExistFileCompSize} += -s $rxOutFile;
1211 $fio->{rxFile}{size} = $fio->{rxSize};
1212 $ret = $fio->attribSet($fio->{rxFile});
1213 $fio->log(@$errs) if ( defined($errs) && @$errs );
1215 if ( !$exists && $outSize > 0 ) {
1217 # the hard link failed, most likely because the target
1218 # file has too many links. We have copied the file
1219 # instead, so add this to the new file list.
1221 my $rxOutFileRel = "$fio->{shareM}/"
1222 . $fio->{bpc}->fileNameMangle($name);
1223 $rxOutFileRel =~ s{^/+}{};
1224 my $fh = $fio->{newFilesFH};
1225 print($fh "$digest $origSize $rxOutFileRel\n")
1226 if ( defined($fh) );
1230 my $exist = $fio->processClose($fio->{rxOutFd},
1231 $fio->{rxOutFileRel},
1233 $fio->logFileAction($exist ? "pool" : "create", $fio->{rxFile})
1234 if ( $fio->{logLevel} >= 1 );
1235 $fio->{rxFile}{size} = $fio->{rxSize};
1236 $ret = $fio->attribSet($fio->{rxFile});
1238 delete($fio->{rxDigest});
1239 delete($fio->{rxInData});
1240 delete($fio->{rxFile});
1241 delete($fio->{rxOutFile});
1246 # Callback function for BackupPC::View->find. Note the order of the
1247 # first two arguments.
1251 my($a, $fio, $fList, $outputFunc) = @_;
1252 my $name = $a->{relPath};
1254 my $type = $a->{type};
1255 my $extraAttribs = {};
1257 if ( $a->{mode} & S_HLINK_TARGET ) {
1258 $a->{hlink_self} = 1;
1259 $a->{mode} &= ~S_HLINK_TARGET;
1261 $n =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
1262 $fio->log("Sending $name (remote=$n) type = $type") if ( $fio->{logLevel} >= 1 );
1263 if ( $type == BPC_FTYPE_CHARDEV
1264 || $type == BPC_FTYPE_BLOCKDEV
1265 || $type == BPC_FTYPE_SYMLINK ) {
1266 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1268 if ( defined($fh) ) {
1269 $rdSize = $fh->read(\$str, $a->{size} + 1024);
1270 if ( $type == BPC_FTYPE_SYMLINK ) {
1272 # Reconstruct symbolic link
1274 $extraAttribs = { link => $str };
1275 if ( $rdSize != $a->{size} ) {
1277 $fio->log("$name: can't read exactly $a->{size} bytes");
1278 $fio->{stats}{errorCnt}++;
1280 } elsif ( $str =~ /(\d*),(\d*)/ ) {
1282 # Reconstruct char or block special major/minor device num
1284 # Note: char/block devices have $a->{size} = 0, so we
1285 # can't do an error check on $rdSize.
1288 rdev => $1 * 256 + $2,
1293 $fio->log("$name: unexpected special file contents $str");
1294 $fio->{stats}{errorCnt}++;
1299 $fio->log("$name: can't open");
1300 $fio->{stats}{errorCnt}++;
1302 } elsif ( $fio->{preserve_hard_links}
1303 && ($type == BPC_FTYPE_HARDLINK || $type == BPC_FTYPE_FILE)
1304 && ($type == BPC_FTYPE_HARDLINK
1305 || $fio->{protocol_version} < 27
1306 || $a->{hlink_self}) ) {
1308 # Fill in fake inode information so that the remote rsync
1309 # can correctly create hardlinks.
1311 $name =~ s/^\.?\/+//;
1312 my($target, $inode);
1314 if ( $type == BPC_FTYPE_HARDLINK ) {
1315 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0,
1317 if ( defined($fh) ) {
1318 $fh->read(\$target, 65536);
1320 $target =~ s/^\.?\/+//;
1321 if ( defined($fio->{hlinkFile2Num}{$target}) ) {
1322 $inode = $fio->{hlinkFile2Num}{$target};
1324 $inode = $fio->{fileListCnt};
1325 $fio->{hlinkFile2Num}{$target} = $inode;
1328 $fio->log("$a->{fullPath}: can't open for hardlink");
1329 $fio->{stats}{errorCnt}++;
1331 } elsif ( $a->{hlink_self} ) {
1332 if ( defined($fio->{hlinkFile2Num}{$name}) ) {
1333 $inode = $fio->{hlinkFile2Num}{$name};
1335 $inode = $fio->{fileListCnt};
1336 $fio->{hlinkFile2Num}{$name} = $inode;
1339 $inode = $fio->{fileListCnt} if ( !defined($inode) );
1340 $fio->log("$name: setting inode to $inode");
1349 mode => $a->{mode} & ~S_HLINK_TARGET,
1352 mtime => $a->{mtime},
1356 my $logName = $f->{name};
1357 from_to($f->{name}, "utf8", $fio->{clientCharset})
1358 if ( $fio->{clientCharset} ne "" );
1361 $logName = "$fio->{xfer}{pathHdrDest}/$logName";
1362 $logName =~ s{//+}{/}g;
1363 $f->{name} = $logName;
1364 $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1366 &$outputFunc($fList->encodeData);
1370 $fio->{fileListCnt}++;
1371 if ( $type != BPC_FTYPE_DIR ) {
1372 $fio->{stats}{TotalFileCnt}++;
1373 $fio->{stats}{TotalFileSize} += $a->{size};
1379 my($fio, $flist, $outputFunc) = @_;
1382 # Populate the file list with the files requested by the user.
1383 # Since some might be directories so we call BackupPC::View::find.
1385 $fio->log("fileListSend: sending file list: "
1386 . join(" ", @{$fio->{fileList}})) if ( $fio->{logLevel} >= 4 );
1387 $fio->{fileListCnt} = 0;
1388 $fio->{hlinkFile2Num} = {};
1389 foreach my $name ( @{$fio->{fileList}} ) {
1390 $fio->{view}->find($fio->{xfer}{bkupSrcNum},
1391 $fio->{xfer}{bkupSrcShare},
1393 \&fileListEltSend, $fio, $flist, $outputFunc);
1399 my($fio, $isChild) = @_;
1402 # If we are aborting early, remove the last file since
1403 # it was not complete
1405 if ( $isChild && defined($fio->{rxFile}) ) {
1406 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1407 if ( defined($fio->{rxFile}) ) {
1408 unlink($fio->{rxOutFile});
1409 $fio->log("finish: removing in-process file $fio->{rxFile}{name}");
1414 # Flush the attributes if this is the child
1416 $fio->attribWrite(undef) if ( $isChild );
1422 # join('',@_), kill 0;