additional changes to it.pm (post 3.0.0beta2)
[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                         );
175             if ( $ret != 1 ) {
176                 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
177                         . " fixed");
178                 $fio->{stats}{errorCnt}++;
179             } else {
180                 $fio->log("$f->{name}: verified cached digest")
181                                     if ( $fio->{logLevel} >= 2 );
182             }
183         }
184         $d->digestEnd;
185     }
186     (my $err, $fio->{csum}, my $blkSize)
187          = BackupPC::Xfer::RsyncDigest->digestStart($attr->{fullPath},
188                          $attr->{size}, 0, $defBlkSize, $fio->{checksumSeed},
189                          $needMD4, $attr->{compress}, 1,
190                          $fio->{protocol_version});
191     if ( $fio->{logLevel} >= 5 ) {
192         my($isCached, $invalid) = $fio->{csum}->isCached;
193         $fio->log("$attr->{fullPath} cache = $isCached,"
194                 . " invalid = $invalid, phase = $phase");
195     }
196     if ( $err ) {
197         $fio->log("Can't get rsync digests from $attr->{fullPath}"
198                 . " (err=$err, name=$f->{name})");
199         $fio->{stats}{errorCnt}++;
200         return -1;
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) = @_;
327     my($dir, $fname, $share, $shareM, $partial, $attr);
328
329     $fname = $f->{name};
330     $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
331                        if ( defined($fio->{xfer}{pathHdrSrc}) );
332     $fname =~ s{//+}{/}g;
333     if ( $fname =~ m{(.*)/(.*)}s ) {
334         $shareM = $fio->{shareM};
335         $dir = $1;
336         $fname = $2;
337     } elsif ( $fname ne "." ) {
338         $shareM = $fio->{shareM};
339         $dir = "";
340     } else {
341         $share = "";
342         $shareM = "";
343         $dir = "";
344         $fname = $fio->{share};
345     }
346     $shareM .= "/$dir" if ( $dir ne "" );
347
348     if ( $noCache ) {
349         $share  = $fio->{share} if ( !defined($share) );
350         my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
351         $attr = $dirAttr->{$fname};
352     } else {
353         $fio->viewCacheDir($share, $dir);
354         if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
355             $partial = 0;
356         } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
357             $partial = 1;
358         } else {
359             return;
360         }
361         if ( $attr->{mode} & S_HLINK_TARGET ) {
362             $attr->{hlink_self} = 1;
363             $attr->{mode} &= ~S_HLINK_TARGET;
364         }
365     }
366     return ($attr, $partial);
367 }
368
369 sub attribGet
370 {
371     my($fio, $f, $doHardLink) = @_;
372
373     my($attr) = $fio->attribGetWhere($f);
374     if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
375         $fio->log("$attr->{fullPath}: opening for hardlink read"
376                 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
377         my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
378                                          $attr->{compress});
379         my $target;
380         if ( defined($fh) ) {
381             $fh->read(\$target,  65536);
382             $fh->close;
383             $target =~ s/^\.?\/+//;
384         } else {
385             $fio->log("$attr->{fullPath}: can't open for hardlink read");
386             $fio->{stats}{errorCnt}++;
387             $attr->{type} = BPC_FTYPE_FILE;
388             return $attr;
389         }
390         $target = "/$target" if ( $target !~ /^\// );
391         $fio->log("$attr->{fullPath}: redirecting to $target (will trim "
392                 . "$fio->{xfer}{pathHdrSrc})") if ( $fio->{logLevel} >= 4 );
393         $target =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
394         $target =~ s{^/+}{};
395         #
396         # Note: overwrites name to point to real file
397         #
398         $f->{name} = $target;
399         ($attr) = $fio->attribGetWhere($f, 1);
400         $fio->log(" ... now got $attr->{fullPath}")
401                             if ( $fio->{logLevel} >= 4 );
402     }
403     return $attr;
404 }
405
406 sub mode2type
407 {
408     my($fio, $f) = @_;
409     my $mode = $f->{mode};
410
411     if ( ($mode & S_IFMT) == S_IFREG ) {
412         if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
413             return BPC_FTYPE_HARDLINK;
414         } else {
415             return BPC_FTYPE_FILE;
416         }
417     } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
418         return BPC_FTYPE_DIR;
419     } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
420         return BPC_FTYPE_SYMLINK;
421     } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
422         return BPC_FTYPE_CHARDEV;
423     } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
424         return BPC_FTYPE_BLOCKDEV;
425     } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
426         return BPC_FTYPE_FIFO;
427     } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
428         return BPC_FTYPE_SOCKET;
429     } else {
430         return BPC_FTYPE_UNKNOWN;
431     }
432 }
433
434 #
435 # Set the attributes for a file.  Returns non-zero on error.
436 #
437 sub attribSet
438 {
439     my($fio, $f, $placeHolder) = @_;
440     my($dir, $file);
441
442     if ( $f->{name} =~ m{(.*)/(.*)}s ) {
443         $file = $2;
444         $dir  = "$fio->{shareM}/" . $1;
445     } elsif ( $f->{name} eq "." ) {
446         $dir  = "";
447         $file = $fio->{share};
448     } else {
449         $dir  = $fio->{shareM};
450         $file = $f->{name};
451     }
452
453     if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
454         #
455         # Flush any directories that don't match the first part
456         # of the new directory
457         #
458         foreach my $d ( keys(%{$fio->{attrib}}) ) {
459             next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
460             $fio->attribWrite($d);
461         }
462         $fio->{attribLastDir} = $dir;
463     }
464     if ( !exists($fio->{attrib}{$dir}) ) {
465         $fio->{attrib}{$dir} = BackupPC::Attrib->new({
466                                      compress => $fio->{xfer}{compress},
467                                 });
468         my $path = $fio->{outDir} . $dir;
469         if ( -f $fio->{attrib}{$dir}->fileName($path)
470                     && !$fio->{attrib}{$dir}->read($path) ) {
471             $fio->log(sprintf("Unable to read attribute file %s",
472                             $fio->{attrib}{$dir}->fileName($path)));
473         }
474     }
475     $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
476
477     my $mode = $f->{mode};
478
479     $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
480     $fio->{attrib}{$dir}->set($file, {
481                             type  => $fio->mode2type($f),
482                             mode  => $mode,
483                             uid   => $f->{uid},
484                             gid   => $f->{gid},
485                             size  => $placeHolder ? -1 : $f->{size},
486                             mtime => $f->{mtime},
487                        });
488     return;
489 }
490
491 sub attribWrite
492 {
493     my($fio, $d) = @_;
494     my($poolWrite);
495
496     #
497     # Don't write attributes on 2nd phase - they're already
498     # taken care of during the first phase.
499     #
500     return if ( $fio->{phase} > 0 );
501     if ( !defined($d) ) {
502         #
503         # flush all entries (in reverse order)
504         #
505         foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
506             $fio->attribWrite($d);
507         }
508         return;
509     }
510     return if ( !defined($fio->{attrib}{$d}) );
511     #
512     # Set deleted files in the attributes.  Any file in the view
513     # that doesn't have attributes is flagged as deleted for
514     # incremental dumps.  All files sent by rsync have attributes
515     # temporarily set so we can do deletion detection.  We also
516     # prune these temporary attributes.
517     #
518     if ( $d ne "" ) {
519         my $dir;
520         my $share;
521
522         $dir = $1 if ( $d =~ m{.+?/(.*)}s );
523         $fio->viewCacheDir(undef, $dir);
524         ##print("attribWrite $d,$dir\n");
525         ##$Data::Dumper::Indent = 1;
526         ##$fio->log("attribWrite $d,$dir");
527         ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
528         ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
529         ##print "viewCache = ", Dumper($fio->{attrib});
530         ##print "attrib = ", Dumper($fio->{attrib});
531         if ( defined($fio->{viewCache}{$d}) ) {
532             foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
533                 my $name = $f;
534                 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
535                 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
536                     #
537                     # delete temporary attributes (skipped files)
538                     #
539                     if ( $a->{size} < 0 ) {
540                         $fio->{attrib}{$d}->set($f, undef);
541                         $fio->logFileAction("skip", {
542                                     %{$fio->{viewCache}{$d}{$f}},
543                                     name => $name,
544                                 }) if ( $fio->{logLevel} >= 2
545                                       && $a->{type} == BPC_FTYPE_FILE );
546                     }
547                 } elsif ( !$fio->{full} ) {
548                     ##print("Delete file $f\n");
549                     $fio->logFileAction("delete", {
550                                 %{$fio->{viewCache}{$d}{$f}},
551                                 name => $name,
552                             }) if ( $fio->{logLevel} >= 1 );
553                     $fio->{attrib}{$d}->set($f, {
554                                     type  => BPC_FTYPE_DELETED,
555                                     mode  => 0,
556                                     uid   => 0,
557                                     gid   => 0,
558                                     size  => 0,
559                                     mtime => 0,
560                                });
561                 }
562             }
563         }
564     }
565     if ( $fio->{attrib}{$d}->fileCount ) {
566         my $data = $fio->{attrib}{$d}->writeData;
567         my $dirM = $d;
568
569         $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
570                         if ( $dirM =~ m{(.*?)/(.*)}s );
571         my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
572         $fio->log("attribWrite(dir=$d) -> $fileName")
573                                 if ( $fio->{logLevel} >= 4 );
574         my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
575                                      length($data), $fio->{xfer}{compress});
576         $poolWrite->write(\$data);
577         $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
578                            length($data), 0);
579     }
580     delete($fio->{attrib}{$d});
581 }
582
583 sub processClose
584 {
585     my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
586     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
587
588     $fileName =~ s{^/+}{};
589     $fio->log(@$errs) if ( defined($errs) && @$errs );
590     if ( $doStats ) {
591         $fio->{stats}{TotalFileCnt}++;
592         $fio->{stats}{TotalFileSize} += $origSize;
593     }
594     if ( $exists ) {
595         if ( $doStats ) {
596             $fio->{stats}{ExistFileCnt}++;
597             $fio->{stats}{ExistFileSize}     += $origSize;
598             $fio->{stats}{ExistFileCompSize} += $outSize;
599         }
600     } elsif ( $outSize > 0 ) {
601         my $fh = $fio->{newFilesFH};
602         print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
603     }
604     return $exists && $origSize > 0;
605 }
606
607 sub statsGet
608 {
609     my($fio) = @_;
610
611     return $fio->{stats};
612 }
613
614 #
615 # Make a given directory.  Returns non-zero on error.
616 #
617 sub makePath
618 {
619     my($fio, $f) = @_;
620     my $name = $1 if ( $f->{name} =~ /(.*)/s );
621     my $path;
622
623     if ( $name eq "." ) {
624         $path = $fio->{outDirSh};
625     } else {
626         $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
627     }
628     $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
629     $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
630     $path = $1 if ( $path =~ /(.*)/s );
631     File::Path::mkpath($path, 0, 0777) if ( !-d $path );
632     return $fio->attribSet($f) if ( -d $path );
633     $fio->log("Can't create directory $path");
634     $fio->{stats}{errorCnt}++;
635     return -1;
636 }
637
638 #
639 # Make a special file.  Returns non-zero on error.
640 #
641 sub makeSpecial
642 {
643     my($fio, $f) = @_;
644     my $name = $1 if ( $f->{name} =~ /(.*)/s );
645     my $fNameM = $fio->{bpc}->fileNameMangle($name);
646     my $path = $fio->{outDirSh} . $fNameM;
647     my $attr = $fio->attribGet($f);
648     my $str = "";
649     my $type = $fio->mode2type($f);
650
651     $fio->log("makeSpecial($path, $type, $f->{mode})")
652                     if ( $fio->{logLevel} >= 5 );
653     if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
654         my($major, $minor, $fh, $fileData);
655
656         if ( defined($f->{rdev_major}) ) {
657             $major = $f->{rdev_major};
658             $minor = $f->{rdev_minor};
659         } else {
660             $major = $f->{rdev} >> 8;
661             $minor = $f->{rdev} & 0xff;
662         }
663         $str = "$major,$minor";
664     } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
665         $str = $f->{link};
666     } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
667         #
668         # this is a hardlink
669         #
670         if ( !defined($f->{hlink}) ) {
671             $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
672                     . " on a regular non-hardlink file");
673             return 1;
674         }
675         $str  = $f->{hlink};
676     }
677     #
678     # Now see if the file is different, or this is a full, in which
679     # case we create the new file.
680     #
681     my($fh, $fileData);
682     if ( $fio->{full}
683             || !defined($attr)
684             || $attr->{type}       != $type
685             || $attr->{mtime}      != $f->{mtime}
686             || $attr->{size}       != $f->{size}
687             || $attr->{uid}        != $f->{uid}
688             || $attr->{gid}        != $f->{gid}
689             || $attr->{mode}       != $f->{mode}
690             || $attr->{hlink_self} != $f->{hlink_self}
691             || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
692                                                       $attr->{compress}))
693             || $fh->read(\$fileData, length($str) + 1) != length($str)
694             || $fileData ne $str ) {
695         $fh->close if ( defined($fh) );
696         $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
697                                      length($str), $fio->{xfer}{compress});
698         $fh->write(\$str);
699         my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
700                                        length($str), 1);
701         $fio->logFileAction($exist ? "pool" : "create", $f)
702                             if ( $fio->{logLevel} >= 1 );
703         return $fio->attribSet($f);
704     } else {
705         $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
706     }
707     $fh->close if ( defined($fh) );
708 }
709
710 #
711 # Make a hardlink.  Returns non-zero on error.
712 # This actually gets called twice for each hardlink.
713 # Once as the file list is processed, and again at
714 # the end.  BackupPC does them as it goes (since it is
715 # just saving the hardlink info and not actually making
716 # hardlinks).
717 #
718 sub makeHardLink
719 {
720     my($fio, $f, $end) = @_;
721
722     return if ( $end );
723     return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
724 }
725
726 sub unlink
727 {
728     my($fio, $path) = @_;
729     
730     $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)"); 
731 }
732
733 #
734 # Default log handler
735 #
736 sub logHandler
737 {
738     my($str) = @_;
739
740     print(STDERR $str, "\n");
741 }
742
743 #
744 # Handle one or more log messages
745 #
746 sub log
747 {
748     my($fio, @logStr) = @_;
749
750     foreach my $str ( @logStr ) {
751         next if ( $str eq "" );
752         $fio->{logHandler}($str);
753     }
754 }
755
756 #
757 # Generate a log file message for a completed file
758 #
759 sub logFileAction
760 {
761     my($fio, $action, $f) = @_;
762     my $owner = "$f->{uid}/$f->{gid}";
763     my $type  = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
764                     [($f->{mode} & S_IFMT) >> 12];
765     my $name = $f->{name};
766
767     if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
768         $name .= " -> $f->{link}";
769     } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
770             && defined($f->{hlink}) && !$f->{hlink_self} ) {
771         $name .= " -> $f->{hlink}";
772     }
773     $name =~ s/\n/\\n/g;
774
775     $fio->log(sprintf("  %-6s %1s%4o %9s %11.0f %s",
776                                 $action,
777                                 $type,
778                                 $f->{mode} & 07777,
779                                 $owner,
780                                 $f->{size},
781                                 $name));
782 }
783
784 #
785 # If there is a partial and we are doing a full, we do an incremental
786 # against the partial and a full against the rest.  This subroutine
787 # is how we tell File::RsyncP which files to ignore attributes on
788 # (ie: against the partial dump we do consider the attributes, but
789 # otherwise we ignore attributes).
790 #
791 sub ignoreAttrOnFile
792 {
793     my($fio, $f) = @_;
794
795     return if ( !defined($fio->{partialNum}) );
796     my($attr, $isPartial) = $fio->attribGetWhere($f);
797     $fio->log("$f->{name}: just checking attributes from partial")
798                                 if ( $isPartial && $fio->{logLevel} >= 5 );
799     return !$isPartial;
800 }
801
802 #
803 # This is called by File::RsyncP when a file is skipped because the
804 # attributes match.
805 #
806 sub attrSkippedFile
807 {
808     my($fio, $f, $attr) = @_;
809
810     #
811     # Unless this is a partial, this is normal so ignore it.
812     #
813     return if ( !defined($fio->{partialNum}) );
814
815     $fio->log("$f->{name}: skipped in partial; adding link")
816                                     if ( $fio->{logLevel} >= 5 );
817     $fio->{rxLocalAttr} = $attr;
818     $fio->{rxFile} = $f;
819     $fio->{rxSize} = $attr->{size};
820     delete($fio->{rxInFd});
821     delete($fio->{rxOutFd});
822     delete($fio->{rxDigest});
823     delete($fio->{rxInData});
824     return $fio->fileDeltaRxDone();
825 }
826
827 #
828 # Start receive of file deltas for a particular file.
829 #
830 sub fileDeltaRxStart
831 {
832     my($fio, $f, $cnt, $size, $remainder) = @_;
833
834     $fio->{rxFile}      = $f;           # remote file attributes
835     $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
836     $fio->{rxBlkCnt}    = $cnt;         # how many blocks we will receive
837     $fio->{rxBlkSize}   = $size;        # block size
838     $fio->{rxRemainder} = $remainder;   # size of the last block
839     $fio->{rxMatchBlk}  = 0;            # current start of match
840     $fio->{rxMatchNext} = 0;            # current next block of match
841     $fio->{rxSize}      = 0;            # size of received file
842     my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
843     if ( $fio->{rxFile}{size} != $rxSize ) {
844         $fio->{rxMatchBlk} = undef;     # size different, so no file match
845         $fio->log("$fio->{rxFile}{name}: size doesn't match"
846                   . " ($fio->{rxFile}{size} vs $rxSize)")
847                         if ( $fio->{logLevel} >= 5 );
848     }
849     #
850     # If compression was off and now on, or on and now off, then
851     # don't do an exact match.
852     #
853     if ( defined($fio->{rxLocalAttr})
854             && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
855         $fio->{rxMatchBlk} = undef;     # compression changed, so no file match
856         $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
857               . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
858                     if ( $fio->{logLevel} >= 4 );
859     }
860     #
861     # If the local file is a hardlink then no match
862     #
863     if ( defined($fio->{rxLocalAttr})
864             && $fio->{rxLocalAttr}{type} == BPC_FTYPE_HARDLINK ) {
865         $fio->{rxMatchBlk} = undef;
866         $fio->log("$fio->{rxFile}{name}: no match on hardlinks")
867                                     if ( $fio->{logLevel} >= 4 );
868         my $fCopy;
869         # need to copy since hardlink attribGet overwrites the name
870         %{$fCopy} = %$f;
871         $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
872     } else {
873         delete($fio->{rxHLinkAttr});
874     }
875     delete($fio->{rxInFd});
876     delete($fio->{rxOutFd});
877     delete($fio->{rxDigest});
878     delete($fio->{rxInData});
879 }
880
881 #
882 # Process the next file delta for the current file.  Returns 0 if ok,
883 # -1 if not.  Must be called with either a block number, $blk, or new data,
884 # $newData, (not both) defined.
885 #
886 sub fileDeltaRxNext
887 {
888     my($fio, $blk, $newData) = @_;
889
890     if ( defined($blk) ) {
891         if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
892             #
893             # got the next block in order; just keep track.
894             #
895             $fio->{rxMatchNext}++;
896             return;
897         }
898     }
899     my $newDataLen = length($newData);
900     $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
901                     if ( $fio->{logLevel} >= 8 );
902     if ( !defined($fio->{rxOutFd}) ) {
903         #
904         # maybe the file has no changes
905         #
906         if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
907                 && !defined($blk) && !defined($newData) ) {
908             #$fio->log("$fio->{rxFile}{name}: file is unchanged");
909             #               if ( $fio->{logLevel} >= 8 );
910             return;
911         }
912
913         #
914         # need to open an output file where we will build the
915         # new version.
916         #
917         $fio->{rxFile}{name} =~ /(.*)/s;
918         my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
919         my $rxOutFile    = $fio->{outDir} . $rxOutFileRel;
920         $fio->{rxOutFd}  = BackupPC::PoolWrite->new($fio->{bpc},
921                                            $rxOutFile, $fio->{rxFile}{size},
922                                            $fio->{xfer}{compress});
923         $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
924                         if ( $fio->{logLevel} >= 9 );
925         $fio->{rxOutFile} = $rxOutFile;
926         $fio->{rxOutFileRel} = $rxOutFileRel;
927         $fio->{rxDigest} = File::RsyncP::Digest->new();
928         $fio->{rxDigest}->protocol($fio->{protocol_version});
929         $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
930     }
931     if ( defined($fio->{rxMatchBlk})
932                 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
933         #
934         # Need to copy the sequence of blocks that matched.  If the file
935         # is compressed we need to make a copy of the uncompressed file,
936         # since the compressed file is not seekable.  Future optimizations
937         # could include only creating an uncompressed copy if the matching
938         # blocks were not monotonic, and to only do this if there are
939         # matching blocks (eg, maybe the entire file is new).
940         #
941         my $attr = $fio->{rxLocalAttr};
942         my $fh;
943         if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
944             my $inPath = $attr->{fullPath};
945             $inPath = $fio->{rxHLinkAttr}{fullPath}
946                             if ( defined($fio->{rxHLinkAttr}) );
947             if ( $attr->{compress} ) {
948                 if ( !defined($fh = BackupPC::FileZIO->open(
949                                                    $inPath,
950                                                    0,
951                                                    $attr->{compress})) ) {
952                     $fio->log("Can't open $inPath");
953                     $fio->{stats}{errorCnt}++;
954                     return -1;
955                 }
956                 if ( $attr->{size} < 16 * 1024 * 1024 ) {
957                     #
958                     # Cache the entire old file if it is less than 16MB
959                     #
960                     my $data;
961                     $fio->{rxInData} = "";
962                     while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
963                         $fio->{rxInData} .= $data;
964                     }
965                     $fio->log("$attr->{fullPath}: cached all $attr->{size}"
966                             . " bytes")
967                                     if ( $fio->{logLevel} >= 9 );
968                 } else {
969                     #
970                     # Create and write a temporary output file
971                     #
972                     unlink("$fio->{outDirSh}RStmp")
973                                     if  ( -f "$fio->{outDirSh}RStmp" );
974                     if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
975                         my $data;
976                         my $byteCnt = 0;
977                         binmode(F);
978                         while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
979                             if ( syswrite(F, $data) != length($data) ) {
980                                 $fio->log(sprintf("Can't write len=%d to %s",
981                                       length($data) , "$fio->{outDirSh}RStmp"));
982                                 $fh->close;
983                                 $fio->{stats}{errorCnt}++;
984                                 return -1;
985                             }
986                             $byteCnt += length($data);
987                         }
988                         $fio->{rxInFd} = *F;
989                         $fio->{rxInName} = "$fio->{outDirSh}RStmp";
990                         sysseek($fio->{rxInFd}, 0, 0);
991                         $fio->log("$attr->{fullPath}: copied $byteCnt,"
992                                 . "$attr->{size} bytes to $fio->{rxInName}")
993                                         if ( $fio->{logLevel} >= 9 );
994                     } else {
995                         $fio->log("Unable to open $fio->{outDirSh}RStmp");
996                         $fh->close;
997                         $fio->{stats}{errorCnt}++;
998                         return -1;
999                     }
1000                 }
1001                 $fh->close;
1002             } else {
1003                 if ( open(F, "<", $inPath) ) {
1004                     binmode(F);
1005                     $fio->{rxInFd} = *F;
1006                     $fio->{rxInName} = $attr->{fullPath};
1007                 } else {
1008                     $fio->log("Unable to open $inPath");
1009                     $fio->{stats}{errorCnt}++;
1010                     return -1;
1011                 }
1012             }
1013         }
1014         my $lastBlk = $fio->{rxMatchNext} - 1;
1015         $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1016                   . "$lastBlk")
1017                         if ( $fio->{logLevel} >= 9 );
1018         my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
1019         if ( defined($fio->{rxInFd})
1020                         && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
1021             $fio->log("Unable to seek $fio->{rxInName} to $seekPosn");
1022             $fio->{stats}{errorCnt}++;
1023             return -1;
1024         }
1025         my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
1026         my($thisCnt, $len, $data);
1027         for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
1028             $thisCnt = $cnt - $i;
1029             $thisCnt = 512 if ( $thisCnt > 512 );
1030             if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
1031                 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
1032             } else {
1033                 $len = $thisCnt * $fio->{rxBlkSize};
1034             }
1035             if ( defined($fio->{rxInData}) ) {
1036                 $data = substr($fio->{rxInData}, $seekPosn, $len);
1037                 $seekPosn += $len;
1038             } else {
1039                 my $got = sysread($fio->{rxInFd}, $data, $len);
1040                 if ( $got != $len ) {
1041                     my $inFileSize = -s $fio->{rxInName};
1042                     $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1043                             . " got=$got, seekPosn=$seekPosn"
1044                             . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1045                             . ",$attr->{size})");
1046                     $fio->{stats}{errorCnt}++;
1047                     return -1;
1048                 }
1049                 $seekPosn += $len;
1050             }
1051             $fio->{rxOutFd}->write(\$data);
1052             $fio->{rxDigest}->add($data);
1053             $fio->{rxSize} += length($data);
1054         }
1055         $fio->{rxMatchBlk} = undef;
1056     }
1057     if ( defined($blk) ) {
1058         #
1059         # Remember the new block number
1060         #
1061         $fio->{rxMatchBlk}  = $blk;
1062         $fio->{rxMatchNext} = $blk + 1;
1063     }
1064     if ( defined($newData) ) {
1065         #
1066         # Write the new chunk
1067         #
1068         my $len = length($newData);
1069         $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1070                         if ( $fio->{logLevel} >= 9 );
1071         $fio->{rxOutFd}->write(\$newData);
1072         $fio->{rxDigest}->add($newData);
1073         $fio->{rxSize} += length($newData);
1074     }
1075 }
1076
1077 #
1078 # Finish up the current receive file.  Returns undef if ok, -1 if not.
1079 # Returns 1 if the md4 digest doesn't match.
1080 #
1081 sub fileDeltaRxDone
1082 {
1083     my($fio, $md4, $phase) = @_;
1084     my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1085     my $ret;
1086
1087     close($fio->{rxInFd})  if ( defined($fio->{rxInFd}) );
1088     unlink("$fio->{outDirSh}RStmp") if  ( -f "$fio->{outDirSh}RStmp" );
1089     $fio->{phase} = $phase;
1090
1091     #
1092     # Check the final md4 digest
1093     #
1094     if ( defined($md4) ) {
1095         my $newDigest;
1096         if ( !defined($fio->{rxDigest}) ) {
1097             #
1098             # File was exact match, but we still need to verify the
1099             # MD4 checksum.  Compute the md4 digest (or fetch the
1100             # cached one.)
1101             #
1102             if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1103                 #
1104                 # block size doesn't matter: we're only going to
1105                 # fetch the md4 file digest, not the block digests.
1106                 #
1107                 my($err, $csum, $blkSize)
1108                          = BackupPC::Xfer::RsyncDigest->digestStart(
1109                                  $attr->{fullPath}, $attr->{size},
1110                                  0, 2048, $fio->{checksumSeed}, 1,
1111                                  $attr->{compress}, 1,
1112                                  $fio->{protocol_version});
1113                 if ( $err ) {
1114                     $fio->log("Can't open $attr->{fullPath} for MD4"
1115                             . " check (err=$err, $name)");
1116                     $fio->{stats}{errorCnt}++;
1117                 } else {
1118                     if ( $fio->{logLevel} >= 5 ) {
1119                         my($isCached, $invalid) = $csum->isCached;
1120                         $fio->log("MD4 $attr->{fullPath} cache = $isCached,"
1121                                 . " invalid = $invalid");
1122                     }
1123                     $newDigest = $csum->digestEnd;
1124                 }
1125                 $fio->{rxSize} = $attr->{size};
1126             } else {
1127                 #
1128                 # Empty file; just create an empty file digest
1129                 #
1130                 $fio->{rxDigest} = File::RsyncP::Digest->new();
1131                 $fio->{rxDigest}->protocol($fio->{protocol_version});
1132                 $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
1133                 $newDigest = $fio->{rxDigest}->digest;
1134             }
1135             $fio->log("$name got exact match") if ( $fio->{logLevel} >= 5 );
1136         } else {
1137             $newDigest = $fio->{rxDigest}->digest;
1138         }
1139         if ( $fio->{logLevel} >= 3 ) {
1140             my $md4Str = unpack("H*", $md4);
1141             my $newStr = unpack("H*", $newDigest);
1142             $fio->log("$name got digests $md4Str vs $newStr")
1143         }
1144         if ( $md4 ne $newDigest ) {
1145             if ( $phase > 0 ) {
1146                 $fio->log("$name: fatal error: md4 doesn't match on retry;"
1147                         . " file removed");
1148             } else {
1149                 $fio->log("$name: md4 doesn't match: will retry in phase 1;"
1150                         . " file removed");
1151             }
1152             $fio->{stats}{errorCnt}++;
1153             if ( defined($fio->{rxOutFd}) ) {
1154                 $fio->{rxOutFd}->close;
1155                 unlink($fio->{rxOutFile});
1156             }
1157             delete($fio->{rxFile});
1158             delete($fio->{rxOutFile});
1159             return 1;
1160         }
1161     }
1162
1163     #
1164     # One special case is an empty file: if the file size is
1165     # zero we need to open the output file to create it.
1166     #
1167     if ( $fio->{rxSize} == 0 ) {
1168         my $rxOutFileRel = "$fio->{shareM}/"
1169                          . $fio->{bpc}->fileNameMangle($name);
1170         my $rxOutFile    = $fio->{outDir} . $rxOutFileRel;
1171         $fio->{rxOutFd}  = BackupPC::PoolWrite->new($fio->{bpc},
1172                                            $rxOutFile, $fio->{rxSize},
1173                                            $fio->{xfer}{compress});
1174     }
1175     if ( !defined($fio->{rxOutFd}) ) {
1176         #
1177         # No output file, meaning original was an exact match.
1178         #
1179         $fio->log("$name: nothing to do")
1180                         if ( $fio->{logLevel} >= 5 );
1181         my $attr = $fio->{rxLocalAttr};
1182         my $f = $fio->{rxFile};
1183         $fio->logFileAction("same", $f) if ( $fio->{logLevel} >= 1 );
1184         if ( $fio->{full}
1185                 || $attr->{type}       != $f->{type}
1186                 || $attr->{mtime}      != $f->{mtime}
1187                 || $attr->{size}       != $f->{size}
1188                 || $attr->{uid}        != $f->{uid}
1189                 || $attr->{gid}        != $f->{gid}
1190                 || $attr->{mode}       != $f->{mode}
1191                 || $attr->{hlink_self} != $f->{hlink_self} ) {
1192             #
1193             # In the full case, or if the attributes are different,
1194             # we need to make a link from the previous file and
1195             # set the attributes.
1196             #
1197             my $rxOutFile = $fio->{outDirSh}
1198                             . $fio->{bpc}->fileNameMangle($name);
1199             my($exists, $digest, $origSize, $outSize, $errs)
1200                                 = BackupPC::PoolWrite::LinkOrCopy(
1201                                       $fio->{bpc},
1202                                       $attr->{fullPath},
1203                                       $attr->{compress},
1204                                       $rxOutFile,
1205                                       $fio->{xfer}{compress});
1206             #
1207             # Cumulate the stats
1208             #
1209             $fio->{stats}{TotalFileCnt}++;
1210             $fio->{stats}{TotalFileSize} += $fio->{rxSize};
1211             $fio->{stats}{ExistFileCnt}++;
1212             $fio->{stats}{ExistFileSize} += $fio->{rxSize};
1213             $fio->{stats}{ExistFileCompSize} += -s $rxOutFile;
1214             $fio->{rxFile}{size} = $fio->{rxSize};
1215             $ret = $fio->attribSet($fio->{rxFile});
1216             $fio->log(@$errs) if ( defined($errs) && @$errs );
1217
1218             if ( !$exists && $outSize > 0 ) {
1219                 #
1220                 # the hard link failed, most likely because the target
1221                 # file has too many links.  We have copied the file
1222                 # instead, so add this to the new file list.
1223                 #
1224                 my $rxOutFileRel = "$fio->{shareM}/"
1225                                  . $fio->{bpc}->fileNameMangle($name);
1226                 $rxOutFileRel =~ s{^/+}{};
1227                 my $fh = $fio->{newFilesFH};
1228                 print($fh "$digest $origSize $rxOutFileRel\n")
1229                                                 if ( defined($fh) );
1230             }
1231         }
1232     } else {
1233         my $exist = $fio->processClose($fio->{rxOutFd},
1234                                        $fio->{rxOutFileRel},
1235                                        $fio->{rxSize}, 1);
1236         $fio->logFileAction($exist ? "pool" : "create", $fio->{rxFile})
1237                             if ( $fio->{logLevel} >= 1 );
1238         $fio->{rxFile}{size} = $fio->{rxSize};
1239         $ret = $fio->attribSet($fio->{rxFile});
1240     }
1241     delete($fio->{rxDigest});
1242     delete($fio->{rxInData});
1243     delete($fio->{rxFile});
1244     delete($fio->{rxOutFile});
1245     return $ret;
1246 }
1247
1248 #
1249 # Callback function for BackupPC::View->find.  Note the order of the
1250 # first two arguments.
1251 #
1252 sub fileListEltSend
1253 {
1254     my($a, $fio, $fList, $outputFunc) = @_;
1255     my $name = $a->{relPath};
1256     my $n = $name;
1257     my $type = $a->{type};
1258     my $extraAttribs = {};
1259
1260     if ( $a->{mode} & S_HLINK_TARGET ) {
1261         $a->{hlink_self} = 1;
1262         $a->{mode} &= ~S_HLINK_TARGET;
1263     }
1264     $n =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
1265     $fio->log("Sending $name (remote=$n) type = $type") if ( $fio->{logLevel} >= 1 );
1266     if ( $type == BPC_FTYPE_CHARDEV
1267             || $type == BPC_FTYPE_BLOCKDEV
1268             || $type == BPC_FTYPE_SYMLINK ) {
1269         my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1270         my($str, $rdSize);
1271         if ( defined($fh) ) {
1272             $rdSize = $fh->read(\$str, $a->{size} + 1024);
1273             if ( $type == BPC_FTYPE_SYMLINK ) {
1274                 #
1275                 # Reconstruct symbolic link
1276                 #
1277                 $extraAttribs = { link => $str };
1278                 if ( $rdSize != $a->{size} ) {
1279                     # ERROR
1280                     $fio->log("$name: can't read exactly $a->{size} bytes");
1281                     $fio->{stats}{errorCnt}++;
1282                 }
1283             } elsif ( $str =~ /(\d*),(\d*)/ ) {
1284                 #
1285                 # Reconstruct char or block special major/minor device num
1286                 #
1287                 # Note: char/block devices have $a->{size} = 0, so we
1288                 # can't do an error check on $rdSize.
1289                 #
1290                 $extraAttribs = {
1291                     rdev       => $1 * 256 + $2,
1292                     rdev_major => $1,
1293                     rdev_minor => $2,
1294                 };
1295             } else {
1296                 $fio->log("$name: unexpected special file contents $str");
1297                 $fio->{stats}{errorCnt}++;
1298             }
1299             $fh->close;
1300         } else {
1301             # ERROR
1302             $fio->log("$name: can't open");
1303             $fio->{stats}{errorCnt}++;
1304         }
1305     } elsif ( $fio->{preserve_hard_links}
1306             && ($type == BPC_FTYPE_HARDLINK || $type == BPC_FTYPE_FILE)
1307             && ($type == BPC_FTYPE_HARDLINK
1308                     || $fio->{protocol_version} < 27
1309                     || $a->{hlink_self}) ) {
1310         #
1311         # Fill in fake inode information so that the remote rsync
1312         # can correctly create hardlinks.
1313         #
1314         $name =~ s/^\.?\/+//;
1315         my($target, $inode);
1316
1317         if ( $type == BPC_FTYPE_HARDLINK ) {
1318             my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0,
1319                                              $a->{compress});
1320             if ( defined($fh) ) {
1321                 $fh->read(\$target,  65536);
1322                 $fh->close;
1323                 $target =~ s/^\.?\/+//;
1324                 if ( defined($fio->{hlinkFile2Num}{$target}) ) {
1325                     $inode = $fio->{hlinkFile2Num}{$target};
1326                 } else {
1327                     $inode = $fio->{fileListCnt};
1328                     $fio->{hlinkFile2Num}{$target} = $inode;
1329                 }
1330             } else {
1331                 $fio->log("$a->{fullPath}: can't open for hardlink");
1332                 $fio->{stats}{errorCnt}++;
1333             }
1334         } elsif ( $a->{hlink_self} ) {
1335             if ( defined($fio->{hlinkFile2Num}{$name}) ) {
1336                 $inode = $fio->{hlinkFile2Num}{$name};
1337             } else {
1338                 $inode = $fio->{fileListCnt};
1339                 $fio->{hlinkFile2Num}{$name} = $inode;
1340             }
1341         }
1342         $inode = $fio->{fileListCnt} if ( !defined($inode) );
1343         $fio->log("$name: setting inode to $inode");
1344         $extraAttribs = {
1345             %$extraAttribs,
1346             dev   => 0,
1347             inode => $inode,
1348         };
1349     }
1350     my $f = {
1351         name  => $n,
1352         mode  => $a->{mode} & ~S_HLINK_TARGET,
1353         uid   => $a->{uid},
1354         gid   => $a->{gid},
1355         mtime => $a->{mtime},
1356         size  => $a->{size},
1357         %$extraAttribs,
1358     };
1359     my $logName = $f->{name};
1360     from_to($f->{name}, "utf8", $fio->{clientCharset})
1361                             if ( $fio->{clientCharset} ne "" );
1362     $fList->encode($f);
1363
1364     $logName = "$fio->{xfer}{pathHdrDest}/$logName";
1365     $logName =~ s{//+}{/}g;
1366     $f->{name} = $logName;
1367     $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1368
1369     &$outputFunc($fList->encodeData);
1370     #
1371     # Cumulate stats
1372     #
1373     $fio->{fileListCnt}++;
1374     if ( $type != BPC_FTYPE_DIR ) {
1375         $fio->{stats}{TotalFileCnt}++;
1376         $fio->{stats}{TotalFileSize} += $a->{size};
1377     }
1378 }
1379
1380 sub fileListSend
1381 {
1382     my($fio, $flist, $outputFunc) = @_;
1383
1384     #
1385     # Populate the file list with the files requested by the user.
1386     # Since some might be directories so we call BackupPC::View::find.
1387     #
1388     $fio->log("fileListSend: sending file list: "
1389              . join(" ", @{$fio->{fileList}})) if ( $fio->{logLevel} >= 4 );
1390     $fio->{fileListCnt} = 0;
1391     $fio->{hlinkFile2Num} = {};
1392     foreach my $name ( @{$fio->{fileList}} ) {
1393         $fio->{view}->find($fio->{xfer}{bkupSrcNum},
1394                            $fio->{xfer}{bkupSrcShare},
1395                            $name, 1,
1396                            \&fileListEltSend, $fio, $flist, $outputFunc);
1397     }
1398 }
1399
1400 sub finish
1401 {
1402     my($fio, $isChild) = @_;
1403
1404     #
1405     # If we are aborting early, remove the last file since
1406     # it was not complete
1407     #
1408     if ( $isChild && defined($fio->{rxFile}) ) {
1409         unlink("$fio->{outDirSh}RStmp") if  ( -f "$fio->{outDirSh}RStmp" );
1410         if ( defined($fio->{rxFile}) ) {
1411             unlink($fio->{rxOutFile});
1412             $fio->log("finish: removing in-process file $fio->{rxFile}{name}");
1413         }
1414     }
1415
1416     #
1417     # Flush the attributes if this is the child
1418     #
1419     $fio->attribWrite(undef) if ( $isChild );
1420 }
1421
1422 #sub is_tainted
1423 #{
1424 #    return ! eval {
1425 #        join('',@_), kill 0;
1426 #        1;
1427 #    };
1428 #}
1429
1430 1;