a8b69b91269429b66e983602a8e604a6667dfab8
[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         my($isCached, $isInvalid) = $d->isCached;
165         if ( $fio->{logLevel} >= 5 ) {
166             $fio->log("$attr->{fullPath} verify; cached = $isCached,"
167                     . " invalid = $isInvalid, phase = $phase");
168         }
169         if ( $isCached || $isInvalid ) {
170             my $ret = BackupPC::Xfer::RsyncDigest->digestAdd(
171                             $attr->{fullPath}, $blkSize,
172                             $fio->{checksumSeed}, 1        # verify
173                         );
174             if ( $ret != 1 ) {
175                 $fio->log("Bad cached digest for $attr->{fullPath} ($ret);"
176                         . " fixed");
177                 $fio->{stats}{errorCnt}++;
178             } else {
179                 $fio->log("$f->{name}: verified cached digest")
180                                     if ( $fio->{logLevel} >= 2 );
181             }
182         }
183         $d->digestEnd;
184     }
185     (my $err, $fio->{csum}, my $blkSize)
186          = BackupPC::Xfer::RsyncDigest->digestStart($attr->{fullPath},
187                          $attr->{size}, 0, $defBlkSize, $fio->{checksumSeed},
188                          $needMD4, $attr->{compress}, 1);
189     if ( $fio->{logLevel} >= 5 ) {
190         my($isCached, $invalid) = $fio->{csum}->isCached;
191         $fio->log("$attr->{fullPath} cache = $isCached,"
192                 . " invalid = $invalid, phase = $phase");
193     }
194     if ( $err ) {
195         $fio->log("Can't get rsync digests from $attr->{fullPath}"
196                 . " (err=$err, name=$f->{name})");
197         $fio->{stats}{errorCnt}++;
198         return -1;
199     }
200     return $blkSize;
201 }
202
203 sub csumGet
204 {
205     my($fio, $num, $csumLen, $blockSize) = @_;
206     my($fileData);
207
208     $num     ||= 100;
209     $csumLen ||= 16;
210     return if ( !defined($fio->{csum}) );
211     return $fio->{csum}->digestGet($num, $csumLen);
212 }
213
214 sub csumEnd
215 {
216     my($fio) = @_;
217
218     return if ( !defined($fio->{csum}) );
219     return $fio->{csum}->digestEnd();
220 }
221
222 sub readStart
223 {
224     my($fio, $f) = @_;
225
226     my $attr = $fio->attribGet($f, 1);
227     $fio->{file} = $f;
228     $fio->readEnd if ( defined($fio->{fh}) );
229     if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
230                                            0,
231                                            $attr->{compress})) ) {
232         $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
233         $fio->{stats}{errorCnt}++;
234         return;
235     }
236     $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
237 }
238
239 sub read
240 {
241     my($fio, $num) = @_;
242     my $fileData;
243
244     $num ||= 32768;
245     return if ( !defined($fio->{fh}) );
246     if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
247         return $fio->readEnd;
248     }
249     $fio->log(sprintf("read returns %d bytes", length($fileData)))
250                                 if ( $fio->{logLevel} >= 8 );
251     return \$fileData;
252 }
253
254 sub readEnd
255 {
256     my($fio) = @_;
257
258     return if ( !defined($fio->{fh}) );
259     $fio->{fh}->close;
260     $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
261     delete($fio->{fh});
262     return;
263 }
264
265 sub checksumSeed
266 {
267     my($fio, $checksumSeed) = @_;
268
269     $fio->{checksumSeed} = $checksumSeed;
270     $fio->log("Checksum caching enabled (checksumSeed = $checksumSeed)")
271         if ( $fio->{logLevel} >= 1 && $checksumSeed == RSYNC_CSUMSEED_CACHE );
272     $fio->log("Checksum seed is $checksumSeed")
273         if ( $fio->{logLevel} >= 2 && $checksumSeed != RSYNC_CSUMSEED_CACHE );
274 }
275
276 sub dirs
277 {
278     my($fio, $localDir, $remoteDir) = @_;
279
280     $fio->{localDir}  = $localDir;
281     $fio->{remoteDir} = $remoteDir;
282 }
283
284 sub viewCacheDir
285 {
286     my($fio, $share, $dir) = @_;
287     my $shareM;
288
289     #$fio->log("viewCacheDir($share, $dir)");
290     if ( !defined($share) ) {
291         $share  = $fio->{share};
292         $shareM = $fio->{shareM};
293     } else {
294         $shareM = $fio->{bpc}->fileNameEltMangle($share);
295     }
296     $shareM = "$shareM/$dir" if ( $dir ne "" );
297     return if ( defined($fio->{viewCache}{$shareM}) );
298     #
299     # purge old cache entries (ie: those that don't match the
300     # first part of $dir).
301     #
302     foreach my $d ( keys(%{$fio->{viewCache}}) ) {
303         delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
304     }
305     #
306     # fetch new directory attributes
307     #
308     $fio->{viewCache}{$shareM}
309                 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
310     #
311     # also cache partial backup attrib data too
312     #
313     if ( defined($fio->{partialNum}) ) {
314         foreach my $d ( keys(%{$fio->{partialCache}}) ) {
315             delete($fio->{partialCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
316         }
317         $fio->{partialCache}{$shareM}
318                     = $fio->{view}->dirAttrib($fio->{partialNum}, $share, $dir);
319     }
320 }
321
322 sub attribGetWhere
323 {
324     my($fio, $f, $noCache) = @_;
325     my($dir, $fname, $share, $shareM, $partial, $attr);
326
327     $fname = $f->{name};
328     $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
329                        if ( defined($fio->{xfer}{pathHdrSrc}) );
330     $fname =~ s{//+}{/}g;
331     if ( $fname =~ m{(.*)/(.*)}s ) {
332         $shareM = $fio->{shareM};
333         $dir = $1;
334         $fname = $2;
335     } elsif ( $fname ne "." ) {
336         $shareM = $fio->{shareM};
337         $dir = "";
338     } else {
339         $share = "";
340         $shareM = "";
341         $dir = "";
342         $fname = $fio->{share};
343     }
344     $shareM .= "/$dir" if ( $dir ne "" );
345
346     if ( $noCache ) {
347         $share  = $fio->{share} if ( !defined($share) );
348         my $dirAttr = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
349         $attr = $dirAttr->{$fname};
350     } else {
351         $fio->viewCacheDir($share, $dir);
352         if ( defined($attr = $fio->{viewCache}{$shareM}{$fname}) ) {
353             $partial = 0;
354         } elsif ( defined($attr = $fio->{partialCache}{$shareM}{$fname}) ) {
355             $partial = 1;
356         } else {
357             return;
358         }
359         if ( $attr->{mode} & S_HLINK_TARGET ) {
360             $attr->{hlink_self} = 1;
361             $attr->{mode} &= ~S_HLINK_TARGET;
362         }
363     }
364     return ($attr, $partial);
365 }
366
367 sub attribGet
368 {
369     my($fio, $f, $doHardLink) = @_;
370
371     my($attr) = $fio->attribGetWhere($f);
372     if ( $doHardLink && $attr->{type} == BPC_FTYPE_HARDLINK ) {
373         $fio->log("$attr->{fullPath}: opening for hardlink read"
374                 . " (name = $f->{name})") if ( $fio->{logLevel} >= 4 );
375         my $fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
376                                          $attr->{compress});
377         my $target;
378         if ( defined($fh) ) {
379             $fh->read(\$target,  65536);
380             $fh->close;
381             $target =~ s/^\.?\/+//;
382         } else {
383             $fio->log("$attr->{fullPath}: can't open for hardlink read");
384             $fio->{stats}{errorCnt}++;
385             $attr->{type} = BPC_FTYPE_FILE;
386             return $attr;
387         }
388         $target = "/$target" if ( $target !~ /^\// );
389         $fio->log("$attr->{fullPath}: redirecting to $target (will trim "
390                 . "$fio->{xfer}{pathHdrSrc})") if ( $fio->{logLevel} >= 4 );
391         $target =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
392         $target =~ s{^/+}{};
393         #
394         # Note: overwrites name to point to real file
395         #
396         $f->{name} = $target;
397         ($attr) = $fio->attribGetWhere($f, 1);
398         $fio->log(" ... now got $attr->{fullPath}")
399                             if ( $fio->{logLevel} >= 4 );
400     }
401     return $attr;
402 }
403
404 sub mode2type
405 {
406     my($fio, $f) = @_;
407     my $mode = $f->{mode};
408
409     if ( ($mode & S_IFMT) == S_IFREG ) {
410         if ( defined($f->{hlink}) && !$f->{hlink_self} ) {
411             return BPC_FTYPE_HARDLINK;
412         } else {
413             return BPC_FTYPE_FILE;
414         }
415     } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
416         return BPC_FTYPE_DIR;
417     } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
418         return BPC_FTYPE_SYMLINK;
419     } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
420         return BPC_FTYPE_CHARDEV;
421     } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
422         return BPC_FTYPE_BLOCKDEV;
423     } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
424         return BPC_FTYPE_FIFO;
425     } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
426         return BPC_FTYPE_SOCKET;
427     } else {
428         return BPC_FTYPE_UNKNOWN;
429     }
430 }
431
432 #
433 # Set the attributes for a file.  Returns non-zero on error.
434 #
435 sub attribSet
436 {
437     my($fio, $f, $placeHolder) = @_;
438     my($dir, $file);
439
440     if ( $f->{name} =~ m{(.*)/(.*)}s ) {
441         $file = $2;
442         $dir  = "$fio->{shareM}/" . $1;
443     } elsif ( $f->{name} eq "." ) {
444         $dir  = "";
445         $file = $fio->{share};
446     } else {
447         $dir  = $fio->{shareM};
448         $file = $f->{name};
449     }
450
451     if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
452         #
453         # Flush any directories that don't match the first part
454         # of the new directory
455         #
456         foreach my $d ( keys(%{$fio->{attrib}}) ) {
457             next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
458             $fio->attribWrite($d);
459         }
460         $fio->{attribLastDir} = $dir;
461     }
462     if ( !exists($fio->{attrib}{$dir}) ) {
463         $fio->{attrib}{$dir} = BackupPC::Attrib->new({
464                                      compress => $fio->{xfer}{compress},
465                                 });
466         my $path = $fio->{outDir} . $dir;
467         if ( -f $fio->{attrib}{$dir}->fileName($path)
468                     && !$fio->{attrib}{$dir}->read($path) ) {
469             $fio->log(sprintf("Unable to read attribute file %s",
470                             $fio->{attrib}{$dir}->fileName($path)));
471         }
472     }
473     $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
474
475     my $mode = $f->{mode};
476
477     $mode |= S_HLINK_TARGET if ( $f->{hlink_self} );
478     $fio->{attrib}{$dir}->set($file, {
479                             type  => $fio->mode2type($f),
480                             mode  => $mode,
481                             uid   => $f->{uid},
482                             gid   => $f->{gid},
483                             size  => $placeHolder ? -1 : $f->{size},
484                             mtime => $f->{mtime},
485                        });
486     return;
487 }
488
489 sub attribWrite
490 {
491     my($fio, $d) = @_;
492     my($poolWrite);
493
494     #
495     # Don't write attributes on 2nd phase - they're already
496     # taken care of during the first phase.
497     #
498     return if ( $fio->{phase} > 0 );
499     if ( !defined($d) ) {
500         #
501         # flush all entries (in reverse order)
502         #
503         foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
504             $fio->attribWrite($d);
505         }
506         return;
507     }
508     return if ( !defined($fio->{attrib}{$d}) );
509     #
510     # Set deleted files in the attributes.  Any file in the view
511     # that doesn't have attributes is flagged as deleted for
512     # incremental dumps.  All files sent by rsync have attributes
513     # temporarily set so we can do deletion detection.  We also
514     # prune these temporary attributes.
515     #
516     if ( $d ne "" ) {
517         my $dir;
518         my $share;
519
520         $dir = $1 if ( $d =~ m{.+?/(.*)}s );
521         $fio->viewCacheDir(undef, $dir);
522         ##print("attribWrite $d,$dir\n");
523         ##$Data::Dumper::Indent = 1;
524         ##$fio->log("attribWrite $d,$dir");
525         ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
526         ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
527         ##print "viewCache = ", Dumper($fio->{attrib});
528         ##print "attrib = ", Dumper($fio->{attrib});
529         if ( defined($fio->{viewCache}{$d}) ) {
530             foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
531                 my $name = $f;
532                 $name = "$1/$name" if ( $d =~ m{.*?/(.*)}s );
533                 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
534                     #
535                     # delete temporary attributes (skipped files)
536                     #
537                     if ( $a->{size} < 0 ) {
538                         $fio->{attrib}{$d}->set($f, undef);
539                         $fio->logFileAction("skip", {
540                                     %{$fio->{viewCache}{$d}{$f}},
541                                     name => $name,
542                                 }) if ( $fio->{logLevel} >= 2
543                                       && $a->{type} == BPC_FTYPE_FILE );
544                     }
545                 } elsif ( !$fio->{full} ) {
546                     ##print("Delete file $f\n");
547                     $fio->logFileAction("delete", {
548                                 %{$fio->{viewCache}{$d}{$f}},
549                                 name => $name,
550                             }) if ( $fio->{logLevel} >= 1 );
551                     $fio->{attrib}{$d}->set($f, {
552                                     type  => BPC_FTYPE_DELETED,
553                                     mode  => 0,
554                                     uid   => 0,
555                                     gid   => 0,
556                                     size  => 0,
557                                     mtime => 0,
558                                });
559                 }
560             }
561         }
562     }
563     if ( $fio->{attrib}{$d}->fileCount ) {
564         my $data = $fio->{attrib}{$d}->writeData;
565         my $dirM = $d;
566
567         $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
568                         if ( $dirM =~ m{(.*?)/(.*)}s );
569         my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
570         $fio->log("attribWrite(dir=$d) -> $fileName")
571                                 if ( $fio->{logLevel} >= 4 );
572         my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
573                                      length($data), $fio->{xfer}{compress});
574         $poolWrite->write(\$data);
575         $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
576                            length($data), 0);
577     }
578     delete($fio->{attrib}{$d});
579 }
580
581 sub processClose
582 {
583     my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
584     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
585
586     $fileName =~ s{^/+}{};
587     $fio->log(@$errs) if ( defined($errs) && @$errs );
588     if ( $doStats ) {
589         $fio->{stats}{TotalFileCnt}++;
590         $fio->{stats}{TotalFileSize} += $origSize;
591     }
592     if ( $exists ) {
593         if ( $doStats ) {
594             $fio->{stats}{ExistFileCnt}++;
595             $fio->{stats}{ExistFileSize}     += $origSize;
596             $fio->{stats}{ExistFileCompSize} += $outSize;
597         }
598     } elsif ( $outSize > 0 ) {
599         my $fh = $fio->{newFilesFH};
600         print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
601     }
602     return $exists && $origSize > 0;
603 }
604
605 sub statsGet
606 {
607     my($fio) = @_;
608
609     return $fio->{stats};
610 }
611
612 #
613 # Make a given directory.  Returns non-zero on error.
614 #
615 sub makePath
616 {
617     my($fio, $f) = @_;
618     my $name = $1 if ( $f->{name} =~ /(.*)/s );
619     my $path;
620
621     if ( $name eq "." ) {
622         $path = $fio->{outDirSh};
623     } else {
624         $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
625     }
626     $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
627     $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
628     $path = $1 if ( $path =~ /(.*)/s );
629     File::Path::mkpath($path, 0, 0777) if ( !-d $path );
630     return $fio->attribSet($f) if ( -d $path );
631     $fio->log("Can't create directory $path");
632     $fio->{stats}{errorCnt}++;
633     return -1;
634 }
635
636 #
637 # Make a special file.  Returns non-zero on error.
638 #
639 sub makeSpecial
640 {
641     my($fio, $f) = @_;
642     my $name = $1 if ( $f->{name} =~ /(.*)/s );
643     my $fNameM = $fio->{bpc}->fileNameMangle($name);
644     my $path = $fio->{outDirSh} . $fNameM;
645     my $attr = $fio->attribGet($f);
646     my $str = "";
647     my $type = $fio->mode2type($f);
648
649     $fio->log("makeSpecial($path, $type, $f->{mode})")
650                     if ( $fio->{logLevel} >= 5 );
651     if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
652         my($major, $minor, $fh, $fileData);
653
654         if ( defined($f->{rdev_major}) ) {
655             $major = $f->{rdev_major};
656             $minor = $f->{rdev_minor};
657         } else {
658             $major = $f->{rdev} >> 8;
659             $minor = $f->{rdev} & 0xff;
660         }
661         $str = "$major,$minor";
662     } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
663         $str = $f->{link};
664     } elsif ( ($f->{mode} & S_IFMT) == S_IFREG ) {
665         #
666         # this is a hardlink
667         #
668         if ( !defined($f->{hlink}) ) {
669             $fio->log("Error: makeSpecial($path, $type, $f->{mode}) called"
670                     . " on a regular non-hardlink file");
671             return 1;
672         }
673         $str  = $f->{hlink};
674     }
675     #
676     # Now see if the file is different, or this is a full, in which
677     # case we create the new file.
678     #
679     my($fh, $fileData);
680     if ( $fio->{full}
681             || !defined($attr)
682             || $attr->{type}       != $type
683             || $attr->{mtime}      != $f->{mtime}
684             || $attr->{size}       != $f->{size}
685             || $attr->{uid}        != $f->{uid}
686             || $attr->{gid}        != $f->{gid}
687             || $attr->{mode}       != $f->{mode}
688             || $attr->{hlink_self} != $f->{hlink_self}
689             || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
690                                                       $attr->{compress}))
691             || $fh->read(\$fileData, length($str) + 1) != length($str)
692             || $fileData ne $str ) {
693         $fh->close if ( defined($fh) );
694         $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
695                                      length($str), $fio->{xfer}{compress});
696         $fh->write(\$str);
697         my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
698                                        length($str), 1);
699         $fio->logFileAction($exist ? "pool" : "create", $f)
700                             if ( $fio->{logLevel} >= 1 );
701         return $fio->attribSet($f);
702     } else {
703         $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
704     }
705     $fh->close if ( defined($fh) );
706 }
707
708 #
709 # Make a hardlink.  Returns non-zero on error.
710 # This actually gets called twice for each hardlink.
711 # Once as the file list is processed, and again at
712 # the end.  BackupPC does them as it goes (since it is
713 # just saving the hardlink info and not actually making
714 # hardlinks).
715 #
716 sub makeHardLink
717 {
718     my($fio, $f, $end) = @_;
719
720     return if ( $end );
721     return $fio->makeSpecial($f) if ( !$f->{hlink_self} );
722 }
723
724 sub unlink
725 {
726     my($fio, $path) = @_;
727     
728     $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)"); 
729 }
730
731 #
732 # Default log handler
733 #
734 sub logHandler
735 {
736     my($str) = @_;
737
738     print(STDERR $str, "\n");
739 }
740
741 #
742 # Handle one or more log messages
743 #
744 sub log
745 {
746     my($fio, @logStr) = @_;
747
748     foreach my $str ( @logStr ) {
749         next if ( $str eq "" );
750         $fio->{logHandler}($str);
751     }
752 }
753
754 #
755 # Generate a log file message for a completed file
756 #
757 sub logFileAction
758 {
759     my($fio, $action, $f) = @_;
760     my $owner = "$f->{uid}/$f->{gid}";
761     my $type  = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
762                     [($f->{mode} & S_IFMT) >> 12];
763     my $name = $f->{name};
764
765     if ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
766         $name .= " -> $f->{link}";
767     } elsif ( ($f->{mode} & S_IFMT) == S_IFREG
768             && defined($f->{hlink}) && !$f->{hlink_self} ) {
769         $name .= " -> $f->{hlink}";
770     }
771     $name =~ s/\n/\\n/g;
772
773     $fio->log(sprintf("  %-6s %1s%4o %9s %11.0f %s",
774                                 $action,
775                                 $type,
776                                 $f->{mode} & 07777,
777                                 $owner,
778                                 $f->{size},
779                                 $name));
780 }
781
782 #
783 # If there is a partial and we are doing a full, we do an incremental
784 # against the partial and a full against the rest.  This subroutine
785 # is how we tell File::RsyncP which files to ignore attributes on
786 # (ie: against the partial dump we do consider the attributes, but
787 # otherwise we ignore attributes).
788 #
789 sub ignoreAttrOnFile
790 {
791     my($fio, $f) = @_;
792
793     return if ( !defined($fio->{partialNum}) );
794     my($attr, $isPartial) = $fio->attribGetWhere($f);
795     $fio->log("$f->{name}: just checking attributes from partial")
796                                 if ( $isPartial && $fio->{logLevel} >= 5 );
797     return !$isPartial;
798 }
799
800 #
801 # This is called by File::RsyncP when a file is skipped because the
802 # attributes match.
803 #
804 sub attrSkippedFile
805 {
806     my($fio, $f, $attr) = @_;
807
808     #
809     # Unless this is a partial, this is normal so ignore it.
810     #
811     return if ( !defined($fio->{partialNum}) );
812
813     $fio->log("$f->{name}: skipped in partial; adding link")
814                                     if ( $fio->{logLevel} >= 5 );
815     $fio->{rxLocalAttr} = $attr;
816     $fio->{rxFile} = $f;
817     $fio->{rxSize} = $attr->{size};
818     delete($fio->{rxInFd});
819     delete($fio->{rxOutFd});
820     delete($fio->{rxDigest});
821     delete($fio->{rxInData});
822     return $fio->fileDeltaRxDone();
823 }
824
825 #
826 # Start receive of file deltas for a particular file.
827 #
828 sub fileDeltaRxStart
829 {
830     my($fio, $f, $cnt, $size, $remainder) = @_;
831
832     $fio->{rxFile}      = $f;           # remote file attributes
833     $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
834     $fio->{rxBlkCnt}    = $cnt;         # how many blocks we will receive
835     $fio->{rxBlkSize}   = $size;        # block size
836     $fio->{rxRemainder} = $remainder;   # size of the last block
837     $fio->{rxMatchBlk}  = 0;            # current start of match
838     $fio->{rxMatchNext} = 0;            # current next block of match
839     $fio->{rxSize}      = 0;            # size of received file
840     my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
841     if ( $fio->{rxFile}{size} != $rxSize ) {
842         $fio->{rxMatchBlk} = undef;     # size different, so no file match
843         $fio->log("$fio->{rxFile}{name}: size doesn't match"
844                   . " ($fio->{rxFile}{size} vs $rxSize)")
845                         if ( $fio->{logLevel} >= 5 );
846     }
847     #
848     # If compression was off and now on, or on and now off, then
849     # don't do an exact match.
850     #
851     if ( defined($fio->{rxLocalAttr})
852             && !$fio->{rxLocalAttr}{compress} != !$fio->{xfer}{compress} ) {
853         $fio->{rxMatchBlk} = undef;     # compression changed, so no file match
854         $fio->log("$fio->{rxFile}{name}: compression changed, so no match"
855               . " ($fio->{rxLocalAttr}{compress} vs $fio->{xfer}{compress})")
856                     if ( $fio->{logLevel} >= 4 );
857     }
858     #
859     # If the local file is a hardlink then no match
860     #
861     if ( defined($fio->{rxLocalAttr})
862             && $fio->{rxLocalAttr}{type} == BPC_FTYPE_HARDLINK ) {
863         $fio->{rxMatchBlk} = undef;
864         $fio->log("$fio->{rxFile}{name}: no match on hardlinks")
865                                     if ( $fio->{logLevel} >= 4 );
866         my $fCopy;
867         # need to copy since hardlink attribGet overwrites the name
868         %{$fCopy} = %$f;
869         $fio->{rxHLinkAttr} = $fio->attribGet($fCopy, 1); # hardlink attributes
870     } else {
871         delete($fio->{rxHLinkAttr});
872     }
873     delete($fio->{rxInFd});
874     delete($fio->{rxOutFd});
875     delete($fio->{rxDigest});
876     delete($fio->{rxInData});
877 }
878
879 #
880 # Process the next file delta for the current file.  Returns 0 if ok,
881 # -1 if not.  Must be called with either a block number, $blk, or new data,
882 # $newData, (not both) defined.
883 #
884 sub fileDeltaRxNext
885 {
886     my($fio, $blk, $newData) = @_;
887
888     if ( defined($blk) ) {
889         if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
890             #
891             # got the next block in order; just keep track.
892             #
893             $fio->{rxMatchNext}++;
894             return;
895         }
896     }
897     my $newDataLen = length($newData);
898     $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
899                     if ( $fio->{logLevel} >= 8 );
900     if ( !defined($fio->{rxOutFd}) ) {
901         #
902         # maybe the file has no changes
903         #
904         if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
905                 && !defined($blk) && !defined($newData) ) {
906             #$fio->log("$fio->{rxFile}{name}: file is unchanged");
907             #               if ( $fio->{logLevel} >= 8 );
908             return;
909         }
910
911         #
912         # need to open an output file where we will build the
913         # new version.
914         #
915         $fio->{rxFile}{name} =~ /(.*)/s;
916         my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
917         my $rxOutFile    = $fio->{outDir} . $rxOutFileRel;
918         $fio->{rxOutFd}  = BackupPC::PoolWrite->new($fio->{bpc},
919                                            $rxOutFile, $fio->{rxFile}{size},
920                                            $fio->{xfer}{compress});
921         $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
922                         if ( $fio->{logLevel} >= 9 );
923         $fio->{rxOutFile} = $rxOutFile;
924         $fio->{rxOutFileRel} = $rxOutFileRel;
925         $fio->{rxDigest} = File::RsyncP::Digest->new();
926         $fio->{rxDigest}->protocol($fio->{protocol_version});
927         $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
928     }
929     if ( defined($fio->{rxMatchBlk})
930                 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
931         #
932         # Need to copy the sequence of blocks that matched.  If the file
933         # is compressed we need to make a copy of the uncompressed file,
934         # since the compressed file is not seekable.  Future optimizations
935         # could include only creating an uncompressed copy if the matching
936         # blocks were not monotonic, and to only do this if there are
937         # matching blocks (eg, maybe the entire file is new).
938         #
939         my $attr = $fio->{rxLocalAttr};
940         my $fh;
941         if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
942             my $inPath = $attr->{fullPath};
943             $inPath = $fio->{rxHLinkAttr}{fullPath}
944                             if ( defined($fio->{rxHLinkAttr}) );
945             if ( $attr->{compress} ) {
946                 if ( !defined($fh = BackupPC::FileZIO->open(
947                                                    $inPath,
948                                                    0,
949                                                    $attr->{compress})) ) {
950                     $fio->log("Can't open $inPath");
951                     $fio->{stats}{errorCnt}++;
952                     return -1;
953                 }
954                 if ( $attr->{size} < 16 * 1024 * 1024 ) {
955                     #
956                     # Cache the entire old file if it is less than 16MB
957                     #
958                     my $data;
959                     $fio->{rxInData} = "";
960                     while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
961                         $fio->{rxInData} .= $data;
962                     }
963                     $fio->log("$attr->{fullPath}: cached all $attr->{size}"
964                             . " bytes")
965                                     if ( $fio->{logLevel} >= 9 );
966                 } else {
967                     #
968                     # Create and write a temporary output file
969                     #
970                     unlink("$fio->{outDirSh}RStmp")
971                                     if  ( -f "$fio->{outDirSh}RStmp" );
972                     if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
973                         my $data;
974                         my $byteCnt = 0;
975                         binmode(F);
976                         while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
977                             if ( syswrite(F, $data) != length($data) ) {
978                                 $fio->log(sprintf("Can't write len=%d to %s",
979                                       length($data) , "$fio->{outDirSh}RStmp"));
980                                 $fh->close;
981                                 $fio->{stats}{errorCnt}++;
982                                 return -1;
983                             }
984                             $byteCnt += length($data);
985                         }
986                         $fio->{rxInFd} = *F;
987                         $fio->{rxInName} = "$fio->{outDirSh}RStmp";
988                         sysseek($fio->{rxInFd}, 0, 0);
989                         $fio->log("$attr->{fullPath}: copied $byteCnt,"
990                                 . "$attr->{size} bytes to $fio->{rxInName}")
991                                         if ( $fio->{logLevel} >= 9 );
992                     } else {
993                         $fio->log("Unable to open $fio->{outDirSh}RStmp");
994                         $fh->close;
995                         $fio->{stats}{errorCnt}++;
996                         return -1;
997                     }
998                 }
999                 $fh->close;
1000             } else {
1001                 if ( open(F, "<", $inPath) ) {
1002                     binmode(F);
1003                     $fio->{rxInFd} = *F;
1004                     $fio->{rxInName} = $attr->{fullPath};
1005                 } else {
1006                     $fio->log("Unable to open $inPath");
1007                     $fio->{stats}{errorCnt}++;
1008                     return -1;
1009                 }
1010             }
1011         }
1012         my $lastBlk = $fio->{rxMatchNext} - 1;
1013         $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
1014                   . "$lastBlk")
1015                         if ( $fio->{logLevel} >= 9 );
1016         my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
1017         if ( defined($fio->{rxInFd})
1018                         && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
1019             $fio->log("Unable to seek $fio->{rxInName} to $seekPosn");
1020             $fio->{stats}{errorCnt}++;
1021             return -1;
1022         }
1023         my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
1024         my($thisCnt, $len, $data);
1025         for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
1026             $thisCnt = $cnt - $i;
1027             $thisCnt = 512 if ( $thisCnt > 512 );
1028             if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
1029                 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
1030             } else {
1031                 $len = $thisCnt * $fio->{rxBlkSize};
1032             }
1033             if ( defined($fio->{rxInData}) ) {
1034                 $data = substr($fio->{rxInData}, $seekPosn, $len);
1035                 $seekPosn += $len;
1036             } else {
1037                 my $got = sysread($fio->{rxInFd}, $data, $len);
1038                 if ( $got != $len ) {
1039                     my $inFileSize = -s $fio->{rxInName};
1040                     $fio->log("Unable to read $len bytes from $fio->{rxInName}"
1041                             . " got=$got, seekPosn=$seekPosn"
1042                             . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
1043                             . ",$attr->{size})");
1044                     $fio->{stats}{errorCnt}++;
1045                     return -1;
1046                 }
1047                 $seekPosn += $len;
1048             }
1049             $fio->{rxOutFd}->write(\$data);
1050             $fio->{rxDigest}->add($data);
1051             $fio->{rxSize} += length($data);
1052         }
1053         $fio->{rxMatchBlk} = undef;
1054     }
1055     if ( defined($blk) ) {
1056         #
1057         # Remember the new block number
1058         #
1059         $fio->{rxMatchBlk}  = $blk;
1060         $fio->{rxMatchNext} = $blk + 1;
1061     }
1062     if ( defined($newData) ) {
1063         #
1064         # Write the new chunk
1065         #
1066         my $len = length($newData);
1067         $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
1068                         if ( $fio->{logLevel} >= 9 );
1069         $fio->{rxOutFd}->write(\$newData);
1070         $fio->{rxDigest}->add($newData);
1071         $fio->{rxSize} += length($newData);
1072     }
1073 }
1074
1075 #
1076 # Finish up the current receive file.  Returns undef if ok, -1 if not.
1077 # Returns 1 if the md4 digest doesn't match.
1078 #
1079 sub fileDeltaRxDone
1080 {
1081     my($fio, $md4, $phase) = @_;
1082     my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/s );
1083     my $ret;
1084
1085     close($fio->{rxInFd})  if ( defined($fio->{rxInFd}) );
1086     unlink("$fio->{outDirSh}RStmp") if  ( -f "$fio->{outDirSh}RStmp" );
1087     $fio->{phase} = $phase;
1088
1089     #
1090     # Check the final md4 digest
1091     #
1092     if ( defined($md4) ) {
1093         my $newDigest;
1094         if ( !defined($fio->{rxDigest}) ) {
1095             #
1096             # File was exact match, but we still need to verify the
1097             # MD4 checksum.  Compute the md4 digest (or fetch the
1098             # cached one.)
1099             #
1100             if ( defined(my $attr = $fio->{rxLocalAttr}) ) {
1101                 #
1102                 # block size doesn't matter: we're only going to
1103                 # fetch the md4 file digest, not the block digests.
1104                 #
1105                 my($err, $csum, $blkSize)
1106                          = BackupPC::Xfer::RsyncDigest->digestStart(
1107                                  $attr->{fullPath}, $attr->{size},
1108                                  0, 2048, $fio->{checksumSeed}, 1,
1109                                  $attr->{compress}, 1);
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;