cc29e293393ded465678b159612b35a157512faa
[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 2.1.0_CVS, released 3 Jul 2003.
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 BackupPC::Attrib qw(:all);
26 use BackupPC::View;
27 use BackupPC::PoolWrite;
28 use BackupPC::PoolWrite;
29 use Data::Dumper;
30
31 use constant S_IFMT       => 0170000;   # type of file
32 use constant S_IFDIR      => 0040000;   # directory
33 use constant S_IFCHR      => 0020000;   # character special
34 use constant S_IFBLK      => 0060000;   # block special
35 use constant S_IFREG      => 0100000;   # regular
36 use constant S_IFLNK      => 0120000;   # symbolic link
37 use constant S_IFSOCK     => 0140000;   # socket
38 use constant S_IFIFO      => 0010000;   # fifo
39
40 use vars qw( $RsyncLibOK );
41
42 BEGIN {
43     eval "use File::RsyncP::Digest";
44     if ( $@ ) {
45         #
46         # Rsync module doesn't exist.
47         #
48         $RsyncLibOK = 0;
49     } else {
50         $RsyncLibOK = 1;
51     }
52 };
53
54 sub new
55 {
56     my($class, $options) = @_;
57
58     return if ( !$RsyncLibOK );
59     $options ||= {};
60     my $fio = bless {
61         blockSize    => 700,
62         logLevel     => 0,
63         digest       => File::RsyncP::Digest->new,
64         checksumSeed => 0,
65         attrib       => {},
66         logHandler   => \&logHandler,
67         stats        => {
68             errorCnt          => 0,
69             TotalFileCnt      => 0,
70             TotalFileSize     => 0,
71             ExistFileCnt      => 0,
72             ExistFileSize     => 0,
73             ExistFileCompSize => 0,
74         },
75         %$options,
76     }, $class;
77
78     $fio->{shareM}   = $fio->{bpc}->fileNameEltMangle($fio->{share});
79     $fio->{outDir}   = "$fio->{xfer}{outDir}/new/";
80     $fio->{outDirSh} = "$fio->{outDir}/$fio->{shareM}/";
81     $fio->{view}     = BackupPC::View->new($fio->{bpc}, $fio->{client},
82                                          $fio->{backups});
83     $fio->{full}     = $fio->{xfer}{type} eq "full" ? 1 : 0;
84     $fio->{newFilesFH} = $fio->{xfer}{newFilesFH};
85     return $fio;
86 }
87
88 sub blockSize
89 {
90     my($fio, $value) = @_;
91
92     $fio->{blockSize} = $value if ( defined($value) );
93     return $fio->{blockSize};
94 }
95
96 sub logHandlerSet
97 {
98     my($fio, $sub) = @_;
99     $fio->{logHandler} = $sub;
100 }
101
102 #
103 # Setup rsync checksum computation for the given file.
104 #
105 sub csumStart
106 {
107     my($fio, $f, $needMD4) = @_;
108
109     my $attr = $fio->attribGet($f);
110     $fio->{file} = $f;
111     $fio->csumEnd if ( defined($fio->{fh}) );
112     return if ( $attr->{type} != BPC_FTYPE_FILE );
113     if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
114                                                        0,
115                                                        $attr->{compress})) ) {
116         $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
117         $fio->{stats}{errorCnt}++;
118         return -1;
119     }
120     if ( $needMD4) {
121         $fio->{csumDigest} = File::RsyncP::Digest->new;
122         $fio->{csumDigest}->add(pack("V", $fio->{checksumSeed}));
123     } else {
124         delete($fio->{csumDigest});
125     }
126 }
127
128 sub csumGet
129 {
130     my($fio, $num, $csumLen, $blockSize) = @_;
131     my($fileData);
132
133     $num     ||= 100;
134     $csumLen ||= 16;
135
136     return if ( !defined($fio->{fh}) );
137     if ( $fio->{fh}->read(\$fileData, $blockSize * $num) <= 0 ) {
138         $fio->log("$fio->{file}{name}: csumGet is at EOF - zero padding");
139         $fio->{stats}{errorCnt}++;
140         $fileData = pack("c", 0) x ($blockSize * $num);
141     }
142     $fio->{csumDigest}->add($fileData) if ( defined($fio->{csumDigest}) );
143     $fio->log(sprintf("%s: getting csum ($num,$csumLen,%d,0x%x)",
144                             $fio->{file}{name},
145                             length($fileData),
146                             $fio->{checksumSeed}))
147                 if ( $fio->{logLevel} >= 9 );
148     return $fio->{digest}->blockDigest($fileData, $blockSize,
149                                          $csumLen, $fio->{checksumSeed});
150 }
151
152 sub csumEnd
153 {
154     my($fio) = @_;
155
156     return if ( !defined($fio->{fh}) );
157     #
158     # make sure we read the entire file for the file MD4 digest
159     #
160     if ( defined($fio->{csumDigest}) ) {
161         my $fileData;
162         while ( $fio->{fh}->read(\$fileData, 65536) > 0 ) {
163             $fio->{csumDigest}->add($fileData);
164         }
165     }
166     $fio->{fh}->close();
167     delete($fio->{fh});
168     return $fio->{csumDigest}->digest if ( defined($fio->{csumDigest}) );
169 }
170
171 sub readStart
172 {
173     my($fio, $f) = @_;
174
175     my $attr = $fio->attribGet($f);
176     $fio->{file} = $f;
177     $fio->readEnd if ( defined($fio->{fh}) );
178     if ( !defined($fio->{fh} = BackupPC::FileZIO->open($attr->{fullPath},
179                                            0,
180                                            $attr->{compress})) ) {
181         $fio->log("Can't open $attr->{fullPath} (name=$f->{name})");
182         $fio->{stats}{errorCnt}++;
183         return;
184     }
185     $fio->log("$f->{name}: opened for read") if ( $fio->{logLevel} >= 4 );
186 }
187
188 sub read
189 {
190     my($fio, $num) = @_;
191     my $fileData;
192
193     $num ||= 32768;
194     return if ( !defined($fio->{fh}) );
195     if ( $fio->{fh}->read(\$fileData, $num) <= 0 ) {
196         return $fio->readEnd;
197     }
198     $fio->log(sprintf("read returns %d bytes", length($fileData)))
199                                 if ( $fio->{logLevel} >= 8 );
200     return \$fileData;
201 }
202
203 sub readEnd
204 {
205     my($fio) = @_;
206
207     return if ( !defined($fio->{fh}) );
208     $fio->{fh}->close;
209     $fio->log("closing $fio->{file}{name})") if ( $fio->{logLevel} >= 8 );
210     delete($fio->{fh});
211     return;
212 }
213
214 sub checksumSeed
215 {
216     my($fio, $checksumSeed) = @_;
217
218     $fio->{checksumSeed} = $checksumSeed;
219 }
220
221 sub dirs
222 {
223     my($fio, $localDir, $remoteDir) = @_;
224
225     $fio->{localDir}  = $localDir;
226     $fio->{remoteDir} = $remoteDir;
227 }
228
229 sub viewCacheDir
230 {
231     my($fio, $share, $dir) = @_;
232     my $shareM;
233
234     #$fio->log("viewCacheDir($share, $dir)");
235     if ( !defined($share) ) {
236         $share  = $fio->{share};
237         $shareM = $fio->{shareM};
238     } else {
239         $shareM = $fio->{bpc}->fileNameEltMangle($share);
240     }
241     $shareM = "$shareM/$dir" if ( $dir ne "" );
242     return if ( defined($fio->{viewCache}{$shareM}) );
243     #
244     # purge old cache entries (ie: those that don't match the
245     # first part of $dir).
246     #
247     foreach my $d ( keys(%{$fio->{viewCache}}) ) {
248         delete($fio->{viewCache}{$d}) if ( $shareM !~ m{^\Q$d/} );
249     }
250     #
251     # fetch new directory attributes
252     #
253     $fio->{viewCache}{$shareM}
254                 = $fio->{view}->dirAttrib($fio->{viewNum}, $share, $dir);
255 }
256
257 sub attribGet
258 {
259     my($fio, $f) = @_;
260     my($dir, $fname, $share, $shareM);
261
262     $fname = $f->{name};
263     $fname = "$fio->{xfer}{pathHdrSrc}/$fname"
264                        if ( defined($fio->{xfer}{pathHdrSrc}) );
265     $fname =~ s{//+}{/}g;
266     if ( $fname =~ m{(.*)/(.*)} ) {
267         $shareM = $fio->{shareM};
268         $dir = $1;
269         $fname = $2;
270     } elsif ( $fname ne "." ) {
271         $shareM = $fio->{shareM};
272         $dir = "";
273     } else {
274         $share = "";
275         $shareM = "";
276         $dir = "";
277         $fname = $fio->{share};
278     }
279     $fio->viewCacheDir($share, $dir);
280     $shareM .= "/$dir" if ( $dir ne "" );
281     return $fio->{viewCache}{$shareM}{$fname};
282 }
283
284 sub mode2type
285 {
286     my($fio, $mode) = @_;
287
288     if ( ($mode & S_IFMT) == S_IFREG ) {
289         return BPC_FTYPE_FILE;
290     } elsif ( ($mode & S_IFMT) == S_IFDIR ) {
291         return BPC_FTYPE_DIR;
292     } elsif ( ($mode & S_IFMT) == S_IFLNK ) {
293         return BPC_FTYPE_SYMLINK;
294     } elsif ( ($mode & S_IFMT) == S_IFCHR ) {
295         return BPC_FTYPE_CHARDEV;
296     } elsif ( ($mode & S_IFMT) == S_IFBLK ) {
297         return BPC_FTYPE_BLOCKDEV;
298     } elsif ( ($mode & S_IFMT) == S_IFIFO ) {
299         return BPC_FTYPE_FIFO;
300     } elsif ( ($mode & S_IFMT) == S_IFSOCK ) {
301         return BPC_FTYPE_SOCKET;
302     } else {
303         return BPC_FTYPE_UNKNOWN;
304     }
305 }
306
307 #
308 # Set the attributes for a file.  Returns non-zero on error.
309 #
310 sub attribSet
311 {
312     my($fio, $f, $placeHolder) = @_;
313     my($dir, $file);
314
315     if ( $f->{name} =~ m{(.*)/(.*)} ) {
316         $file = $2;
317         $dir  = "$fio->{shareM}/" . $1;
318     } elsif ( $f->{name} eq "." ) {
319         $dir  = "";
320         $file = $fio->{share};
321     } else {
322         $dir  = $fio->{shareM};
323         $file = $f->{name};
324     }
325
326     if ( !defined($fio->{attribLastDir}) || $fio->{attribLastDir} ne $dir ) {
327         #
328         # Flush any directories that don't match the first part
329         # of the new directory
330         #
331         foreach my $d ( keys(%{$fio->{attrib}}) ) {
332             next if ( $d eq "" || "$dir/" =~ m{^\Q$d/} );
333             $fio->attribWrite($d);
334         }
335         $fio->{attribLastDir} = $dir;
336     }
337     if ( !exists($fio->{attrib}{$dir}) ) {
338         $fio->{attrib}{$dir} = BackupPC::Attrib->new({
339                                      compress => $fio->{xfer}{compress},
340                                 });
341         my $path = $fio->{outDir} . $dir;
342         if ( -f $fio->{attrib}{$dir}->fileName($path)
343                     && !$fio->{attrib}{$dir}->read($path) ) {
344             $fio->log(sprintf("Unable to read attribute file %s",
345                             $fio->{attrib}{$dir}->fileName($path)));
346         }
347     }
348     $fio->log("attribSet(dir=$dir, file=$file)") if ( $fio->{logLevel} >= 4 );
349
350     $fio->{attrib}{$dir}->set($file, {
351                             type  => $fio->mode2type($f->{mode}),
352                             mode  => $f->{mode},
353                             uid   => $f->{uid},
354                             gid   => $f->{gid},
355                             size  => $placeHolder ? -1 : $f->{size},
356                             mtime => $f->{mtime},
357                        });
358     return;
359 }
360
361 sub attribWrite
362 {
363     my($fio, $d) = @_;
364     my($poolWrite);
365
366     if ( !defined($d) ) {
367         #
368         # flush all entries (in reverse order)
369         #
370         foreach $d ( sort({$b cmp $a} keys(%{$fio->{attrib}})) ) {
371             $fio->attribWrite($d);
372         }
373         return;
374     }
375     return if ( !defined($fio->{attrib}{$d}) );
376     #
377     # Set deleted files in the attributes.  Any file in the view
378     # that doesn't have attributes is deleted.  All files sent by
379     # rsync have attributes temporarily set so we can do deletion
380     # detection.  We also prune these temporary attributes.
381     #
382     if ( $d ne "" ) {
383         my $dir;
384         my $share;
385
386         $dir = $1 if ( $d =~ m{.+?/(.*)} );
387         $fio->viewCacheDir(undef, $dir);
388         ##print("attribWrite $d,$dir\n");
389         ##$Data::Dumper::Indent = 1;
390         ##$fio->log("attribWrite $d,$dir");
391         ##$fio->log("viewCacheLogKeys = ", keys(%{$fio->{viewCache}}));
392         ##$fio->log("attribKeys = ", keys(%{$fio->{attrib}}));
393         ##print "viewCache = ", Dumper($fio->{attrib});
394         ##print "attrib = ", Dumper($fio->{attrib});
395         if ( defined($fio->{viewCache}{$d}) ) {
396             foreach my $f ( keys(%{$fio->{viewCache}{$d}}) ) {
397                 my $name = $f;
398                 $name = "$1/$name" if ( $d =~ m{.*?/(.*)} );
399                 if ( defined(my $a = $fio->{attrib}{$d}->get($f)) ) {
400                     #
401                     # delete temporary attributes (skipped files)
402                     #
403                     if ( $a->{size} < 0 ) {
404                         $fio->{attrib}{$d}->set($f, undef);
405                         $fio->logFileAction("skip", {
406                                     %{$fio->{viewCache}{$d}{$f}},
407                                     name => $name,
408                                 }) if ( $fio->{logLevel} >= 2 );
409                     }
410                 } else {
411                     ##print("Delete file $f\n");
412                     $fio->logFileAction("delete", {
413                                 %{$fio->{viewCache}{$d}{$f}},
414                                 name => $name,
415                             }) if ( $fio->{logLevel} >= 1 );
416                     $fio->{attrib}{$d}->set($f, {
417                                     type  => BPC_FTYPE_DELETED,
418                                     mode  => 0,
419                                     uid   => 0,
420                                     gid   => 0,
421                                     size  => 0,
422                                     mtime => 0,
423                                });
424                 }
425             }
426         }
427     }
428     if ( $fio->{attrib}{$d}->fileCount ) {
429         my $data = $fio->{attrib}{$d}->writeData;
430         my $dirM = $d;
431
432         $dirM = $1 . "/" . $fio->{bpc}->fileNameMangle($2)
433                         if ( $dirM =~ m{(.*?)/(.*)} );
434         my $fileName = $fio->{attrib}{$d}->fileName("$fio->{outDir}$dirM");
435         $fio->log("attribWrite(dir=$d) -> $fileName")
436                                 if ( $fio->{logLevel} >= 4 );
437         my $poolWrite = BackupPC::PoolWrite->new($fio->{bpc}, $fileName,
438                                      length($data), $fio->{xfer}{compress});
439         $poolWrite->write(\$data);
440         $fio->processClose($poolWrite, $fio->{attrib}{$d}->fileName($dirM),
441                            length($data), 0);
442     }
443     delete($fio->{attrib}{$d});
444 }
445
446 sub processClose
447 {
448     my($fio, $poolWrite, $fileName, $origSize, $doStats) = @_;
449     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
450
451     $fileName =~ s{^/+}{};
452     $fio->log(@$errs) if ( defined($errs) && @$errs );
453     if ( $doStats ) {
454         $fio->{stats}{TotalFileCnt}++;
455         $fio->{stats}{TotalFileSize} += $origSize;
456     }
457     if ( $exists ) {
458         if ( $doStats ) {
459             $fio->{stats}{ExistFileCnt}++;
460             $fio->{stats}{ExistFileSize}     += $origSize;
461             $fio->{stats}{ExistFileCompSize} += $outSize;
462         }
463     } elsif ( $outSize > 0 ) {
464         my $fh = $fio->{newFilesFH};
465         print($fh "$digest $origSize $fileName\n") if ( defined($fh) );
466     }
467     return $exists && $origSize > 0;
468 }
469
470 sub statsGet
471 {
472     my($fio) = @_;
473
474     return $fio->{stats};
475 }
476
477 #
478 # Make a given directory.  Returns non-zero on error.
479 #
480 sub makePath
481 {
482     my($fio, $f) = @_;
483     my $name = $1 if ( $f->{name} =~ /(.*)/ );
484     my $path;
485
486     if ( $name eq "." ) {
487         $path = $fio->{outDirSh};
488     } else {
489         $path = $fio->{outDirSh} . $fio->{bpc}->fileNameMangle($name);
490     }
491     $fio->logFileAction("create", $f) if ( $fio->{logLevel} >= 1 );
492     $fio->log("makePath($path, 0777)") if ( $fio->{logLevel} >= 5 );
493     $path = $1 if ( $path =~ /(.*)/ );
494     File::Path::mkpath($path, 0, 0777) if ( !-d $path );
495     return $fio->attribSet($f) if ( -d $path );
496     $fio->log("Can't create directory $path");
497     $fio->{stats}{errorCnt}++;
498     return -1;
499 }
500
501 #
502 # Make a special file.  Returns non-zero on error.
503 #
504 sub makeSpecial
505 {
506     my($fio, $f) = @_;
507     my $name = $1 if ( $f->{name} =~ /(.*)/ );
508     my $fNameM = $fio->{bpc}->fileNameMangle($name);
509     my $path = $fio->{outDirSh} . $fNameM;
510     my $attr = $fio->attribGet($f);
511     my $str = "";
512     my $type = $fio->mode2type($f->{mode});
513
514     $fio->log("makeSpecial($path, $type, $f->{mode})")
515                     if ( $fio->{logLevel} >= 5 );
516     if ( $type == BPC_FTYPE_CHARDEV || $type == BPC_FTYPE_BLOCKDEV ) {
517         my($major, $minor, $fh, $fileData);
518
519         $major = $f->{rdev} >> 8;
520         $minor = $f->{rdev} & 0xff;
521         $str = "$major,$minor";
522     } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
523         $str = $f->{link};
524     }
525     #
526     # Now see if the file is different, or this is a full, in which
527     # case we create the new file.
528     #
529     my($fh, $fileData);
530     if ( $fio->{full}
531             || !defined($attr)
532             || $attr->{type}  != $fio->mode2type($f->{mode})
533             || $attr->{mtime} != $f->{mtime}
534             || $attr->{size}  != $f->{size}
535             || $attr->{uid}   != $f->{uid}
536             || $attr->{gid}   != $f->{gid}
537             || $attr->{mode}  != $f->{mode}
538             || !defined($fh = BackupPC::FileZIO->open($attr->{fullPath}, 0,
539                                                       $attr->{compress}))
540             || $fh->read(\$fileData, length($str) + 1) != length($str)
541             || $fileData ne $str ) {
542         $fh->close if ( defined($fh) );
543         $fh = BackupPC::PoolWrite->new($fio->{bpc}, $path,
544                                      length($str), $fio->{xfer}{compress});
545         $fh->write(\$str);
546         my $exist = $fio->processClose($fh, "$fio->{shareM}/$fNameM",
547                                        length($str), 1);
548         $fio->logFileAction($exist ? "pool" : "create", $f)
549                             if ( $fio->{logLevel} >= 1 );
550         return $fio->attribSet($f);
551     } else {
552         $fio->logFileAction("skip", $f) if ( $fio->{logLevel} >= 2 );
553     }
554     $fh->close if ( defined($fh) );
555 }
556
557 sub unlink
558 {
559     my($fio, $path) = @_;
560     
561     $fio->log("Unexpected call BackupPC::Xfer::RsyncFileIO->unlink($path)"); 
562 }
563
564 #
565 # Default log handler
566 #
567 sub logHandler
568 {
569     my($str) = @_;
570
571     print(STDERR $str, "\n");
572 }
573
574 #
575 # Handle one or more log messages
576 #
577 sub log
578 {
579     my($fio, @logStr) = @_;
580
581     foreach my $str ( @logStr ) {
582         next if ( $str eq "" );
583         $fio->{logHandler}($str);
584     }
585 }
586
587 #
588 # Generate a log file message for a completed file
589 #
590 sub logFileAction
591 {
592     my($fio, $action, $f) = @_;
593     my $owner = "$f->{uid}/$f->{gid}";
594     my $type  = (("", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s"))
595                     [($f->{mode} & S_IFMT) >> 12];
596
597     $fio->log(sprintf("  %-6s %1s%4o %9s %11.0f %s",
598                                 $action,
599                                 $type,
600                                 $f->{mode} & 07777,
601                                 $owner,
602                                 $f->{size},
603                                 $f->{name}));
604 }
605
606 #
607 # Later we'll use this function to complete a prior unfinished dump.
608 # We'll do an incremental on the part we have already, and then a
609 # full or incremental against the rest.
610 #
611 sub ignoreAttrOnFile
612 {
613     return undef;
614 }
615
616 #
617 # Start receive of file deltas for a particular file.
618 #
619 sub fileDeltaRxStart
620 {
621     my($fio, $f, $cnt, $size, $remainder) = @_;
622
623     $fio->{rxFile}      = $f;           # remote file attributes
624     $fio->{rxLocalAttr} = $fio->attribGet($f); # local file attributes
625     $fio->{rxBlkCnt}    = $cnt;         # how many blocks we will receive
626     $fio->{rxBlkSize}   = $size;        # block size
627     $fio->{rxRemainder} = $remainder;   # size of the last block
628     $fio->{rxMatchBlk}  = 0;            # current start of match
629     $fio->{rxMatchNext} = 0;            # current next block of match
630     $fio->{rxSize}      = 0;            # size of received file
631     my $rxSize = $cnt > 0 ? ($cnt - 1) * $size + $remainder : 0;
632     if ( $fio->{rxFile}{size} != $rxSize ) {
633         $fio->{rxMatchBlk} = undef;     # size different, so no file match
634         $fio->log("$fio->{rxFile}{name}: size doesn't match"
635                   . " ($fio->{rxFile}{size} vs $rxSize)")
636                         if ( $fio->{logLevel} >= 5 );
637     }
638     delete($fio->{rxInFd});
639     delete($fio->{rxOutFd});
640     delete($fio->{rxDigest});
641     delete($fio->{rxInData});
642 }
643
644 #
645 # Process the next file delta for the current file.  Returns 0 if ok,
646 # -1 if not.  Must be called with either a block number, $blk, or new data,
647 # $newData, (not both) defined.
648 #
649 sub fileDeltaRxNext
650 {
651     my($fio, $blk, $newData) = @_;
652
653     if ( defined($blk) ) {
654         if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
655             #
656             # got the next block in order; just keep track.
657             #
658             $fio->{rxMatchNext}++;
659             return;
660         }
661     }
662     my $newDataLen = length($newData);
663     $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen, rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
664                     if ( $fio->{logLevel} >= 8 );
665     if ( !defined($fio->{rxOutFd}) ) {
666         #
667         # maybe the file has no changes
668         #
669         if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
670                 && !defined($blk) && !defined($newData) ) {
671             #$fio->log("$fio->{rxFile}{name}: file is unchanged");
672             #               if ( $fio->{logLevel} >= 8 );
673             return;
674         }
675
676         #
677         # need to open an output file where we will build the
678         # new version.
679         #
680         $fio->{rxFile}{name} =~ /(.*)/;
681         my $rxOutFileRel = "$fio->{shareM}/" . $fio->{bpc}->fileNameMangle($1);
682         my $rxOutFile    = $fio->{outDir} . $rxOutFileRel;
683         $fio->{rxOutFd}  = BackupPC::PoolWrite->new($fio->{bpc},
684                                            $rxOutFile, $fio->{rxFile}{size},
685                                            $fio->{xfer}{compress});
686         $fio->log("$fio->{rxFile}{name}: opening output file $rxOutFile")
687                         if ( $fio->{logLevel} >= 9 );
688         $fio->{rxOutFile} = $rxOutFile;
689         $fio->{rxOutFileRel} = $rxOutFileRel;
690         $fio->{rxDigest} = File::RsyncP::Digest->new;
691         $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
692     }
693     if ( defined($fio->{rxMatchBlk})
694                 && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
695         #
696         # Need to copy the sequence of blocks that matched.  If the file
697         # is compressed we need to make a copy of the uncompressed file,
698         # since the compressed file is not seekable.  Future optimizations
699         # would be to keep the uncompressed file in memory (eg, up to say
700         # 10MB), only create an uncompressed copy if the matching
701         # blocks were not monotonic, and to only do this if there are
702         # matching blocks (eg, maybe the entire file is new).
703         #
704         my $attr = $fio->{rxLocalAttr};
705         my $fh;
706         if ( !defined($fio->{rxInFd}) && !defined($fio->{rxInData}) ) {
707             if ( $attr->{compress} ) {
708                 if ( !defined($fh = BackupPC::FileZIO->open(
709                                                    $attr->{fullPath},
710                                                    0,
711                                                    $attr->{compress})) ) {
712                     $fio->log("Can't open $attr->{fullPath}");
713                     $fio->{stats}{errorCnt}++;
714                     return -1;
715                 }
716                 if ( $attr->{size} < 16 * 1024 * 1024 ) {
717                     #
718                     # Cache the entire old file if it is less than 16MB
719                     #
720                     my $data;
721                     $fio->{rxInData} = "";
722                     while ( $fh->read(\$data, 16 * 1024 * 1024) > 0 ) {
723                         $fio->{rxInData} .= $data;
724                     }
725                     $fio->log("$attr->{fullPath}: cached all $attr->{size}"
726                             . " bytes")
727                                     if ( $fio->{logLevel} >= 9 );
728                 } else {
729                     #
730                     # Create and write a temporary output file
731                     #
732                     unlink("$fio->{outDirSh}RStmp")
733                                     if  ( -f "$fio->{outDirSh}RStmp" );
734                     if ( open(F, "+>", "$fio->{outDirSh}RStmp") ) {
735                         my $data;
736                         my $byteCnt = 0;
737                         binmode(F);
738                         while ( $fh->read(\$data, 1024 * 1024) > 0 ) {
739                             if ( syswrite(F, $data) != length($data) ) {
740                                 $fio->log(sprintf("Can't write len=%d to %s",
741                                       length($data) , "$fio->{outDirSh}RStmp"));
742                                 $fh->close;
743                                 $fio->{stats}{errorCnt}++;
744                                 return -1;
745                             }
746                             $byteCnt += length($data);
747                         }
748                         $fio->{rxInFd} = *F;
749                         $fio->{rxInName} = "$fio->{outDirSh}RStmp";
750                         sysseek($fio->{rxInFd}, 0, 0);
751                         $fio->log("$attr->{fullPath}: copied $byteCnt,"
752                                 . "$attr->{size} bytes to $fio->{rxInName}")
753                                         if ( $fio->{logLevel} >= 9 );
754                     } else {
755                         $fio->log("Unable to open $fio->{outDirSh}RStmp");
756                         $fh->close;
757                         $fio->{stats}{errorCnt}++;
758                         return -1;
759                     }
760                 }
761                 $fh->close;
762             } else {
763                 if ( open(F, "<", $attr->{fullPath}) ) {
764                     binmode(F);
765                     $fio->{rxInFd} = *F;
766                     $fio->{rxInName} = $attr->{fullPath};
767                 } else {
768                     $fio->log("Unable to open $attr->{fullPath}");
769                     $fio->{stats}{errorCnt}++;
770                     return -1;
771                 }
772             }
773         }
774         my $lastBlk = $fio->{rxMatchNext} - 1;
775         $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
776                   . "$lastBlk")
777                         if ( $fio->{logLevel} >= 9 );
778         my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
779         if ( defined($fio->{rxInFd})
780                         && !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
781             $fio->log("Unable to seek $attr->{rxInName} to $seekPosn");
782             $fio->{stats}{errorCnt}++;
783             return -1;
784         }
785         my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
786         my($thisCnt, $len, $data);
787         for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
788             $thisCnt = $cnt - $i;
789             $thisCnt = 512 if ( $thisCnt > 512 );
790             if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
791                 $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
792             } else {
793                 $len = $thisCnt * $fio->{rxBlkSize};
794             }
795             if ( defined($fio->{rxInData}) ) {
796                 $data = substr($fio->{rxInData}, $seekPosn, $len);
797                 $seekPosn += $len;
798             } else {
799                 my $got = sysread($fio->{rxInFd}, $data, $len);
800                 if ( $got != $len ) {
801                     my $inFileSize = -s $fio->{rxInName};
802                     $fio->log("Unable to read $len bytes from $fio->{rxInName}"
803                             . " got=$got, seekPosn=$seekPosn"
804                             . " ($i,$thisCnt,$fio->{rxBlkCnt},$inFileSize"
805                             . ",$attr->{size})");
806                     $fio->{stats}{errorCnt}++;
807                     return -1;
808                 }
809                 $seekPosn += $len;
810             }
811             $fio->{rxOutFd}->write(\$data);
812             $fio->{rxDigest}->add($data);
813             $fio->{rxSize} += length($data);
814         }
815         $fio->{rxMatchBlk} = undef;
816     }
817     if ( defined($blk) ) {
818         #
819         # Remember the new block number
820         #
821         $fio->{rxMatchBlk}  = $blk;
822         $fio->{rxMatchNext} = $blk + 1;
823     }
824     if ( defined($newData) ) {
825         #
826         # Write the new chunk
827         #
828         my $len = length($newData);
829         $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
830                         if ( $fio->{logLevel} >= 9 );
831         $fio->{rxOutFd}->write(\$newData);
832         $fio->{rxDigest}->add($newData);
833         $fio->{rxSize} += length($newData);
834     }
835 }
836
837 #
838 # Finish up the current receive file.  Returns undef if ok, -1 if not.
839 # Returns 1 if the md4 digest doesn't match.
840 #
841 sub fileDeltaRxDone
842 {
843     my($fio, $md4) = @_;
844     my $name = $1 if ( $fio->{rxFile}{name} =~ /(.*)/ );
845
846     if ( !defined($fio->{rxDigest}) ) {
847         #
848         # File was exact match, but we still need to verify the
849         # MD4 checksum.  Therefore open and read the file.
850         #
851         $fio->{rxDigest} = File::RsyncP::Digest->new;
852         $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
853         my $attr = $fio->{rxLocalAttr};
854         if ( defined($attr) ) {
855             if ( defined(my $fh = BackupPC::FileZIO->open(
856                                                        $attr->{fullPath},
857                                                        0,
858                                                        $attr->{compress})) ) {
859                 my $data;
860                 while ( $fh->read(\$data, 4 * 65536) > 0 ) {
861                     $fio->{rxDigest}->add($data);
862                     $fio->{rxSize} += length($data);
863                 }
864                 $fh->close;
865             } else {
866                 $fio->log("Can't open $attr->{fullPath} for MD4 check ($name)");
867                 $fio->{stats}{errorCnt}++;
868             }
869         }
870         $fio->log("$name got exact match")
871                         if ( $fio->{logLevel} >= 5 );
872     }
873     close($fio->{rxInFd})  if ( defined($fio->{rxInFd}) );
874     unlink("$fio->{outDirSh}RStmp") if  ( -f "$fio->{outDirSh}RStmp" );
875     my $newDigest = $fio->{rxDigest}->digest;
876     if ( $fio->{logLevel} >= 3 ) {
877         my $md4Str = unpack("H*", $md4);
878         my $newStr = unpack("H*", $newDigest);
879         $fio->log("$name got digests $md4Str vs $newStr")
880     }
881     if ( $md4 ne $newDigest ) {
882         $fio->log("$name: fatal error: md4 doesn't match");
883         $fio->{stats}{errorCnt}++;
884         if ( defined($fio->{rxOutFd}) ) {
885             $fio->{rxOutFd}->close;
886             unlink($fio->{rxOutFile});
887         }
888         return 1;
889     }
890     #
891     # One special case is an empty file: if the file size is
892     # zero we need to open the output file to create it.
893     #
894     if ( $fio->{rxSize} == 0 ) {
895         my $rxOutFileRel = "$fio->{shareM}/"
896                          . $fio->{bpc}->fileNameMangle($name);
897         my $rxOutFile    = $fio->{outDir} . $rxOutFileRel;
898         $fio->{rxOutFd}  = BackupPC::PoolWrite->new($fio->{bpc},
899                                            $rxOutFile, $fio->{rxSize},
900                                            $fio->{xfer}{compress});
901     }
902     if ( !defined($fio->{rxOutFd}) ) {
903         #
904         # No output file, meaning original was an exact match.
905         #
906         $fio->log("$name: nothing to do")
907                         if ( $fio->{logLevel} >= 5 );
908         my $attr = $fio->{rxLocalAttr};
909         my $f = $fio->{rxFile};
910         $fio->logFileAction("same", $f) if ( $fio->{logLevel} >= 1 );
911         if ( $fio->{full}
912                 || $attr->{type}  != $f->{type}
913                 || $attr->{mtime} != $f->{mtime}
914                 || $attr->{size}  != $f->{size}
915                 || $attr->{gid}   != $f->{gid}
916                 || $attr->{mode}  != $f->{mode} ) {
917             #
918             # In the full case, or if the attributes are different,
919             # we need to make a link from the previous file and
920             # set the attributes.
921             #
922             my $rxOutFile = $fio->{outDirSh}
923                             . $fio->{bpc}->fileNameMangle($name);
924             if ( !link($attr->{fullPath}, $rxOutFile) ) {
925                 $fio->log("Unable to link $attr->{fullPath} to $rxOutFile");
926                 $fio->{stats}{errorCnt}++;
927                 return -1;
928             }
929             #
930             # Cumulate the stats
931             #
932             $fio->{stats}{TotalFileCnt}++;
933             $fio->{stats}{TotalFileSize} += $fio->{rxSize};
934             $fio->{stats}{ExistFileCnt}++;
935             $fio->{stats}{ExistFileSize} += $fio->{rxSize};
936             $fio->{stats}{ExistFileCompSize} += -s $rxOutFile;
937             $fio->{rxFile}{size} = $fio->{rxSize};
938             return $fio->attribSet($fio->{rxFile});
939         }
940     }
941     if ( defined($fio->{rxOutFd}) ) {
942         my $exist = $fio->processClose($fio->{rxOutFd},
943                                        $fio->{rxOutFileRel},
944                                        $fio->{rxSize}, 1);
945         $fio->logFileAction($exist ? "pool" : "create", $fio->{rxFile})
946                             if ( $fio->{logLevel} >= 1 );
947         $fio->{rxFile}{size} = $fio->{rxSize};
948         return $fio->attribSet($fio->{rxFile});
949     }
950     delete($fio->{rxDigest});
951     delete($fio->{rxInData});
952     return;
953 }
954
955 #
956 # Callback function for BackupPC::View->find.  Note the order of the
957 # first two arguments.
958 #
959 sub fileListEltSend
960 {
961     my($a, $fio, $fList, $outputFunc) = @_;
962     my $name = $a->{relPath};
963     my $n = $name;
964     my $type = $fio->mode2type($a->{mode});
965     my $extraAttribs = {};
966
967     $n =~ s/^\Q$fio->{xfer}{pathHdrSrc}//;
968     $fio->log("Sending $name (remote=$n)") if ( $fio->{logLevel} >= 4 );
969     if ( $type == BPC_FTYPE_CHARDEV
970             || $type == BPC_FTYPE_BLOCKDEV
971             || $type == BPC_FTYPE_SYMLINK ) {
972         my $fh = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
973         my($str, $rdSize);
974         if ( defined($fh) ) {
975             $rdSize = $fh->read(\$str, $a->{size} + 1024);
976             if ( $type == BPC_FTYPE_SYMLINK ) {
977                 #
978                 # Reconstruct symbolic link
979                 #
980                 $extraAttribs = { link => $str };
981                 if ( $rdSize != $a->{size} ) {
982                     # ERROR
983                     $fio->log("$name: can't read exactly $a->{size} bytes");
984                     $fio->{stats}{errorCnt}++;
985                 }
986             } elsif ( $str =~ /(\d*),(\d*)/ ) {
987                 #
988                 # Reconstruct char or block special major/minor device num
989                 #
990                 # Note: char/block devices have $a->{size} = 0, so we
991                 # can't do an error check on $rdSize.
992                 #
993                 $extraAttribs = { rdev => $1 * 256 + $2 };
994             } else {
995                 $fio->log("$name: unexpected special file contents $str");
996                 $fio->{stats}{errorCnt}++;
997             }
998             $fh->close;
999         } else {
1000             # ERROR
1001             $fio->log("$name: can't open");
1002             $fio->{stats}{errorCnt}++;
1003         }
1004     }
1005     my $f = {
1006             name  => $n,
1007             #dev   => 0,                # later, when we support hardlinks
1008             #inode => 0,                # later, when we support hardlinks
1009             mode  => $a->{mode},
1010             uid   => $a->{uid},
1011             gid   => $a->{gid},
1012             mtime => $a->{mtime},
1013             size  => $a->{size},
1014             %$extraAttribs,
1015     };
1016     $fList->encode($f);
1017     $f->{name} = "$fio->{xfer}{pathHdrDest}/$f->{name}";
1018     $f->{name} =~ s{//+}{/}g;
1019     $fio->logFileAction("restore", $f) if ( $fio->{logLevel} >= 1 );
1020     &$outputFunc($fList->encodeData);
1021     #
1022     # Cumulate stats
1023     #
1024     if ( $type != BPC_FTYPE_DIR ) {
1025         $fio->{stats}{TotalFileCnt}++;
1026         $fio->{stats}{TotalFileSize} += $a->{size};
1027     }
1028 }
1029
1030 sub fileListSend
1031 {
1032     my($fio, $flist, $outputFunc) = @_;
1033
1034     #
1035     # Populate the file list with the files requested by the user.
1036     # Since some might be directories so we call BackupPC::View::find.
1037     #
1038     $fio->log("fileListSend: sending file list: "
1039              . join(" ", @{$fio->{fileList}})) if ( $fio->{logLevel} >= 4 );
1040     foreach my $name ( @{$fio->{fileList}} ) {
1041         $fio->{view}->find($fio->{xfer}{bkupSrcNum},
1042                            $fio->{xfer}{bkupSrcShare},
1043                            $name, 1,
1044                            \&fileListEltSend, $fio, $flist, $outputFunc);
1045     }
1046 }
1047
1048 sub finish
1049 {
1050     my($fio, $isChild) = @_;
1051
1052     #
1053     # Flush the attributes if this is the child
1054     #
1055     $fio->attribWrite(undef);
1056 }
1057
1058 #sub is_tainted
1059 #{
1060 #    return ! eval {
1061 #        join('',@_), kill 0;
1062 #        1;
1063 #    };
1064 #}
1065
1066 1;