* Removed default paths from conf/config.pl so configure.pl will
[BackupPC.git] / lib / BackupPC / Xfer / RsyncFileIO.pm
1 #============================================================= -*-perl-*-
2 #
3 # Rsync package
4 #
5 # DESCRIPTION
6 #
7 # AUTHOR
8 #   Craig Barratt  <cbarratt@users.sourceforge.net>
9 #
10 # COPYRIGHT
11 #   Copyright (C) 2002-2003  Craig Barratt
12 #
13 #========================================================================
14 #
15 # Version 3.0.0beta2, released 11 Nov 2006.
16 #
17 # See http://backuppc.sourceforge.net.
18 #
19 #========================================================================
20
21 package BackupPC::Xfer::RsyncFileIO;
22
23 use strict;
24 use File::Path;
25 use Encode qw/from_to/;
26 use BackupPC::Attrib qw(:all);
27 use BackupPC::View;
28 use BackupPC::Xfer::RsyncDigest qw(:all);
29 use BackupPC::PoolWrite;
30
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
40
41 use vars qw( $RsyncLibOK );
42
43 BEGIN {
44     eval "use File::RsyncP::Digest";
45     if ( $@ ) {
46         #
47         # Rsync module doesn't exist.
48         #
49         $RsyncLibOK = 0;
50     } else {
51         $RsyncLibOK = 1;
52     }
53 };
54
55 sub new
56 {
57     my($class, $options) = @_;
58
59     return if ( !$RsyncLibOK );
60     $options ||= {};
61     my $fio = bless {
62         blockSize    => 700,
63         logLevel     => 0,
64         digest       => File::RsyncP::Digest->new(),
65         checksumSeed => 0,
66         attrib       => {},
67         logHandler   => \&logHandler,
68         stats        => {
69             errorCnt          => 0,
70             TotalFileCnt      => 0,
71             TotalFileSize     => 0,
72             ExistFileCnt      => 0,
73             ExistFileSize     => 0,
74             ExistFileCompSize => 0,
75         },
76         %$options,
77     }, $class;
78
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},
84                                          $fio->{backups});
85     $fio->{full}     = $fio->{xfer}{type} eq "full" ? 1 : 0;
86     $fio->{newFilesFH} = $fio->{xfer}{newFilesFH};
87     $fio->{partialNum} = undef if ( !$fio->{full} );
88     return $fio;
89 }
90
91 #
92 # We publish our version to File::RsyncP.  This is so File::RsyncP
93 # can provide backward compatibility to older FileIO code.
94 #
95 # Versions:
96 #
97 #   undef or 1:  protocol version 26, no hardlinks
98 #   2:           protocol version 28, supports hardlinks
99 #
100 sub version
101 {
102     return 2;
103 }
104
105 sub blockSize
106 {
107     my($fio, $value) = @_;
108
109     $fio->{blockSize} = $value if ( defined($value) );
110     return $fio->{blockSize};
111 }
112
113 sub protocol_version
114 {
115     my($fio, $value) = @_;
116
117     if ( defined($value) ) {
118         $fio->{protocol_version} = $value;
119         $fio->{digest}->protocol($fio->{protocol_version});
120     }
121     return $fio->{protocol_version};
122 }
123
124 sub preserve_hard_links
125 {
126     my($fio, $value) = @_;
127
128     $fio->{preserve_hard_links} = $value if ( defined($value) );
129     return $fio->{preserve_hard_links};
130 }
131
132 sub logHandlerSet
133 {
134     my($fio, $sub) = @_;
135     $fio->{logHandler} = $sub;
136     BackupPC::Xfer::RsyncDigest->logHandlerSet($sub);
137 }
138
139 #
140 # Setup rsync checksum computation for the given file.
141 #
142 sub csumStart
143 {
144     my($fio, $f, $needMD4, $defBlkSize, $phase) = @_;
145
146     $defBlkSize ||= $fio->{blockSize};
147     my $attr = $fio->attribGet($f, 1);
148     $fio->{file} = $f;
149     $fio->csumEnd if ( defined($fio->{csum}) );
150     return -1 if ( $attr->{type} != BPC_FTYPE_FILE );
151
152     #
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.
156     #
157     if ( ($phase > 0 || rand(1) < $fio->{cacheCheckProb})
158             && $attr->{compress}
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");
169         }
170         if ( $isCached || $isInvalid ) {
171             my $ret = BackupPC::Xfer::RsyncDigest->digestAdd(
172                             $attr->{fullPath}, $blkSize,
173                             $fio->{checksumSeed}, 1,        # verify
174                             $fio->{protocol_version}
175                         );
176             if ( $ret != 1 ) {
177                 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
178                         . " fixed");
179                 $fio->{stats}{errorCnt}++;
180             } else {
181                 $fio->log("$f->{name}: verified cached digest")
182                                     if ( $fio->{logLevel} >= 2 );
183             }
184         }
185         $d->digestEnd;
186     }
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});
191     if ( $err ) {
192         $fio->log("Can't get rsync digests from $attr->{fullPath}"
193                 . " (err=$err, name=$f->{name})");
194         $fio->{stats}{errorCnt}++;
195         return -1;
196     }
197     if ( $fio->{logLevel} >= 5 ) {
198         my($isCached, $invalid) = $fio->{csum}->isCached;
199         $fio->log("$attr->{fullPath} cache = $isCached,"
200                 . " invalid = $invalid, phase = $phase");
201     }
202     return $blkSize;
203 }
204
205 sub csumGet
206 {
207     my($fio, $num, $csumLen, $blockSize) = @_;
208     my($fileData);
209
210     $num     ||= 100;
211     $csumLen ||= 16;
212     return if ( !defined($fio->{csum}) );
213     return $fio->{csum}->digestGet($num, $csumLen);
214 }
215
216 sub csumEnd
217 {
218     my($fio) = @_;
219
220     return if ( !defined($fio->{csum}) );
221     return $fio->{csum}->digestEnd();
222 }
223
224 sub readStart
225 {
226     my($fio, $f) = @_;
227
228     my $attr = $fio->attribGet($f, 1);
229     $fio->{file} = $f;
230     $fio->readEnd if ( defined($fio->{fh}) );
231     if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
232                                            0,
233                                            $attr->{compress})) ) {
234         $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
235         $fio->{stats}{errorCnt}++;
236         return;
237     }
238     $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
239 }
240
241 sub read
242 {
243     my($fio, $num) = @_;
244     my $fileData;
245
246     $num ||= 32768;
247     return if ( !defined($fio->{fh}) );
248     if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
249         return $fio->readEnd;
250     }
251     $fio->log(sprintf("read returns %d bytes", length($fileData)))
252                                 if ( $fio->{logLevel} >= 8 );
253     return \$fileData;
254 }
255
256 sub readEnd
257 {
258     my($fio) = @_;
259
260     return if ( !defined($fio->{fh}) );
261     $fio->{fh}->close;
262     $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
263     delete($fio->{fh});
264     return;
265 }
266
267 sub checksumSeed
268 {
269     my($fio, $checksumSeed) = @_;
270
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 );
276 }
277
278 sub dirs
279 {
280     my($fio, $localDir, $remoteDir) = @_;
281
282     $fio->{localDir}  = $localDir;
283     $fio->{remoteDir} = $remoteDir;
284 }
285
286 sub viewCacheDir
287 {
288     my($fio, $share, $dir) = @_;
289     my $shareM;
290
291     #$fio->log("viewCacheDir($share, $dir)");
292     if ( !defined($share) ) {
293         $share  = $fio->{share};
294         $shareM = $fio->{shareM};
295     } else {
296         $shareM = $fio->{bpc}->fileNameEltMangle($share);
297     }
298     $shareM = "$shareM/$dir" if ( $dir ne "" );
299     return if ( defined($fio->{viewCache}{$shareM}) );
300     #
301     # purge old cache entries (ie: those that don't match the
302     # first part of $dir).
303     #
304     foreach my $d ( keys(%{$fio->{viewCache}}) ) {
305         delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
306     }
307     #
308     # fetch new directory attributes
309     #
310     $fio->{viewCache}{$shareM}
311                 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
312     #
313     # also cache partial backup attrib data too
314     #
315     if ( defined($fio->{partialNum}) ) {
316         foreach my $d ( keys(%{$fio->{partialCache}}) ) {
317             delete($fio->{partialCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
318         }
319         $fio->{partialCache}{$shareM}
320                     = $fio->{view}->dirAttrib($fio->{partialNum}, $share, $dir);
321     }
322 }
323
324 sub attribGetWhere
325 {
326     my($fio, $f, $noCache, $fname) = @_;
327     my($dir, $share, $shareM, $partial, $attr);
328
329     if ( !defined($fname) ) {
330         $fname = $f->{name};
331         $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
332                        if ( defined($fio->{xfer}{pathHdrSrc}) );
333     }
334     $fname =~ s{//+}{/}g;
335     if ( $fname =~ m{(.*)/(.*)}s ) {
336         $shareM = $fio->{shareM};
337         $dir = $1;
338         $fname = $2;
339     } elsif ( $fname ne "." ) {
340         $shareM = $fio->{shareM};
341         $dir = "";
342     } else {
343         $share = "";
344         $shareM = "";
345         $dir = "";
346         $fname = $fio->{share};
347     }
348     $shareM .= "/$dir" if ( $dir ne "" );
349
350     if ( $noCache ) {
351         $share  = $fio->{share} if ( !defined($share) );
352         my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
353         $attr = $dirAttr->{$fname};
354     } else {
355         $fio->viewCacheDir($share, $dir);
356         if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
357             $partial = 0;
358         } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
359             $partial = 1;
360         } else {
361             return;
362         }
363         if ( $attr->{mode} & S_HLINK_TARGET ) {
364             $attr->{hlink_self} = 1;
365             $attr->{mode} &= ~S_HLINK_TARGET;
366         }
367     }
368     return ($attr, $partial);
369 }
370
371 sub attribGet
372 {
373     my($fio, $f, $doHardLink) = @_;
374
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,
380                                          $attr->{compress});
381         my $target;
382         if ( defined($fh) ) {
383             $fh->read(\$target,  65536);
384             $fh->close;
385             $target =~ s/^\.?\/+//;
386         } else {
387             $fio->log("$attr->{fullPath}: can't open for hardlink read");
388             $fio->{stats}{errorCnt}++;
389             $attr->{type} = BPC_FTYPE_FILE;
390             return $attr;
391         }
392         $target = "/$target" if ( $target !~ /^\// );
393         $fio->log("$attr->{fullPath}: redirecting to $target")
394                                     if ( $fio->{logLevel} >= 4 );
395         $target =~ s{^/+}{};
396         ($attr) = $fio->attribGetWhere($f, 1, $target);
397         $fio->log(" ... now got $attr->{fullPath}")
398                             if ( $fio->{logLevel} >= 4 );
399     }
400     return $attr;
401 }
402
403 sub mode2type
404 {
405     my($fio, $f) = @_;
406     my $mode = $f->{mode};
407
408     if ( ($mode & S_IFMT) == S_IFREG ) {
409         if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
410             return BPC_FTYPE_HARDLINK;
411         } else {
412             return BPC_FTYPE_FILE;
413         }
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;
426     } else {
427         return BPC_FTYPE_UNKNOWN;
428     }
429 }
430
431 #
432 # Set the attributes for a file.  Returns non-zero on error.
433 #
434 sub attribSet
435 {
436     my($fio, $f, $placeHolder) = @_;
437     my($dir, $file);
438
439     if ( $f->{name} =~ m{(.*)/(.*)}s ) {
440         $file = $2;
441         $dir  = "$fio->{shareM}/" . $1;
442     } elsif ( $f->{name} eq "." ) {
443         $dir  = "";
444         $file = $fio->{share};
445     } else {
446         $dir  = $fio->{shareM};
447         $file = $f->{name};
448     }
449
450     if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
451         #
452         # Flush any directories that don't match the first part
453         # of the new directory
454         #
455         foreach my $d ( keys(%{$fio->{attrib}}) ) {
456             next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
457             $fio->attribWrite($d);
458         }
459         $fio->{attribLastDir} = $dir;
460     }
461     if ( !exists($fio->{attrib}{$dir}) ) {
462         $fio->{attrib}{$dir} = BackupPC::Attrib->new({
463                                      compress => $fio->{xfer}{compress},
464                                 });
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)));
470         }
471     }
472     $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
473
474     my $mode = $f->{mode};
475
476     $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
477     $fio->{attrib}{$dir}->set($file, {
478                             type  => $fio->mode2type($f),
479                             mode  => $mode,
480                             uid   => $f->{uid},
481                             gid   => $f->{gid},
482                             size  => $placeHolder ? -1 : $f->{size},
483                             mtime => $f->{mtime},
484                        });
485     return;
486 }
487
488 sub attribWrite
489 {
490     my($fio, $d) = @_;
491     my($poolWrite);
492
493     #
494     # Don't write attributes on 2nd phase - they're already
495     # taken care of during the first phase.
496     #
497     return if ( $fio->{phase} > 0 );
498     if ( !defined($d) ) {
499         #
500         # flush all entries (in reverse order)
501         #
502         foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
503             $fio->attribWrite($d);
504         }
505         return;
506     }
507     return if ( !defined($fio->{attrib}{$d}) );
508     #
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.
514     #
515     if ( $d ne "" ) {
516         my $dir;
517         my $share;
518
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}}) ) {
530                 my $name = $f;
531                 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
532                 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
533                     #
534                     # delete temporary attributes (skipped files)
535                     #
536                     if ( $a->{size} < 0 ) {
537                         $fio->{attrib}{$d}->set($f, undef);
538                         $fio->logFileAction("skip", {
539                                     %{$fio->{viewCache}{$d}{$f}},
540                                     name => $name,
541                                 }) if ( $fio->{logLevel} >= 2
542                                       && $a->{type} == BPC_FTYPE_FILE );
543                     }
544                 } elsif ( !$fio->{full} ) {
545                     ##print("Delete file $f\n");
546                     $fio->logFileAction("delete", {
547                                 %{$fio->{viewCache}{$d}{$f}},
548                                 name => $name,
549                             }) if ( $fio->{logLevel} >= 1 );
550                     $fio->{attrib}{$d}->set($f, {
551                                     type  => BPC_FTYPE_DELETED,
552                                     mode  => 0,
553                                     uid   => 0,
554                                     gid   => 0,
555                                     size  => 0,
556                                     mtime => 0,
557                                });
558                 }
559             }
560         }
561     }
562     if ( $fio->{attrib}{$d}->fileCount ) {
563         my $data = $fio->{attrib}{$d}->writeData;
564         my $dirM = $d;
565
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),
575                            length($data), 0);
576     }
577     delete($fio->{attrib}{$d});
578 }
579
580 sub processClose
581 {
582     my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
583     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
584
585     $fileName =~ s{^/+}{};
586     $fio->log(@$errs) if ( defined($errs) && @$errs );
587     if ( $doStats ) {
588         $fio->{stats}{TotalFileCnt}++;
589         $fio->{stats}{TotalFileSize} += $origSize;
590     }
591     if ( $exists ) {
592         if ( $doStats ) {
593             $fio->{stats}{ExistFileCnt}++;
594             $fio->{stats}{ExistFileSize}     += $origSize;
595             $fio->{stats}{ExistFileCompSize} += $outSize;
596         }
597     } elsif ( $outSize > 0 ) {
598         my $fh = $fio->{newFilesFH};
599         print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
600     }
601     return $exists && $origSize > 0;
602 }
603
604 sub statsGet
605 {
606     my($fio) = @_;
607
608     return $fio->{stats};
609 }
610
611 #
612 # Make a given directory.  Returns non-zero on error.
613 #
614 sub makePath
615 {
616     my($fio, $f) = @_;
617     my $name = $1 if ( $f->{name} =~ /(.*)/s );
618     my $path;
619
620     if ( $name eq "." ) {
621         $path = $fio->{outDirSh};
622     } else {
623         $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
624     }
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}++;
632     return -1;
633 }
634
635 #
636 # Make a special file.  Returns non-zero on error.
637 #
638 sub makeSpecial
639 {
640     my($fio, $f) = @_;
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);
645     my $str = "";
646     my $type = $fio->mode2type($f);
647
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);
652
653         if ( defined($f->{rdev_major}) ) {
654             $major = $f->{rdev_major};
655             $minor = $f->{rdev_minor};
656         } else {
657             $major = $f->{rdev} >> 8;
658             $minor = $f->{rdev} & 0xff;
659         }
660         $str = "$major,$minor";
661     } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
662         $str = $f->{link};
663     } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
664         #
665         # this is a hardlink
666         #
667         if ( !defined($f->{hlink}) ) {
668             $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
669                     . " on a regular non-hardlink file");
670             return 1;
671         }
672         $str  = $f->{hlink};
673     }
674     #
675     # Now see if the file is different, or this is a full, in which
676     # case we create the new file.
677     #
678     my($fh, $fileData);
679     if ( $fio->{full}
680             || !defined($attr)
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,
689                                                       $attr->{compress}))
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});
695         $fh->write(\$str);
696         my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
697                                        length($str), 1);
698         $fio->logFileAction($exist ? "pool" : "create", $f)
699                             if ( $fio->{logLevel} >= 1 );
700         return $fio->attribSet($f);
701     } else {
702         $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
703     }
704     $fh->close if ( defined($fh) );
705 }
706
707 #
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
713 # hardlinks).
714 #
715 sub makeHardLink
716 {
717     my($fio, $f, $end) = @_;
718
719     return if ( $end );
720     return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
721 }
722
723 sub unlink
724 {
725     my($fio, $path) = @_;
726     
727     $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)"); 
728 }
729
730 #
731 # Default log handler
732 #
733 sub logHandler
734 {
735     my($str) = @_;
736
737     print(STDERR $str, "\n");
738 }
739
740 #
741 # Handle one or more log messages
742 #
743 sub log
744 {
745     my($fio, @logStr) = @_;
746
747     foreach my $str ( @logStr ) {
748         next if ( $str eq "" );
749         $fio->{logHandler}($str);
750     }
751 }
752
753 #
754 # Generate a log file message for a completed file
755 #
756 sub logFileAction
757 {
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};
763
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}";
769     }
770     $name =~ s/\n/\\n/g;
771
772     $fio->log(sprintf("  %-6s %1s%4o %9s %11.0f %s",
773                                 $action,
774                                 $type,
775                                 $f->{mode} & 07777,
776                                 $owner,
777                                 $f->{size},
778                                 $name));
779 }
780
781 #
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).
787 #
788 sub ignoreAttrOnFile
789 {
790     my($fio, $f) = @_;
791
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 );
796     return !$isPartial;
797 }
798
799 #
800 # This is called by File::RsyncP when a file is skipped because the
801 # attributes match.
802 #
803 sub attrSkippedFile
804 {
805     my($fio, $f, $attr) = @_;
806
807     #
808     # Unless this is a partial, this is normal so ignore it.
809     #
810     return if ( !defined($fio->{partialNum}) );
811
812     $fio->log("$f->{name}: skipped in partial; adding link")
813                                     if ( $fio->{logLevel} >= 5 );
814     $fio->{rxLocalAttr} = $attr;
815     $fio->{rxFile} = $f;
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();
822 }
823
824 #
825 # Start receive of file deltas for a particular file.
826 #
827 sub fileDeltaRxStart
828 {
829     my($fio, $f, $cnt, $size, $remainder) = @_;
830
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 );
845     }
846     #
847     # If compression was off and now on, or on and now off, then
848     # don't do an exact match.
849     #
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 );
856     }
857     #
858     # If the local file is a hardlink then no match
859     #
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 );
865         my $fCopy;
866         # need to copy since hardlink attribGet overwrites the name
867         %{$fCopy} = %$f;
868         $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
869     } else {
870         delete($fio->{rxHLinkAttr});
871     }
872     delete($fio->{rxInFd});
873     delete($fio->{rxOutFd});
874     delete($fio->{rxDigest});
875     delete($fio->{rxInData});
876 }
877
878 #
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.
882 #
883 sub fileDeltaRxNext
884 {
885     my($fio, $blk, $newData) = @_;
886
887     if ( defined($blk) ) {
888         if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
889             #
890             # got the next block in order; just keep track.
891             #
892             $fio->{rxMatchNext}++;
893             return;
894         }
895     }
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}) ) {
900         #
901         # maybe the file has no changes
902         #
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 );
907             return;
908         }
909
910         #
911         # need to open an output file where we will build the
912         # new version.
913         #
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}));
927     }
928     if ( defined($fio->{rxMatchBlk})
929                 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
930         #
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).
937         #
938         my $attr = $fio->{rxLocalAttr};
939         my $fh;
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(
946                                                    $inPath,
947                                                    0,
948                                                    $attr->{compress})) ) {
949                     $fio->log("Can't open $inPath");
950                     $fio->{stats}{errorCnt}++;
951                     return -1;
952                 }
953                 if ( $attr->{size} < 16 * 1024 * 1024 ) {
954                     #
955                     # Cache the entire old file if it is less than 16MB
956                     #
957                     my $data;
958                     $fio->{rxInData} = "";
959                     while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
960                         $fio->{rxInData} .= $data;
961                     }
962                     $fio->log("$attr->{fullPath}: cached all $attr->{size}"
963                             . " bytes")
964                                     if ( $fio->{logLevel} >= 9 );
965                 } else {
966                     #
967                     # Create and write a temporary output file
968                     #
969                     unlink("$fio->{outDirSh}RStmp")
970                                     if  ( -f "$fio->{outDirSh}RStmp" );
971                     if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
972                         my $data;
973                         my $byteCnt = 0;
974                         binmode(F);
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"));
979                                 $fh->close;
980                                 $fio->{stats}{errorCnt}++;
981                                 return -1;
982                             }
983                             $byteCnt += length($data);
984                         }
985                         $fio->{rxInFd} = *F;
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 );
991                     } else {
992                         $fio->log("Unable to open $fio->{outDirSh}RStmp");
993                         $fh->close;
994                         $fio->{stats}{errorCnt}++;
995                         return -1;
996                     }
997                 }
998                 $fh->close;
999             } else {
1000                 if ( open(F, "<", $inPath) ) {
1001                     binmode(F);
1002                     $fio->{rxInFd} = *F;
1003                     $fio->{rxInName} = $attr->{fullPath};
1004                 } else {
1005                     $fio->log("Unable to open $inPath");
1006                     $fio->{stats}{errorCnt}++;
1007                     return -1;
1008                 }
1009             }
1010         }
1011         my $lastBlk = $fio->{rxMatchNext} - 1;
1012         $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1013                   . "$lastBlk")
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}++;
1020             return -1;
1021         }
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};
1029             } else {
1030                 $len = $thisCnt * $fio->{rxBlkSize};
1031             }
1032             if ( defined($fio->{rxInData}) ) {
1033                 $data = substr($fio->{rxInData}, $seekPosn, $len);
1034                 $seekPosn += $len;
1035             } else {
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}++;
1044                     return -1;
1045                 }
1046                 $seekPosn += $len;
1047             }
1048             $fio->{rxOutFd}->write(\$data);
1049             $fio->{rxDigest}->add($data);
1050             $fio->{rxSize} += length($data);
1051         }
1052         $fio->{rxMatchBlk} = undef;
1053     }
1054     if ( defined($blk) ) {
1055         #
1056         # Remember the new block number
1057         #
1058         $fio->{rxMatchBlk}  = $blk;
1059         $fio->{rxMatchNext} = $blk + 1;
1060     }
1061     if ( defined($newData) ) {
1062         #
1063         # Write the new chunk
1064         #
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);
1071     }
1072 }
1073
1074 #
1075 # Finish up the current receive file.  Returns undef if ok, -1 if not.
1076 # Returns 1 if the md4 digest doesn't match.
1077 #
1078 sub fileDeltaRxDone
1079 {
1080     my($fio, $md4, $phase) = @_;
1081     my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1082     my $ret;
1083
1084     close($fio->{rxInFd})  if ( defined($fio->{rxInFd}) );
1085     unlink("$fio->{outDirSh}RStmp") if  ( -f "$fio->{outDirSh}RStmp" );
1086     $fio->{phase} = $phase;
1087
1088     #
1089     # Check the final md4 digest
1090     #
1091     if ( defined($md4) ) {
1092         my $newDigest;
1093         if ( !defined($fio->{rxDigest}) ) {
1094             #
1095             # File was exact match, but we still need to verify the
1096             # MD4 checksum.  Compute the md4 digest (or fetch the
1097             # cached one.)
1098             #
1099             if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1100                 #
1101                 # block size doesn't matter: we're only going to
1102                 # fetch the md4 file digest, not the block digests.
1103                 #
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});
1110                 if ( $err ) {
1111                     $fio->log("Can't open $attr->{fullPath} for MD4"
1112                             . " check (err=$err, $name)");
1113                     $fio->{stats}{errorCnt}++;
1114                 } else {
1115                     if ( $fio->{logLevel} >= 5 ) {
1116                         my($isCached, $invalid) = $csum->isCached;
1117                         $fio->log("MD4 $attr->{fullPath} cache = $isCached,"
1118                                 . " invalid = $invalid");
1119                     }
1120                     $newDigest = $csum->digestEnd;
1121                 }
1122                 $fio->{rxSize} = $attr->{size};
1123             } else {
1124                 #
1125                 # Empty file; just create an empty file digest
1126                 #
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;
1131             }
1132             $fio->log("$name got exact match") if ( $fio->{logLevel} >= 5 );
1133         } else {
1134             $newDigest = $fio->{rxDigest}->digest;
1135         }
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")
1140         }
1141         if ( $md4 ne $newDigest ) {
1142             if ( $phase > 0 ) {
1143                 $fio->log("$name: fatal error: md4 doesn't match on retry;"
1144                         . " file removed");
1145             } else {
1146                 $fio->log("$name: md4 doesn't match: will retry in phase 1;"
1147                         . " file removed");
1148             }
1149             $fio->{stats}{errorCnt}++;
1150             if ( defined($fio->{rxOutFd}) ) {
1151                 $fio->{rxOutFd}->close;
1152                 unlink($fio->{rxOutFile});
1153             }
1154             delete($fio->{rxFile});
1155             delete($fio->{rxOutFile});
1156             return 1;
1157         }
1158     }
1159
1160     #
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.
1163     #
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});
1171     }
1172     if ( !defined($fio->{rxOutFd}) ) {
1173         #
1174         # No output file, meaning original was an exact match.
1175         #
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 );
1181         if ( $fio->{full}
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} ) {
1189             #
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.
1193             #
1194             my $rxOutFile = $fio->{outDirSh}
1195                             . $fio->{bpc}->fileNameMangle($name);
1196             my($exists, $digest, $origSize, $outSize, $errs)
1197                                 = BackupPC::PoolWrite::LinkOrCopy(
1198                                       $fio->{bpc},
1199                                       $attr->{fullPath},
1200                                       $attr->{compress},
1201                                       $rxOutFile,
1202                                       $fio->{xfer}{compress});
1203             #
1204             # Cumulate the stats
1205             #
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 );
1214
1215             if ( !$exists && $outSize > 0 ) {
1216                 #
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.
1220                 #
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) );
1227             }
1228         }
1229     } else {
1230         my $exist = $fio->processClose($fio->{rxOutFd},
1231                                        $fio->{rxOutFileRel},
1232                                        $fio->{rxSize}, 1);
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});
1237     }
1238     delete($fio->{rxDigest});
1239     delete($fio->{rxInData});
1240     delete($fio->{rxFile});
1241     delete($fio->{rxOutFile});
1242     return $ret;
1243 }
1244
1245 #
1246 # Callback function for BackupPC::View->find.  Note the order of the
1247 # first two arguments.
1248 #
1249 sub fileListEltSend
1250 {
1251     my($a, $fio, $fList, $outputFunc) = @_;
1252     my $name = $a->{relPath};
1253     my $n = $name;
1254     my $type = $a->{type};
1255     my $extraAttribs = {};
1256
1257     if ( $a->{mode} & S_HLINK_TARGET ) {
1258         $a->{hlink_self} = 1;
1259         $a->{mode} &= ~S_HLINK_TARGET;
1260     }
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});
1267         my($str, $rdSize);
1268         if ( defined($fh) ) {
1269             $rdSize = $fh->read(\$str, $a->{size} + 1024);
1270             if ( $type == BPC_FTYPE_SYMLINK ) {
1271                 #
1272                 # Reconstruct symbolic link
1273                 #
1274                 $extraAttribs = { link => $str };
1275                 if ( $rdSize != $a->{size} ) {
1276                     # ERROR
1277                     $fio->log("$name: can't read exactly $a->{size} bytes");
1278                     $fio->{stats}{errorCnt}++;
1279                 }
1280             } elsif ( $str =~ /(\d*),(\d*)/ ) {
1281                 #
1282                 # Reconstruct char or block special major/minor device num
1283                 #
1284                 # Note: char/block devices have $a->{size} = 0, so we
1285                 # can't do an error check on $rdSize.
1286                 #
1287                 $extraAttribs = {
1288                     rdev       => $1 * 256 + $2,
1289                     rdev_major => $1,
1290                     rdev_minor => $2,
1291                 };
1292             } else {
1293                 $fio->log("$name: unexpected special file contents $str");
1294                 $fio->{stats}{errorCnt}++;
1295             }
1296             $fh->close;
1297         } else {
1298             # ERROR
1299             $fio->log("$name: can't open");
1300             $fio->{stats}{errorCnt}++;
1301         }
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}) ) {
1307         #
1308         # Fill in fake inode information so that the remote rsync
1309         # can correctly create hardlinks.
1310         #
1311         $name =~ s/^\.?\/+//;
1312         my($target, $inode);
1313
1314         if ( $type == BPC_FTYPE_HARDLINK ) {
1315             my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0,
1316                                              $a->{compress});
1317             if ( defined($fh) ) {
1318                 $fh->read(\$target,  65536);
1319                 $fh->close;
1320                 $target =~ s/^\.?\/+//;
1321                 if ( defined($fio->{hlinkFile2Num}{$target}) ) {
1322                     $inode = $fio->{hlinkFile2Num}{$target};
1323                 } else {
1324                     $inode = $fio->{fileListCnt};
1325                     $fio->{hlinkFile2Num}{$target} = $inode;
1326                 }
1327             } else {
1328                 $fio->log("$a->{fullPath}: can't open for hardlink");
1329                 $fio->{stats}{errorCnt}++;
1330             }
1331         } elsif ( $a->{hlink_self} ) {
1332             if ( defined($fio->{hlinkFile2Num}{$name}) ) {
1333                 $inode = $fio->{hlinkFile2Num}{$name};
1334             } else {
1335                 $inode = $fio->{fileListCnt};
1336                 $fio->{hlinkFile2Num}{$name} = $inode;
1337             }
1338         }
1339         $inode = $fio->{fileListCnt} if ( !defined($inode) );
1340         $fio->log("$name: setting inode to $inode");
1341         $extraAttribs = {
1342             %$extraAttribs,
1343             dev   => 0,
1344             inode => $inode,
1345         };
1346     }
1347     my $f = {
1348         name  => $n,
1349         mode  => $a->{mode} & ~S_HLINK_TARGET,
1350         uid   => $a->{uid},
1351         gid   => $a->{gid},
1352         mtime => $a->{mtime},
1353         size  => $a->{size},
1354         %$extraAttribs,
1355     };
1356     my $logName = $f->{name};
1357     from_to($f->{name}, "utf8", $fio->{clientCharset})
1358                             if ( $fio->{clientCharset} ne "" );
1359     $fList->encode($f);
1360
1361     $logName = "$fio->{xfer}{pathHdrDest}/$logName";
1362     $logName =~ s{//+}{/}g;
1363     $f->{name} = $logName;
1364     $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1365
1366     &$outputFunc($fList->encodeData);
1367     #
1368     # Cumulate stats
1369     #
1370     $fio->{fileListCnt}++;
1371     if ( $type != BPC_FTYPE_DIR ) {
1372         $fio->{stats}{TotalFileCnt}++;
1373         $fio->{stats}{TotalFileSize} += $a->{size};
1374     }
1375 }
1376
1377 sub fileListSend
1378 {
1379     my($fio, $flist, $outputFunc) = @_;
1380
1381     #
1382     # Populate the file list with the files requested by the user.
1383     # Since some might be directories so we call BackupPC::View::find.
1384     #
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},
1392                            $name, 1,
1393                            \&fileListEltSend, $fio, $flist, $outputFunc);
1394     }
1395 }
1396
1397 sub finish
1398 {
1399     my($fio, $isChild) = @_;
1400
1401     #
1402     # If we are aborting early, remove the last file since
1403     # it was not complete
1404     #
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}");
1410         }
1411     }
1412
1413     #
1414     # Flush the attributes if this is the child
1415     #
1416     $fio->attribWrite(undef) if ( $isChild );
1417 }
1418
1419 #sub is_tainted
1420 #{
1421 #    return ! eval {
1422 #        join('',@_), kill 0;
1423 #        1;
1424 #    };
1425 #}
1426
1427 1;