1 #============================================================= -*-perl-*-
8 # Craig Barratt <cbarratt@users.sourceforge.net>
11 # Copyright (C) 2002-2003 Craig Barratt
13 #========================================================================
15 # Version 3.0.0alpha, released 23 Jan 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);
325 my($dir, $fname, $share, $shareM);
328 $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
329 if ( defined($fio->{xfer}{pathHdrSrc}) );
330 $fname =~ s{//+}{/}g;
331 if ( $fname =~ m{(.*)/(.*)} ) {
332 $shareM = $fio->{shareM};
335 } elsif ( $fname ne "." ) {
336 $shareM = $fio->{shareM};
342 $fname = $fio->{share};
344 $fio->viewCacheDir($share, $dir);
345 $shareM .= "/$dir" if ( $dir ne "" );
346 if ( defined(my $attr = $fio->{viewCache}{$shareM}{$fname}) ) {
348 } elsif ( defined(my $attr = $fio->{partialCache}{$shareM}{$fname}) ) {
357 my($fio, $f, $doHardLink) = @_;
359 my($attr) = $fio->attribGetWhere($f);
360 if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
361 $fio->log("$attr->{fullPath}: opening for hardlink read"
362 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
363 my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
366 if ( defined($fh) ) {
367 $fh->read(\$target, 65536);
369 $target =~ s/^\.?\/+//;
371 $fio->log("$attr->{fullPath}: can't open for hardlink read");
372 $fio->{stats}{errorCnt}++;
373 $attr->{type} = BPC_FTYPE_FILE;
376 $target = "/$target" if ( $target !~ /^\// );
377 $fio->log("$attr->{fullPath}: redirecting to $target (will trim "
378 . "$fio->{xfer}{pathHdrSrc})") if ( $fio->{logLevel} >= 4 );
379 $target =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
380 $f->{name} = $target;
381 $attr = $fio->attribGet($f);
382 $fio->log(" ... now got $attr->{fullPath}")
383 if ( $fio->{logLevel} >= 4 );
391 my $mode = $f->{mode};
393 if ( ($mode & S_IFMT) == S_IFREG ) {
394 if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
395 return BPC_FTYPE_HARDLINK;
397 return BPC_FTYPE_FILE;
399 } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
400 return BPC_FTYPE_DIR;
401 } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
402 return BPC_FTYPE_SYMLINK;
403 } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
404 return BPC_FTYPE_CHARDEV;
405 } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
406 return BPC_FTYPE_BLOCKDEV;
407 } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
408 return BPC_FTYPE_FIFO;
409 } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
410 return BPC_FTYPE_SOCKET;
412 return BPC_FTYPE_UNKNOWN;
417 # Set the attributes for a file. Returns non-zero on error.
421 my($fio, $f, $placeHolder) = @_;
424 if ( $f->{name} =~ m{(.*)/(.*)} ) {
426 $dir = "$fio->{shareM}/" . $1;
427 } elsif ( $f->{name} eq "." ) {
429 $file = $fio->{share};
431 $dir = $fio->{shareM};
435 if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
437 # Flush any directories that don't match the first part
438 # of the new directory
440 foreach my $d ( keys(%{$fio->{attrib}}) ) {
441 next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
442 $fio->attribWrite($d);
444 $fio->{attribLastDir} = $dir;
446 if ( !exists($fio->{attrib}{$dir}) ) {
447 $fio->{attrib}{$dir} = BackupPC::Attrib->new({
448 compress => $fio->{xfer}{compress},
450 my $path = $fio->{outDir} . $dir;
451 if ( -f $fio->{attrib}{$dir}->fileName($path)
452 && !$fio->{attrib}{$dir}->read($path) ) {
453 $fio->log(sprintf("Unable to read attribute file %s",
454 $fio->{attrib}{$dir}->fileName($path)));
457 $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
459 my $mode = $f->{mode};
461 $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
462 $fio->{attrib}{$dir}->set($file, {
463 type => $fio->mode2type($f),
467 size => $placeHolder ? -1 : $f->{size},
468 mtime => $f->{mtime},
479 # Don't write attributes on 2nd phase - they're already
480 # taken care of during the first phase.
482 return if ( $fio->{phase} > 0 );
483 if ( !defined($d) ) {
485 # flush all entries (in reverse order)
487 foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
488 $fio->attribWrite($d);
492 return if ( !defined($fio->{attrib}{$d}) );
494 # Set deleted files in the attributes. Any file in the view
495 # that doesn't have attributes is flagged as deleted for
496 # incremental dumps. All files sent by rsync have attributes
497 # temporarily set so we can do deletion detection. We also
498 # prune these temporary attributes.
504 $dir = $1 if ( $d =~ m{.+?/(.*)} );
505 $fio->viewCacheDir(undef, $dir);
506 ##print("attribWrite $d,$dir\n");
507 ##$Data::Dumper::Indent = 1;
508 ##$fio->log("attribWrite $d,$dir");
509 ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
510 ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
511 ##print "viewCache = ", Dumper($fio->{attrib});
512 ##print "attrib = ", Dumper($fio->{attrib});
513 if ( defined($fio->{viewCache}{$d}) ) {
514 foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
516 $name = "$1/$name" if ( $d =~ m{.*?/(.*)} );
517 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
519 # delete temporary attributes (skipped files)
521 if ( $a->{size} < 0 ) {
522 $fio->{attrib}{$d}->set($f, undef);
523 $fio->logFileAction("skip", {
524 %{$fio->{viewCache}{$d}{$f}},
526 }) if ( $fio->{logLevel} >= 2
527 && $a->{type} == BPC_FTYPE_FILE );
529 } elsif ( !$fio->{full} ) {
530 ##print("Delete file $f\n");
531 $fio->logFileAction("delete", {
532 %{$fio->{viewCache}{$d}{$f}},
534 }) if ( $fio->{logLevel} >= 1 );
535 $fio->{attrib}{$d}->set($f, {
536 type => BPC_FTYPE_DELETED,
547 if ( $fio->{attrib}{$d}->fileCount ) {
548 my $data = $fio->{attrib}{$d}->writeData;
551 $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
552 if ( $dirM =~ m{(.*?)/(.*)} );
553 my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
554 $fio->log("attribWrite(dir=$d) -> $fileName")
555 if ( $fio->{logLevel} >= 4 );
556 my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
557 length($data), $fio->{xfer}{compress});
558 $poolWrite->write(\$data);
559 $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
562 delete($fio->{attrib}{$d});
567 my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
568 my($exists, $digest, $outSize, $errs) = $poolWrite->close;
570 $fileName =~ s{^/+}{};
571 $fio->log(@$errs) if ( defined($errs) && @$errs );
573 $fio->{stats}{TotalFileCnt}++;
574 $fio->{stats}{TotalFileSize} += $origSize;
578 $fio->{stats}{ExistFileCnt}++;
579 $fio->{stats}{ExistFileSize} += $origSize;
580 $fio->{stats}{ExistFileCompSize} += $outSize;
582 } elsif ( $outSize > 0 ) {
583 my $fh = $fio->{newFilesFH};
584 print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
586 return $exists && $origSize > 0;
593 return $fio->{stats};
597 # Make a given directory. Returns non-zero on error.
602 my $name = $1 if ( $f->{name} =~ /(.*)/ );
605 if ( $name eq "." ) {
606 $path = $fio->{outDirSh};
608 $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
610 $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
611 $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
612 $path = $1 if ( $path =~ /(.*)/ );
613 File::Path::mkpath($path, 0, 0777) if ( !-d $path );
614 return $fio->attribSet($f) if ( -d $path );
615 $fio->log("Can't create directory $path");
616 $fio->{stats}{errorCnt}++;
621 # Make a special file. Returns non-zero on error.
626 my $name = $1 if ( $f->{name} =~ /(.*)/ );
627 my $fNameM = $fio->{bpc}->fileNameMangle($name);
628 my $path = $fio->{outDirSh} . $fNameM;
629 my $attr = $fio->attribGet($f);
631 my $type = $fio->mode2type($f);
633 $fio->log("makeSpecial($path, $type, $f->{mode})")
634 if ( $fio->{logLevel} >= 5 );
635 if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
636 my($major, $minor, $fh, $fileData);
638 if ( defined($f->{rdev_major}) ) {
639 $major = $f->{rdev_major};
640 $minor = $f->{rdev_minor};
642 $major = $f->{rdev} >> 8;
643 $minor = $f->{rdev} & 0xff;
645 $str = "$major,$minor";
646 } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
648 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
652 if ( !defined($f->{hlink}) ) {
653 $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
654 . " on a regular non-hardlink file");
660 # Now see if the file is different, or this is a full, in which
661 # case we create the new file.
666 || $attr->{type} != $type
667 || $attr->{mtime} != $f->{mtime}
668 || $attr->{size} != $f->{size}
669 || $attr->{uid} != $f->{uid}
670 || $attr->{gid} != $f->{gid}
671 || $attr->{mode} != $f->{mode}
672 || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
674 || $fh->read(\$fileData, length($str) + 1) != length($str)
675 || $fileData ne $str ) {
676 $fh->close if ( defined($fh) );
677 $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
678 length($str), $fio->{xfer}{compress});
680 my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
682 $fio->logFileAction($exist ? "pool" : "create", $f)
683 if ( $fio->{logLevel} >= 1 );
684 return $fio->attribSet($f);
686 $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
688 $fh->close if ( defined($fh) );
692 # Make a hardlink. Returns non-zero on error.
693 # This actually gets called twice for each hardlink.
694 # Once as the file list is processed, and again at
695 # the end. BackupPC does them as it goes (since it is
696 # just saving the hardlink info and not actually making
701 my($fio, $f, $end) = @_;
704 return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
709 my($fio, $path) = @_;
711 $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)");
715 # Default log handler
721 print(STDERR $str, "\n");
725 # Handle one or more log messages
729 my($fio, @logStr) = @_;
731 foreach my $str ( @logStr ) {
732 next if ( $str eq "" );
733 $fio->{logHandler}($str);
738 # Generate a log file message for a completed file
742 my($fio, $action, $f) = @_;
743 my $owner = "$f->{uid}/$f->{gid}";
744 my $type = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
745 [($f->{mode} & S_IFMT) >> 12];
746 my $name = $f->{name};
748 if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
749 $name .= " -> $f->{link}";
750 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
751 && defined($f->{hlink}) && !$f->{hlink_self} ) {
752 $name .= " -> $f->{hlink}";
756 $fio->log(sprintf(" %-6s %1s%4o %9s %11.0f %s",
766 # If there is a partial and we are doing a full, we do an incremental
767 # against the partial and a full against the rest. This subroutine
768 # is how we tell File::RsyncP which files to ignore attributes on
769 # (ie: against the partial dump we do consider the attributes, but
770 # otherwise we ignore attributes).
776 return if ( !defined($fio->{partialNum}) );
777 my($attr, $isPartial) = $fio->attribGetWhere($f);
778 $fio->log("$f->{name}: just checking attributes from partial")
779 if ( $isPartial && $fio->{logLevel} >= 5 );
784 # This is called by File::RsyncP when a file is skipped because the
789 my($fio, $f, $attr) = @_;
792 # Unless this is a partial, this is normal so ignore it.
794 return if ( !defined($fio->{partialNum}) );
796 $fio->log("$f->{name}: skipped in partial; adding link")
797 if ( $fio->{logLevel} >= 5 );
798 $fio->{rxLocalAttr} = $attr;
800 $fio->{rxSize} = $attr->{size};
801 delete($fio->{rxInFd});
802 delete($fio->{rxOutFd});
803 delete($fio->{rxDigest});
804 delete($fio->{rxInData});
805 return $fio->fileDeltaRxDone();
809 # Start receive of file deltas for a particular file.
813 my($fio, $f, $cnt, $size, $remainder) = @_;
815 $fio->{rxFile} = $f; # remote file attributes
816 $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
817 $fio->{rxBlkCnt} = $cnt; # how many blocks we will receive
818 $fio->{rxBlkSize} = $size; # block size
819 $fio->{rxRemainder} = $remainder; # size of the last block
820 $fio->{rxMatchBlk} = 0; # current start of match
821 $fio->{rxMatchNext} = 0; # current next block of match
822 $fio->{rxSize} = 0; # size of received file
823 my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
824 if ( $fio->{rxFile}{size} != $rxSize ) {
825 $fio->{rxMatchBlk} = undef; # size different, so no file match
826 $fio->log("$fio->{rxFile}{name}: size doesn't match"
827 . " ($fio->{rxFile}{size} vs $rxSize)")
828 if ( $fio->{logLevel} >= 5 );
831 # If compression was off and now on, or on and now off, then
832 # don't do an exact match.
834 if ( defined($fio->{rxLocalAttr})
835 && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
836 $fio->{rxMatchBlk} = undef; # compression changed, so no file match
837 $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
838 . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
839 if ( $fio->{logLevel} >= 4 );
841 delete($fio->{rxInFd});
842 delete($fio->{rxOutFd});
843 delete($fio->{rxDigest});
844 delete($fio->{rxInData});
848 # Process the next file delta for the current file. Returns 0 if ok,
849 # -1 if not. Must be called with either a block number, $blk, or new data,
850 # $newData, (not both) defined.
854 my($fio, $blk, $newData) = @_;
856 if ( defined($blk) ) {
857 if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
859 # got the next block in order; just keep track.
861 $fio->{rxMatchNext}++;
865 my $newDataLen = length($newData);
866 $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
867 if ( $fio->{logLevel} >= 8 );
868 if ( !defined($fio->{rxOutFd}) ) {
870 # maybe the file has no changes
872 if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
873 && !defined($blk) && !defined($newData) ) {
874 #$fio->log("$fio->{rxFile}{name}: file is unchanged");
875 # if ( $fio->{logLevel} >= 8 );
880 # need to open an output file where we will build the
883 $fio->{rxFile}{name} =~ /(.*)/;
884 my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
885 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
886 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
887 $rxOutFile, $fio->{rxFile}{size},
888 $fio->{xfer}{compress});
889 $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
890 if ( $fio->{logLevel} >= 9 );
891 $fio->{rxOutFile} = $rxOutFile;
892 $fio->{rxOutFileRel} = $rxOutFileRel;
893 $fio->{rxDigest} = File::RsyncP::Digest->new();
894 $fio->{rxDigest}->protocol($fio->{protocol_version});
895 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
897 if ( defined($fio->{rxMatchBlk})
898 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
900 # Need to copy the sequence of blocks that matched. If the file
901 # is compressed we need to make a copy of the uncompressed file,
902 # since the compressed file is not seekable. Future optimizations
903 # could include only creating an uncompressed copy if the matching
904 # blocks were not monotonic, and to only do this if there are
905 # matching blocks (eg, maybe the entire file is new).
907 my $attr = $fio->{rxLocalAttr};
909 if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
910 if ( $attr->{compress} ) {
911 if ( !defined($fh = BackupPC::FileZIO->open(
914 $attr->{compress})) ) {
915 $fio->log("Can't open $attr->{fullPath}");
916 $fio->{stats}{errorCnt}++;
919 if ( $attr->{size} < 16 * 1024 * 1024 ) {
921 # Cache the entire old file if it is less than 16MB
924 $fio->{rxInData} = "";
925 while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
926 $fio->{rxInData} .= $data;
928 $fio->log("$attr->{fullPath}: cached all $attr->{size}"
930 if ( $fio->{logLevel} >= 9 );
933 # Create and write a temporary output file
935 unlink("$fio->{outDirSh}RStmp")
936 if ( -f "$fio->{outDirSh}RStmp" );
937 if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
941 while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
942 if ( syswrite(F, $data) != length($data) ) {
943 $fio->log(sprintf("Can't write len=%d to %s",
944 length($data) , "$fio->{outDirSh}RStmp"));
946 $fio->{stats}{errorCnt}++;
949 $byteCnt += length($data);
952 $fio->{rxInName} = "$fio->{outDirSh}RStmp";
953 sysseek($fio->{rxInFd}, 0, 0);
954 $fio->log("$attr->{fullPath}: copied $byteCnt,"
955 . "$attr->{size} bytes to $fio->{rxInName}")
956 if ( $fio->{logLevel} >= 9 );
958 $fio->log("Unable to open $fio->{outDirSh}RStmp");
960 $fio->{stats}{errorCnt}++;
966 if ( open(F, "<", $attr->{fullPath}) ) {
969 $fio->{rxInName} = $attr->{fullPath};
971 $fio->log("Unable to open $attr->{fullPath}");
972 $fio->{stats}{errorCnt}++;
977 my $lastBlk = $fio->{rxMatchNext} - 1;
978 $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
980 if ( $fio->{logLevel} >= 9 );
981 my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
982 if ( defined($fio->{rxInFd})
983 && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
984 $fio->log("Unable to seek $attr->{rxInName} to $seekPosn");
985 $fio->{stats}{errorCnt}++;
988 my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
989 my($thisCnt, $len, $data);
990 for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
991 $thisCnt = $cnt - $i;
992 $thisCnt = 512 if ( $thisCnt > 512 );
993 if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
994 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
996 $len = $thisCnt * $fio->{rxBlkSize};
998 if ( defined($fio->{rxInData}) ) {
999 $data = substr($fio->{rxInData}, $seekPosn, $len);
1002 my $got = sysread($fio->{rxInFd}, $data, $len);
1003 if ( $got != $len ) {
1004 my $inFileSize = -s $fio->{rxInName};
1005 $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1006 . " got=$got, seekPosn=$seekPosn"
1007 . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1008 . ",$attr->{size})");
1009 $fio->{stats}{errorCnt}++;
1014 $fio->{rxOutFd}->write(\$data);
1015 $fio->{rxDigest}->add($data);
1016 $fio->{rxSize} += length($data);
1018 $fio->{rxMatchBlk} = undef;
1020 if ( defined($blk) ) {
1022 # Remember the new block number
1024 $fio->{rxMatchBlk} = $blk;
1025 $fio->{rxMatchNext} = $blk + 1;
1027 if ( defined($newData) ) {
1029 # Write the new chunk
1031 my $len = length($newData);
1032 $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1033 if ( $fio->{logLevel} >= 9 );
1034 $fio->{rxOutFd}->write(\$newData);
1035 $fio->{rxDigest}->add($newData);
1036 $fio->{rxSize} += length($newData);
1041 # Finish up the current receive file. Returns undef if ok, -1 if not.
1042 # Returns 1 if the md4 digest doesn't match.
1046 my($fio, $md4, $phase) = @_;
1047 my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/ );
1050 close($fio->{rxInFd}) if ( defined($fio->{rxInFd}) );
1051 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1052 $fio->{phase} = $phase;
1055 # Check the final md4 digest
1057 if ( defined($md4) ) {
1059 if ( !defined($fio->{rxDigest}) ) {
1061 # File was exact match, but we still need to verify the
1062 # MD4 checksum. Compute the md4 digest (or fetch the
1065 if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1067 # block size doesn't matter: we're only going to
1068 # fetch the md4 file digest, not the block digests.
1070 my($err, $csum, $blkSize)
1071 = BackupPC::Xfer::RsyncDigest->digestStart(
1072 $attr->{fullPath}, $attr->{size},
1073 0, 2048, $fio->{checksumSeed}, 1,
1074 $attr->{compress}, 1);
1076 $fio->log("Can't open $attr->{fullPath} for MD4"
1077 . " check (err=$err, $name)");
1078 $fio->{stats}{errorCnt}++;
1080 if ( $fio->{logLevel} >= 5 ) {
1081 my($isCached, $invalid) = $csum->isCached;
1082 $fio->log("MD4 $attr->{fullPath} cache = $isCached,"
1083 . " invalid = $invalid");
1085 $newDigest = $csum->digestEnd;
1087 $fio->{rxSize} = $attr->{size};
1090 # Empty file; just create an empty file digest
1092 $fio->{rxDigest} = File::RsyncP::Digest->new();
1093 $fio->{rxDigest}->protocol($fio->{protocol_version});
1094 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
1095 $newDigest = $fio->{rxDigest}->digest;
1097 $fio->log("$name got exact match") if ( $fio->{logLevel} >= 5 );
1099 $newDigest = $fio->{rxDigest}->digest;
1101 if ( $fio->{logLevel} >= 3 ) {
1102 my $md4Str = unpack("H*", $md4);
1103 my $newStr = unpack("H*", $newDigest);
1104 $fio->log("$name got digests $md4Str vs $newStr")
1106 if ( $md4 ne $newDigest ) {
1108 $fio->log("$name: fatal error: md4 doesn't match on retry;"
1111 $fio->log("$name: md4 doesn't match: will retry in phase 1;"
1114 $fio->{stats}{errorCnt}++;
1115 if ( defined($fio->{rxOutFd}) ) {
1116 $fio->{rxOutFd}->close;
1117 unlink($fio->{rxOutFile});
1119 delete($fio->{rxFile});
1120 delete($fio->{rxOutFile});
1126 # One special case is an empty file: if the file size is
1127 # zero we need to open the output file to create it.
1129 if ( $fio->{rxSize} == 0 ) {
1130 my $rxOutFileRel = "$fio->{shareM}/"
1131 . $fio->{bpc}->fileNameMangle($name);
1132 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
1133 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
1134 $rxOutFile, $fio->{rxSize},
1135 $fio->{xfer}{compress});
1137 if ( !defined($fio->{rxOutFd}) ) {
1139 # No output file, meaning original was an exact match.
1141 $fio->log("$name: nothing to do")
1142 if ( $fio->{logLevel} >= 5 );
1143 my $attr = $fio->{rxLocalAttr};
1144 my $f = $fio->{rxFile};
1145 $fio->logFileAction("same", $f) if ( $fio->{logLevel} >= 1 );
1147 || $attr->{type} != $f->{type}
1148 || $attr->{mtime} != $f->{mtime}
1149 || $attr->{size} != $f->{size}
1150 || $attr->{gid} != $f->{gid}
1151 || $attr->{mode} != $f->{mode} ) {
1153 # In the full case, or if the attributes are different,
1154 # we need to make a link from the previous file and
1155 # set the attributes.
1157 my $rxOutFile = $fio->{outDirSh}
1158 . $fio->{bpc}->fileNameMangle($name);
1159 my($exists, $digest, $origSize, $outSize, $errs)
1160 = BackupPC::PoolWrite::LinkOrCopy(
1165 $fio->{xfer}{compress});
1167 # Cumulate the stats
1169 $fio->{stats}{TotalFileCnt}++;
1170 $fio->{stats}{TotalFileSize} += $fio->{rxSize};
1171 $fio->{stats}{ExistFileCnt}++;
1172 $fio->{stats}{ExistFileSize} += $fio->{rxSize};
1173 $fio->{stats}{ExistFileCompSize} += -s $rxOutFile;
1174 $fio->{rxFile}{size} = $fio->{rxSize};
1175 $ret = $fio->attribSet($fio->{rxFile});
1176 $fio->log(@$errs) if ( defined($errs) && @$errs );
1178 if ( !$exists && $outSize > 0 ) {
1180 # the hard link failed, most likely because the target
1181 # file has too many links. We have copied the file
1182 # instead, so add this to the new file list.
1184 my $rxOutFileRel = "$fio->{shareM}/"
1185 . $fio->{bpc}->fileNameMangle($name);
1186 $rxOutFileRel =~ s{^/+}{};
1187 my $fh = $fio->{newFilesFH};
1188 print($fh "$digest $origSize $rxOutFileRel\n")
1189 if ( defined($fh) );
1193 my $exist = $fio->processClose($fio->{rxOutFd},
1194 $fio->{rxOutFileRel},
1196 $fio->logFileAction($exist ? "pool" : "create", $fio->{rxFile})
1197 if ( $fio->{logLevel} >= 1 );
1198 $fio->{rxFile}{size} = $fio->{rxSize};
1199 $ret = $fio->attribSet($fio->{rxFile});
1201 delete($fio->{rxDigest});
1202 delete($fio->{rxInData});
1203 delete($fio->{rxFile});
1204 delete($fio->{rxOutFile});
1209 # Callback function for BackupPC::View->find. Note the order of the
1210 # first two arguments.
1214 my($a, $fio, $fList, $outputFunc) = @_;
1215 my $name = $a->{relPath};
1217 my $type = $a->{type};
1218 my $extraAttribs = {};
1220 $n =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
1221 $fio->log("Sending $name (remote=$n) type = $type") if ( $fio->{logLevel} >= 1 );
1222 if ( $type == BPC_FTYPE_CHARDEV
1223 || $type == BPC_FTYPE_BLOCKDEV
1224 || $type == BPC_FTYPE_SYMLINK ) {
1225 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1227 if ( defined($fh) ) {
1228 $rdSize = $fh->read(\$str, $a->{size} + 1024);
1229 if ( $type == BPC_FTYPE_SYMLINK ) {
1231 # Reconstruct symbolic link
1233 $extraAttribs = { link => $str };
1234 if ( $rdSize != $a->{size} ) {
1236 $fio->log("$name: can't read exactly $a->{size} bytes");
1237 $fio->{stats}{errorCnt}++;
1239 } elsif ( $str =~ /(\d*),(\d*)/ ) {
1241 # Reconstruct char or block special major/minor device num
1243 # Note: char/block devices have $a->{size} = 0, so we
1244 # can't do an error check on $rdSize.
1247 rdev => $1 * 256 + $2,
1252 $fio->log("$name: unexpected special file contents $str");
1253 $fio->{stats}{errorCnt}++;
1258 $fio->log("$name: can't open");
1259 $fio->{stats}{errorCnt}++;
1261 } elsif ( $fio->{preserve_hard_links}
1262 && ($type == BPC_FTYPE_HARDLINK || $type == BPC_FTYPE_FILE)
1263 && ($type == BPC_FTYPE_HARDLINK
1264 || $fio->{protocol_version} < 27
1265 || ($a->{mode} & S_HLINK_TARGET) ) ) {
1267 # Fill in fake inode information so that the remote rsync
1268 # can correctly create hardlinks.
1270 $name =~ s/^\.?\/+//;
1271 my($target, $inode);
1273 if ( $type == BPC_FTYPE_HARDLINK ) {
1274 my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0,
1276 if ( defined($fh) ) {
1277 $fh->read(\$target, 65536);
1279 $target =~ s/^\.?\/+//;
1280 if ( defined($fio->{hlinkFile2Num}{$target}) ) {
1281 $inode = $fio->{hlinkFile2Num}{$target};
1283 $inode = $fio->{fileListCnt};
1284 $fio->{hlinkFile2Num}{$target} = $inode;
1287 $fio->log("$a->{fullPath}: can't open for hardlink");
1288 $fio->{stats}{errorCnt}++;
1290 } elsif ( $a->{mode} & S_HLINK_TARGET ) {
1291 if ( defined($fio->{hlinkFile2Num}{$name}) ) {
1292 $inode = $fio->{hlinkFile2Num}{$name};
1294 $inode = $fio->{fileListCnt};
1295 $fio->{hlinkFile2Num}{$name} = $inode;
1298 $inode = $fio->{fileListCnt} if ( !defined($inode) );
1299 $fio->log("$name: setting inode to $inode");
1308 mode => $a->{mode} & ~S_HLINK_TARGET,
1311 mtime => $a->{mtime},
1315 my $logName = $f->{name};
1316 from_to($f->{name}, "utf8", $fio->{clientCharset})
1317 if ( $fio->{clientCharset} ne "" );
1320 $logName = "$fio->{xfer}{pathHdrDest}/$f->{name}";
1321 $logName =~ s{//+}{/}g;
1322 $f->{name} = $logName;
1323 $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1325 &$outputFunc($fList->encodeData);
1329 $fio->{fileListCnt}++;
1330 if ( $type != BPC_FTYPE_DIR ) {
1331 $fio->{stats}{TotalFileCnt}++;
1332 $fio->{stats}{TotalFileSize} += $a->{size};
1338 my($fio, $flist, $outputFunc) = @_;
1341 # Populate the file list with the files requested by the user.
1342 # Since some might be directories so we call BackupPC::View::find.
1344 $fio->log("fileListSend: sending file list: "
1345 . join(" ", @{$fio->{fileList}})) if ( $fio->{logLevel} >= 4 );
1346 $fio->{fileListCnt} = 0;
1347 $fio->{hlinkFile2Num} = {};
1348 foreach my $name ( @{$fio->{fileList}} ) {
1349 $fio->{view}->find($fio->{xfer}{bkupSrcNum},
1350 $fio->{xfer}{bkupSrcShare},
1352 \&fileListEltSend, $fio, $flist, $outputFunc);
1358 my($fio, $isChild) = @_;
1361 # If we are aborting early, remove the last file since
1362 # it was not complete
1364 if ( $isChild && defined($fio->{rxFile}) ) {
1365 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1366 if ( defined($fio->{rxFile}) ) {
1367 unlink($fio->{rxOutFile});
1368 $fio->log("finish: removing in-process file $fio->{rxFile}{name}");
1373 # Flush the attributes if this is the child
1375 $fio->attribWrite(undef) if ( $isChild );
1381 # join('',@_), kill 0;