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