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 $fio->{protocol_version});
165 my($isCached, $isInvalid) = $d->isCached;
166 if ( $fio->{logLevel} >= 5 ) {
167 $fio->log("$attr->{fullPath} verify; cached = $isCached,"
168 . " invalid = $isInvalid, phase = $phase");
170 if ( $isCached || $isInvalid ) {
171 my $ret = BackupPC::Xfer::RsyncDigest->digestAdd(
172 $attr->{fullPath}, $blkSize,
173 $fio->{checksumSeed}, 1, # verify
174 $fio->{protocol_version}
177 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
179 $fio->{stats}{errorCnt}++;
181 $fio->log("$f->{name}: verified cached digest")
182 if ( $fio->{logLevel} >= 2 );
187 (my $err, $fio->{csum}, my $blkSize)
188 = BackupPC::Xfer::RsyncDigest->digestStart($attr->{fullPath},
189 $attr->{size}, 0, $defBlkSize, $fio->{checksumSeed},
190 $needMD4, $attr->{compress}, 1, $fio->{protocol_version});
192 $fio->log("Can't get rsync digests from $attr->{fullPath}"
193 . " (err=$err, name=$f->{name})");
194 $fio->{stats}{errorCnt}++;
197 if ( $fio->{logLevel} >= 5 ) {
198 my($isCached, $invalid) = $fio->{csum}->isCached;
199 $fio->log("$attr->{fullPath} cache = $isCached,"
200 . " invalid = $invalid, phase = $phase");
207 my($fio, $num, $csumLen, $blockSize) = @_;
212 return if ( !defined($fio->{csum}) );
213 return $fio->{csum}->digestGet($num, $csumLen);
220 return if ( !defined($fio->{csum}) );
221 return $fio->{csum}->digestEnd();
228 my $attr = $fio->attribGet($f, 1);
230 $fio->readEnd if ( defined($fio->{fh}) );
231 if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
233 $attr->{compress})) ) {
234 $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
235 $fio->{stats}{errorCnt}++;
238 $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
247 return if ( !defined($fio->{fh}) );
248 if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
249 return $fio->readEnd;
251 $fio->log(sprintf("read returns %d bytes", length($fileData)))
252 if ( $fio->{logLevel} >= 8 );
260 return if ( !defined($fio->{fh}) );
262 $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
269 my($fio, $checksumSeed) = @_;
271 $fio->{checksumSeed} = $checksumSeed;
272 $fio->log("Checksum caching enabled (checksumSeed = $checksumSeed)")
273 if ( $fio->{logLevel} >= 1 && $checksumSeed == RSYNC_CSUMSEED_CACHE );
274 $fio->log("Checksum seed is $checksumSeed")
275 if ( $fio->{logLevel} >= 2 && $checksumSeed != RSYNC_CSUMSEED_CACHE );
280 my($fio, $localDir, $remoteDir) = @_;
282 $fio->{localDir} = $localDir;
283 $fio->{remoteDir} = $remoteDir;
288 my($fio, $share, $dir) = @_;
291 #$fio->log("viewCacheDir($share, $dir)");
292 if ( !defined($share) ) {
293 $share = $fio->{share};
294 $shareM = $fio->{shareM};
296 $shareM = $fio->{bpc}->fileNameEltMangle($share);
298 $shareM = "$shareM/$dir" if ( $dir ne "" );
299 return if ( defined($fio->{viewCache}{$shareM}) );
301 # purge old cache entries (ie: those that don't match the
302 # first part of $dir).
304 foreach my $d ( keys(%{$fio->{viewCache}}) ) {
305 delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
308 # fetch new directory attributes
310 $fio->{viewCache}{$shareM}
311 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
313 # also cache partial backup attrib data too
315 if ( defined($fio->{partialNum}) ) {
316 foreach my $d ( keys(%{$fio->{partialCache}}) ) {
317 delete($fio->{partialCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
319 $fio->{partialCache}{$shareM}
320 = $fio->{view}->dirAttrib($fio->{partialNum}, $share, $dir);
326 my($fio, $f, $noCache, $fname) = @_;
327 my($dir, $share, $shareM, $partial, $attr);
329 if ( !defined($fname) ) {
331 $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
332 if ( defined($fio->{xfer}{pathHdrSrc}) );
334 $fname =~ s{//+}{/}g;
335 if ( $fname =~ m{(.*)/(.*)}s ) {
336 $shareM = $fio->{shareM};
339 } elsif ( $fname ne "." ) {
340 $shareM = $fio->{shareM};
346 $fname = $fio->{share};
348 $shareM .= "/$dir" if ( $dir ne "" );
351 $share = $fio->{share} if ( !defined($share) );
352 my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
353 $attr = $dirAttr->{$fname};
355 $fio->viewCacheDir($share, $dir);
356 if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
358 } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
363 if ( $attr->{mode} & S_HLINK_TARGET ) {
364 $attr->{hlink_self} = 1;
365 $attr->{mode} &= ~S_HLINK_TARGET;
368 return ($attr, $partial);
373 my($fio, $f, $doHardLink) = @_;
375 my($attr) = $fio->attribGetWhere($f);
376 if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
377 $fio->log("$attr->{fullPath}: opening for hardlink read"
378 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
379 my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
382 if ( defined($fh) ) {
383 $fh->read(\$target, 65536);
385 $target =~ s/^\.?\/+//;
387 $fio->log("$attr->{fullPath}: can't open for hardlink read");
388 $fio->{stats}{errorCnt}++;
389 $attr->{type} = BPC_FTYPE_FILE;
392 $target = "/$target" if ( $target !~ /^\// );
393 $fio->log("$attr->{fullPath}: redirecting to $target")
394 if ( $fio->{logLevel} >= 4 );
396 ($attr) = $fio->attribGetWhere($f, 1, $target);
397 $fio->log(" ... now got $attr->{fullPath}")
398 if ( $fio->{logLevel} >= 4 );
406 my $mode = $f->{mode};
408 if ( ($mode & S_IFMT) == S_IFREG ) {
409 if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
410 return BPC_FTYPE_HARDLINK;
412 return BPC_FTYPE_FILE;
414 } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
415 return BPC_FTYPE_DIR;
416 } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
417 return BPC_FTYPE_SYMLINK;
418 } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
419 return BPC_FTYPE_CHARDEV;
420 } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
421 return BPC_FTYPE_BLOCKDEV;
422 } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
423 return BPC_FTYPE_FIFO;
424 } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
425 return BPC_FTYPE_SOCKET;
427 return BPC_FTYPE_UNKNOWN;
432 # Set the attributes for a file. Returns non-zero on error.
436 my($fio, $f, $placeHolder) = @_;
439 if ( $f->{name} =~ m{(.*)/(.*)}s ) {
441 $dir = "$fio->{shareM}/" . $1;
442 } elsif ( $f->{name} eq "." ) {
444 $file = $fio->{share};
446 $dir = $fio->{shareM};
450 if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
452 # Flush any directories that don't match the first part
453 # of the new directory
455 foreach my $d ( keys(%{$fio->{attrib}}) ) {
456 next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
457 $fio->attribWrite($d);
459 $fio->{attribLastDir} = $dir;
461 if ( !exists($fio->{attrib}{$dir}) ) {
462 $fio->{attrib}{$dir} = BackupPC::Attrib->new({
463 compress => $fio->{xfer}{compress},
465 my $path = $fio->{outDir} . $dir;
466 if ( -f $fio->{attrib}{$dir}->fileName($path)
467 && !$fio->{attrib}{$dir}->read($path) ) {
468 $fio->log(sprintf("Unable to read attribute file %s",
469 $fio->{attrib}{$dir}->fileName($path)));
472 $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
474 my $mode = $f->{mode};
476 $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
477 $fio->{attrib}{$dir}->set($file, {
478 type => $fio->mode2type($f),
482 size => $placeHolder ? -1 : $f->{size},
483 mtime => $f->{mtime},
494 # Don't write attributes on 2nd phase - they're already
495 # taken care of during the first phase.
497 return if ( $fio->{phase} > 0 );
498 if ( !defined($d) ) {
500 # flush all entries (in reverse order)
502 foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
503 $fio->attribWrite($d);
507 return if ( !defined($fio->{attrib}{$d}) );
509 # Set deleted files in the attributes. Any file in the view
510 # that doesn't have attributes is flagged as deleted for
511 # incremental dumps. All files sent by rsync have attributes
512 # temporarily set so we can do deletion detection. We also
513 # prune these temporary attributes.
519 $dir = $1 if ( $d =~ m{.+?/(.*)}s );
520 $fio->viewCacheDir(undef, $dir);
521 ##print("attribWrite $d,$dir\n");
522 ##$Data::Dumper::Indent = 1;
523 ##$fio->log("attribWrite $d,$dir");
524 ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
525 ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
526 ##print "viewCache = ", Dumper($fio->{attrib});
527 ##print "attrib = ", Dumper($fio->{attrib});
528 if ( defined($fio->{viewCache}{$d}) ) {
529 foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
531 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
532 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
534 # delete temporary attributes (skipped files)
536 if ( $a->{size} < 0 ) {
537 $fio->{attrib}{$d}->set($f, undef);
538 $fio->logFileAction("skip", {
539 %{$fio->{viewCache}{$d}{$f}},
541 }) if ( $fio->{logLevel} >= 2
542 && $a->{type} == BPC_FTYPE_FILE );
544 } elsif ( !$fio->{full} ) {
545 ##print("Delete file $f\n");
546 $fio->logFileAction("delete", {
547 %{$fio->{viewCache}{$d}{$f}},
549 }) if ( $fio->{logLevel} >= 1 );
550 $fio->{attrib}{$d}->set($f, {
551 type => BPC_FTYPE_DELETED,
562 if ( $fio->{attrib}{$d}->fileCount ) {
563 my $data = $fio->{attrib}{$d}->writeData;
566 $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
567 if ( $dirM =~ m{(.*?)/(.*)}s );
568 my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
569 $fio->log("attribWrite(dir=$d) -> $fileName")
570 if ( $fio->{logLevel} >= 4 );
571 my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
572 length($data), $fio->{xfer}{compress});
573 $poolWrite->write(\$data);
574 $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
577 delete($fio->{attrib}{$d});
582 my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
583 my($exists, $digest, $outSize, $errs) = $poolWrite->close;
585 $fileName =~ s{^/+}{};
586 $fio->log(@$errs) if ( defined($errs) && @$errs );
588 $fio->{stats}{TotalFileCnt}++;
589 $fio->{stats}{TotalFileSize} += $origSize;
593 $fio->{stats}{ExistFileCnt}++;
594 $fio->{stats}{ExistFileSize} += $origSize;
595 $fio->{stats}{ExistFileCompSize} += $outSize;
597 } elsif ( $outSize > 0 ) {
598 my $fh = $fio->{newFilesFH};
599 print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
601 return $exists && $origSize > 0;
608 return $fio->{stats};
612 # Make a given directory. Returns non-zero on error.
617 my $name = $1 if ( $f->{name} =~ /(.*)/s );
620 if ( $name eq "." ) {
621 $path = $fio->{outDirSh};
623 $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
625 $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
626 $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
627 $path = $1 if ( $path =~ /(.*)/s );
628 File::Path::mkpath($path, 0, 0777) if ( !-d $path );
629 return $fio->attribSet($f) if ( -d $path );
630 $fio->log("Can't create directory $path");
631 $fio->{stats}{errorCnt}++;
636 # Make a special file. Returns non-zero on error.
641 my $name = $1 if ( $f->{name} =~ /(.*)/s );
642 my $fNameM = $fio->{bpc}->fileNameMangle($name);
643 my $path = $fio->{outDirSh} . $fNameM;
644 my $attr = $fio->attribGet($f);
646 my $type = $fio->mode2type($f);
648 $fio->log("makeSpecial($path, $type, $f->{mode})")
649 if ( $fio->{logLevel} >= 5 );
650 if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
651 my($major, $minor, $fh, $fileData);
653 if ( defined($f->{rdev_major}) ) {
654 $major = $f->{rdev_major};
655 $minor = $f->{rdev_minor};
657 $major = $f->{rdev} >> 8;
658 $minor = $f->{rdev} & 0xff;
660 $str = "$major,$minor";
661 } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
663 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
667 if ( !defined($f->{hlink}) ) {
668 $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
669 . " on a regular non-hardlink file");
675 # Now see if the file is different, or this is a full, in which
676 # case we create the new file.
681 || $attr->{type} != $type
682 || $attr->{mtime} != $f->{mtime}
683 || $attr->{size} != $f->{size}
684 || $attr->{uid} != $f->{uid}
685 || $attr->{gid} != $f->{gid}
686 || $attr->{mode} != $f->{mode}
687 || $attr->{hlink_self} != $f->{hlink_self}
688 || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
690 || $fh->read(\$fileData, length($str) + 1) != length($str)
691 || $fileData ne $str ) {
692 $fh->close if ( defined($fh) );
693 $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
694 length($str), $fio->{xfer}{compress});
696 my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
698 $fio->logFileAction($exist ? "pool" : "create", $f)
699 if ( $fio->{logLevel} >= 1 );
700 return $fio->attribSet($f);
702 $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
704 $fh->close if ( defined($fh) );
708 # Make a hardlink. Returns non-zero on error.
709 # This actually gets called twice for each hardlink.
710 # Once as the file list is processed, and again at
711 # the end. BackupPC does them as it goes (since it is
712 # just saving the hardlink info and not actually making
717 my($fio, $f, $end) = @_;
720 return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
725 my($fio, $path) = @_;
727 $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)");
731 # Default log handler
737 print(STDERR $str, "\n");
741 # Handle one or more log messages
745 my($fio, @logStr) = @_;
747 foreach my $str ( @logStr ) {
748 next if ( $str eq "" );
749 $fio->{logHandler}($str);
754 # Generate a log file message for a completed file
758 my($fio, $action, $f) = @_;
759 my $owner = "$f->{uid}/$f->{gid}";
760 my $type = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
761 [($f->{mode} & S_IFMT) >> 12];
762 my $name = $f->{name};
764 if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
765 $name .= " -> $f->{link}";
766 } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
767 && defined($f->{hlink}) && !$f->{hlink_self} ) {
768 $name .= " -> $f->{hlink}";
772 $fio->log(sprintf(" %-6s %1s%4o %9s %11.0f %s",
782 # If there is a partial and we are doing a full, we do an incremental
783 # against the partial and a full against the rest. This subroutine
784 # is how we tell File::RsyncP which files to ignore attributes on
785 # (ie: against the partial dump we do consider the attributes, but
786 # otherwise we ignore attributes).
792 return if ( !defined($fio->{partialNum}) );
793 my($attr, $isPartial) = $fio->attribGetWhere($f);
794 $fio->log("$f->{name}: just checking attributes from partial")
795 if ( $isPartial && $fio->{logLevel} >= 5 );
800 # This is called by File::RsyncP when a file is skipped because the
805 my($fio, $f, $attr) = @_;
808 # Unless this is a partial, this is normal so ignore it.
810 return if ( !defined($fio->{partialNum}) );
812 $fio->log("$f->{name}: skipped in partial; adding link")
813 if ( $fio->{logLevel} >= 5 );
814 $fio->{rxLocalAttr} = $attr;
816 $fio->{rxSize} = $attr->{size};
817 delete($fio->{rxInFd});
818 delete($fio->{rxOutFd});
819 delete($fio->{rxDigest});
820 delete($fio->{rxInData});
821 return $fio->fileDeltaRxDone();
825 # Start receive of file deltas for a particular file.
829 my($fio, $f, $cnt, $size, $remainder) = @_;
831 $fio->{rxFile} = $f; # remote file attributes
832 $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
833 $fio->{rxBlkCnt} = $cnt; # how many blocks we will receive
834 $fio->{rxBlkSize} = $size; # block size
835 $fio->{rxRemainder} = $remainder; # size of the last block
836 $fio->{rxMatchBlk} = 0; # current start of match
837 $fio->{rxMatchNext} = 0; # current next block of match
838 $fio->{rxSize} = 0; # size of received file
839 my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
840 if ( $fio->{rxFile}{size} != $rxSize ) {
841 $fio->{rxMatchBlk} = undef; # size different, so no file match
842 $fio->log("$fio->{rxFile}{name}: size doesn't match"
843 . " ($fio->{rxFile}{size} vs $rxSize)")
844 if ( $fio->{logLevel} >= 5 );
847 # If compression was off and now on, or on and now off, then
848 # don't do an exact match.
850 if ( defined($fio->{rxLocalAttr})
851 && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
852 $fio->{rxMatchBlk} = undef; # compression changed, so no file match
853 $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
854 . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
855 if ( $fio->{logLevel} >= 4 );
858 # If the local file is a hardlink then no match
860 if ( defined($fio->{rxLocalAttr})
861 && $fio->{rxLocalAttr}{type} == BPC_FTYPE_HARDLINK ) {
862 $fio->{rxMatchBlk} = undef;
863 $fio->log("$fio->{rxFile}{name}: no match on hardlinks")
864 if ( $fio->{logLevel} >= 4 );
866 # need to copy since hardlink attribGet overwrites the name
868 $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
870 delete($fio->{rxHLinkAttr});
872 delete($fio->{rxInFd});
873 delete($fio->{rxOutFd});
874 delete($fio->{rxDigest});
875 delete($fio->{rxInData});
879 # Process the next file delta for the current file. Returns 0 if ok,
880 # -1 if not. Must be called with either a block number, $blk, or new data,
881 # $newData, (not both) defined.
885 my($fio, $blk, $newData) = @_;
887 if ( defined($blk) ) {
888 if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
890 # got the next block in order; just keep track.
892 $fio->{rxMatchNext}++;
896 my $newDataLen = length($newData);
897 $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
898 if ( $fio->{logLevel} >= 8 );
899 if ( !defined($fio->{rxOutFd}) ) {
901 # maybe the file has no changes
903 if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
904 && !defined($blk) && !defined($newData) ) {
905 #$fio->log("$fio->{rxFile}{name}: file is unchanged");
906 # if ( $fio->{logLevel} >= 8 );
911 # need to open an output file where we will build the
914 $fio->{rxFile}{name} =~ /(.*)/s;
915 my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
916 my $rxOutFile = $fio->{outDir} . $rxOutFileRel;
917 $fio->{rxOutFd} = BackupPC::PoolWrite->new($fio->{bpc},
918 $rxOutFile, $fio->{rxFile}{size},
919 $fio->{xfer}{compress});
920 $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
921 if ( $fio->{logLevel} >= 9 );
922 $fio->{rxOutFile} = $rxOutFile;
923 $fio->{rxOutFileRel} = $rxOutFileRel;
924 $fio->{rxDigest} = File::RsyncP::Digest->new();
925 $fio->{rxDigest}->protocol($fio->{protocol_version});
926 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
928 if ( defined($fio->{rxMatchBlk})
929 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
931 # Need to copy the sequence of blocks that matched. If the file
932 # is compressed we need to make a copy of the uncompressed file,
933 # since the compressed file is not seekable. Future optimizations
934 # could include only creating an uncompressed copy if the matching
935 # blocks were not monotonic, and to only do this if there are
936 # matching blocks (eg, maybe the entire file is new).
938 my $attr = $fio->{rxLocalAttr};
940 if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
941 my $inPath = $attr->{fullPath};
942 $inPath = $fio->{rxHLinkAttr}{fullPath}
943 if ( defined($fio->{rxHLinkAttr}) );
944 if ( $attr->{compress} ) {
945 if ( !defined($fh = BackupPC::FileZIO->open(
948 $attr->{compress})) ) {
949 $fio->log("Can't open $inPath");
950 $fio->{stats}{errorCnt}++;
953 if ( $attr->{size} < 16 * 1024 * 1024 ) {
955 # Cache the entire old file if it is less than 16MB
958 $fio->{rxInData} = "";
959 while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
960 $fio->{rxInData} .= $data;
962 $fio->log("$attr->{fullPath}: cached all $attr->{size}"
964 if ( $fio->{logLevel} >= 9 );
967 # Create and write a temporary output file
969 unlink("$fio->{outDirSh}RStmp")
970 if ( -f "$fio->{outDirSh}RStmp" );
971 if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
975 while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
976 if ( syswrite(F, $data) != length($data) ) {
977 $fio->log(sprintf("Can't write len=%d to %s",
978 length($data) , "$fio->{outDirSh}RStmp"));
980 $fio->{stats}{errorCnt}++;
983 $byteCnt += length($data);
986 $fio->{rxInName} = "$fio->{outDirSh}RStmp";
987 sysseek($fio->{rxInFd}, 0, 0);
988 $fio->log("$attr->{fullPath}: copied $byteCnt,"
989 . "$attr->{size} bytes to $fio->{rxInName}")
990 if ( $fio->{logLevel} >= 9 );
992 $fio->log("Unable to open $fio->{outDirSh}RStmp");
994 $fio->{stats}{errorCnt}++;
1000 if ( open(F, "<", $inPath) ) {
1002 $fio->{rxInFd} = *F;
1003 $fio->{rxInName} = $attr->{fullPath};
1005 $fio->log("Unable to open $inPath");
1006 $fio->{stats}{errorCnt}++;
1011 my $lastBlk = $fio->{rxMatchNext} - 1;
1012 $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1014 if ( $fio->{logLevel} >= 9 );
1015 my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
1016 if ( defined($fio->{rxInFd})
1017 && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
1018 $fio->log("Unable to seek $fio->{rxInName} to $seekPosn");
1019 $fio->{stats}{errorCnt}++;
1022 my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
1023 my($thisCnt, $len, $data);
1024 for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
1025 $thisCnt = $cnt - $i;
1026 $thisCnt = 512 if ( $thisCnt > 512 );
1027 if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
1028 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
1030 $len = $thisCnt * $fio->{rxBlkSize};
1032 if ( defined($fio->{rxInData}) ) {
1033 $data = substr($fio->{rxInData}, $seekPosn, $len);
1036 my $got = sysread($fio->{rxInFd}, $data, $len);
1037 if ( $got != $len ) {
1038 my $inFileSize = -s $fio->{rxInName};
1039 $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1040 . " got=$got, seekPosn=$seekPosn"
1041 . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1042 . ",$attr->{size})");
1043 $fio->{stats}{errorCnt}++;
1048 $fio->{rxOutFd}->write(\$data);
1049 $fio->{rxDigest}->add($data);
1050 $fio->{rxSize} += length($data);
1052 $fio->{rxMatchBlk} = undef;
1054 if ( defined($blk) ) {
1056 # Remember the new block number
1058 $fio->{rxMatchBlk} = $blk;
1059 $fio->{rxMatchNext} = $blk + 1;
1061 if ( defined($newData) ) {
1063 # Write the new chunk
1065 my $len = length($newData);
1066 $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1067 if ( $fio->{logLevel} >= 9 );
1068 $fio->{rxOutFd}->write(\$newData);
1069 $fio->{rxDigest}->add($newData);
1070 $fio->{rxSize} += length($newData);
1075 # Finish up the current receive file. Returns undef if ok, -1 if not.
1076 # Returns 1 if the md4 digest doesn't match.
1080 my($fio, $md4, $phase) = @_;
1081 my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1084 close($fio->{rxInFd}) if ( defined($fio->{rxInFd}) );
1085 unlink("$fio->{outDirSh}RStmp") if ( -f "$fio->{outDirSh}RStmp" );
1086 $fio->{phase} = $phase;
1089 # Check the final md4 digest
1091 if ( defined($md4) ) {
1093 if ( !defined($fio->{rxDigest}) ) {
1095 # File was exact match, but we still need to verify the
1096 # MD4 checksum. Compute the md4 digest (or fetch the
1099 if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1101 # block size doesn't matter: we're only going to
1102 # fetch the md4 file digest, not the block digests.
1104 my($err, $csum, $blkSize)
1105 = BackupPC::Xfer::RsyncDigest->digestStart(
1106 $attr->{fullPath}, $attr->{size},
1107 0, 2048, $fio->{checksumSeed}, 1,
1108 $attr->{compress}, 1,
1109 $fio->{protocol_version});
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;