* Support for rsync and rsyncd. Changes to BackupPC_dump and new
[BackupPC.git] / bin / BackupPC_dump
1 #!/bin/perl -T
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_dump: Dump a single PC.
5 #
6 # DESCRIPTION
7 #
8 #   Usage: BackupPC_dump [-i] [-f] [-d] [-e] <host>
9 #
10 #   Flags:
11 #
12 #     -i   Do an incremental dump, overriding any scheduling (but a full
13 #          dump will be done if no dumps have yet succeeded)
14 #
15 #     -f   Do a full dump, overriding any scheduling.
16 #
17 #     -d   Host is a DHCP pool address, so initially we have no
18 #          idea which machine this actually is.  BackupPC_dump
19 #          determines the actual PC host name by using the NetBios
20 #          name.
21 #
22 #     -e   Just do an dump expiry check for the host.  Don't do anything else.  #          This is used periodically by BackupPC to make sure that dhcp hosts
23 #          have correctly expired old backups.  Without this, dhcp hosts that
24 #          are no longer on the network will not expire old backups.
25 #
26 #   BackupPC_dump is run periodically by BackupPC to backup $host.
27 #   The file $TopDir/pc/$host/backups is read to decide whether a
28 #   full or incremental backup needs to be run.  If no backup is
29 #   scheduled, or a ping to $host fails, then BackupPC_dump quits.
30 #
31 #   The backup is done using the selected XferMethod (smb, tar, rsync etc),
32 #   extracting the dump into $TopDir/pc/$host/new.  The xfer output is
33 #   put into $TopDir/pc/$host/XferLOG.
34 #
35 #   If the dump succeeds (based on parsing the output of the XferMethod):
36 #     - $TopDir/pc/$host/new is renamed to $TopDir/pc/$host/nnn, where
37 #           nnn is the next sequential dump number.
38 #     - $TopDir/pc/$host/XferLOG is renamed to $TopDir/pc/$host/XferLOG.nnn.
39 #     - $TopDir/pc/$host/backups is updated.
40 #
41 #   If the dump fails:
42 #     - $TopDir/pc/$host/new is moved to $TopDir/trash for later removal.
43 #     - $TopDir/pc/$host/XferLOG is renamed to $TopDir/pc/$host/XferLOG.bad
44 #           for later viewing.
45 #
46 #   BackupPC_dump communicates to BackupPC via printing to STDOUT.
47 #
48 # AUTHOR
49 #   Craig Barratt  <cbarratt@users.sourceforge.net>
50 #
51 # COPYRIGHT
52 #   Copyright (C) 2001  Craig Barratt
53 #
54 #   This program is free software; you can redistribute it and/or modify
55 #   it under the terms of the GNU General Public License as published by
56 #   the Free Software Foundation; either version 2 of the License, or
57 #   (at your option) any later version.
58 #
59 #   This program is distributed in the hope that it will be useful,
60 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
61 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
62 #   GNU General Public License for more details.
63 #
64 #   You should have received a copy of the GNU General Public License
65 #   along with this program; if not, write to the Free Software
66 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
67 #
68 #========================================================================
69 #
70 # Version 1.6.0_CVS, released 10 Dec 2002.
71 #
72 # See http://backuppc.sourceforge.net.
73 #
74 #========================================================================
75
76 use strict;
77 use lib "/usr/local/BackupPC/lib";
78 use BackupPC::Lib;
79 use BackupPC::FileZIO;
80 use BackupPC::Xfer::Smb;
81 use BackupPC::Xfer::Tar;
82 use BackupPC::Xfer::Rsync;
83 use File::Path;
84 use Getopt::Std;
85
86 ###########################################################################
87 # Initialize
88 ###########################################################################
89
90 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
91 my $TopDir = $bpc->TopDir();
92 my $BinDir = $bpc->BinDir();
93 my %Conf   = $bpc->Conf();
94
95 $bpc->ChildInit();
96
97 my %opts;
98 getopts("defi", \%opts);
99 if ( @ARGV != 1 ) {
100     print("usage: $0 [-d] [-e] [-f] [-i] <host>\n");
101     exit(1);
102 }
103 if ( $ARGV[0] !~ /^([\w\.-]+)$/ ) {
104     print("$0: bad host name '$ARGV[0]'\n");
105     exit(1);
106 }
107 my $hostIP = $1;
108 my($host, $user);
109
110 if ( $opts{d} ) {
111     #
112     # The host name $hostIP is simply a DHCP address.  We need to check
113     # if there is any machine at this address, and if so, get the actual
114     # host name via NetBios using nmblookup.
115     #
116     exit(1) if ( $bpc->CheckHostAlive($hostIP) < 0 );
117     ($host, $user) = $bpc->NetBiosInfoGet($hostIP);
118     exit(1) if ( $host !~ /^([\w\.-]+)$/ );
119     my $hosts = $bpc->HostInfoRead($host);
120     exit(1) if ( !defined($hosts->{$host}) );
121 } else {
122     $host = $hostIP;
123 }
124
125 my $Dir     = "$TopDir/pc/$host";
126 my $xferPid = -1;
127 my $tarPid  = -1;
128
129 #
130 # Re-read config file, so we can include the PC-specific config
131 #
132 if ( defined(my $error = $bpc->ConfigRead($host)) ) {
133     print("Can't read PC's config file: $error\n");
134     exit(1);
135 }
136 %Conf = $bpc->Conf();
137
138 #
139 # Catch various signals
140 #
141 $SIG{INT}  = \&catch_signal;
142 $SIG{ALRM} = \&catch_signal;
143 $SIG{TERM} = \&catch_signal;
144
145 #
146 # Make sure we eventually timeout if there is no activity from
147 # the data transport program.
148 #
149 alarm($Conf{SmbClientTimeout});
150
151 mkpath($Dir, 0, 0777) if ( !-d $Dir );
152 if ( !-f "$Dir/LOCK" ) {
153     open(LOCK, ">$Dir/LOCK") && close(LOCK);
154 }
155 open(LOG, ">>$Dir/LOG");
156 select(LOG); $| = 1; select(STDOUT);
157
158 ###########################################################################
159 # Figure out what to do and do it
160 ###########################################################################
161
162 #
163 # For the -e option we just expire backups and quit
164 #
165 if ( $opts{e} ) {
166     BackupExpire($host);
167     exit(0);
168 }
169
170 #
171 # See if we should skip this host during a certain range
172 # of times.
173 #
174 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
175 if ( $err ne "" ) {
176     print("Can't connect to server ($err)\n");
177     print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
178     exit(1);
179 }
180 my $reply = $bpc->ServerMesg("status host($host)");
181 $reply = $1 if ( $reply =~ /(.*)/s );
182 my(%StatusHost);
183 eval($reply);
184 $bpc->ServerDisconnect();
185
186 #
187 # For DHCP tell BackupPC which host this is
188 #
189 if ( $opts{d} ) {
190     if ( $StatusHost{activeJob} ) {
191         # oops, something is already running for this host
192         exit(0);
193     }
194     print("DHCP $hostIP $host\n");
195 }
196
197 my($needLink, @Backups, $type, $lastBkupNum, $lastFullBkupNum);
198 my $lastFull = 0;
199 my $lastIncr = 0;
200
201 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
202         || $Conf{FullPeriod} == -2 ) {
203     NothingToDo($needLink);
204 }
205
206 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
207              && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
208     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
209     my($currHours) = $hour + $min / 60 + $sec / 3600;
210     if ( $Conf{BlackoutHourBegin} <= $currHours
211               && $currHours <= $Conf{BlackoutHourEnd}
212               && grep($_ == $wday, @{$Conf{BlackoutWeekDays}}) ) {
213 #        print(LOG $bpc->timeStamp, "skipping because of blackout"
214 #                    . " (alive $StatusHost{aliveCnt} times)\n");
215         NothingToDo($needLink);
216     }
217 }
218
219 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
220     printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
221                 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
222     NothingToDo($needLink);
223 }
224
225 #
226 # Now see if there are any old backups we should delete
227 #
228 BackupExpire($host);
229
230 #
231 # Read Backup information, and find times of the most recent full and
232 # incremental backups
233 #
234 @Backups = $bpc->BackupInfoRead($host);
235 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
236     $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
237                         || -f "$Dir/NewFileList.$Backups[$i]{num}" );
238     $lastBkupNum = $Backups[$i]{num};
239     if ( $Backups[$i]{type} eq "full" ) {
240         if ( $lastFull < $Backups[$i]{startTime} ) {
241             $lastFull = $Backups[$i]{startTime};
242             $lastFullBkupNum = $Backups[$i]{num};
243         }
244     } else {
245         $lastIncr = $Backups[$i]{startTime}
246                 if ( $lastIncr < $Backups[$i]{startTime} );
247     }
248 }
249
250 #
251 # Decide whether we do nothing, or a full or incremental backup.
252 #
253 if ( @Backups == 0
254         || $opts{f}
255         || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
256             && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
257     $type = "full";
258 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
259         && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
260     $type = "incr";
261 } else {
262     NothingToDo($needLink);
263 }
264
265 #
266 # Check if $host is alive
267 #
268 my $delay = $bpc->CheckHostAlive($hostIP);
269 if ( $delay < 0 ) {
270     print(LOG $bpc->timeStamp, "no ping response\n");
271     print("no ping response\n");
272     print("link $host\n") if ( $needLink );
273     exit(1);
274 } elsif ( $delay > $Conf{PingMaxMsec} ) {
275     printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
276     printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
277                     $delay, $Conf{PingMaxMsec});
278     print("link $host\n") if ( $needLink );
279     exit(1);
280 }
281
282 #
283 # Make sure it is really the machine we expect (only for fixed addresses,
284 # since we got the DHCP address above).
285 #
286 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
287     print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
288     print("dump failed: $errMsg\n");
289     exit(1);
290 } elsif ( $opts{d} ) {
291     print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
292 }
293
294 #
295 # Get a clean directory $Dir/new
296 #
297 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
298
299 #
300 # Setup file extension for compression and open XferLOG output file
301 #
302 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
303 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
304 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
305                                      $Conf{CompressLevel});
306 if ( !defined($XferLOG) ) {
307     print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
308                              . " $Dir/XferLOG$fileExt\n");
309     print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
310     exit(1);
311 }
312 unlink("$Dir/NewFileList");
313 my $startTime = time();
314
315 my $tarErrs       = 0;
316 my $nFilesExist   = 0;
317 my $sizeExist     = 0;
318 my $sizeExistComp = 0;
319 my $nFilesTotal   = 0;
320 my $sizeTotal     = 0;
321 my($logMsg, %stat, $xfer, $ShareNames);
322 my $newFilesFH;
323
324 if ( $Conf{XferMethod} eq "tar" ) {
325     $ShareNames = $Conf{TarShareName};
326 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
327     $ShareNames = $Conf{RsyncShareName};
328 } else {
329     $ShareNames = $Conf{SmbShareName};
330 }
331
332 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
333
334 #
335 # Now backup each of the shares
336 #
337 for my $shareName ( @$ShareNames ) {
338     local(*RH, *WH);
339
340     $stat{xferOK} = $stat{hostAbort} = undef;
341     $stat{hostError} = $stat{lastOutputLine} = undef;
342     if ( -d "$Dir/new/$shareName" ) {
343         print(LOG $bpc->timeStamp,
344                   "unexpected repeated share name $shareName skipped\n");
345         next;
346     }
347
348     if ( $Conf{XferMethod} eq "tar" ) {
349         #
350         # Use tar (eg: tar/ssh) as the transport program.
351         #
352         $xfer = BackupPC::Xfer::Tar->new($bpc);
353     } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
354         #
355         # Use rsync as the transport program.
356         #
357         if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
358             print(LOG $bpc->timeStamp,
359                         "dump failed: File::RsyncP module is not installed\n");
360             print("dump failed: Rsync module is not installed\n");
361             exit(1);
362         }
363     } else {
364         #
365         # Default is to use smbclient (smb) as the transport program.
366         #
367         $xfer = BackupPC::Xfer::Smb->new($bpc);
368     }
369     my $useTar = $xfer->useTar;
370
371     if ( $useTar ) {
372         #
373         # This xfer method outputs a tar format file, so we start a
374         # BackupPC_tarExtract to extract the data.
375         #
376         # Create a pipe to connect the Xfer method to BackupPC_tarExtract
377         # WH is the write handle for writing, provided to the transport
378         # program, and RH is the other end of the pipe for reading,
379         # provided to BackupPC_tarExtract.
380         #
381         pipe(RH, WH);
382
383         #
384         # fork a child for BackupPC_tarExtract.  TAR is a file handle
385         # on which we (the parent) read the stdout & stderr from
386         # BackupPC_tarExtract.
387         #
388         if ( !defined($tarPid = open(TAR, "-|")) ) {
389             print(LOG $bpc->timeStamp, "can't fork to run tar\n");
390             print("can't fork to run tar\n");
391             close(RH);
392             close(WH);
393             last;
394         }
395         if ( !$tarPid ) {
396             #
397             # This is the tar child.  Close the write end of the pipe,
398             # clone STDERR to STDOUT, clone STDIN from RH, and then
399             # exec BackupPC_tarExtract.
400             #
401             setpgrp 0,0;
402             close(WH);
403             close(STDERR);
404             open(STDERR, ">&STDOUT");
405             close(STDIN);
406             open(STDIN, "<&RH");
407             exec("$BinDir/BackupPC_tarExtract '$host' '$shareName'"
408                  . " $Conf{CompressLevel}");
409             print(LOG $bpc->timeStamp,
410                         "can't exec $BinDir/BackupPC_tarExtract\n");
411             exit(0);
412         }
413     } elsif ( !defined($newFilesFH) ) {
414         #
415         # We need to create the NewFileList output file
416         #
417         local(*NEW_FILES);
418         open(NEW_FILES, ">$TopDir/pc/$host/NewFileList")
419                      || die("can't open $TopDir/pc/$host/NewFileList");
420         $newFilesFH = *NEW_FILES;
421     }
422
423     #
424     # Run the transport program
425     #
426     $xfer->args({
427         host        => $host,
428         hostIP      => $hostIP,
429         shareName   => $shareName,
430         pipeRH      => *RH,
431         pipeWH      => *WH,
432         XferLOG     => $XferLOG,
433         newFilesFH  => $newFilesFH,
434         outDir      => $Dir,
435         type        => $type,
436         lastFull    => $lastFull,
437         lastBkupNum => $lastBkupNum,
438         lastFullBkupNum => $lastFullBkupNum,
439         backups     => \@Backups,
440         compress    => $Conf{CompressLevel},
441         XferMethod  => => $Conf{XferMethod},
442     });
443
444     if ( !defined($logMsg = $xfer->start()) ) {
445         print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
446         print("dump failed: ", $xfer->errStr, "\n");
447         print("link $host\n") if ( $needLink );
448         #
449         # kill off the tar process, first nicely then forcefully
450         #
451         if ( $tarPid > 0 ) {
452             kill(2, $tarPid);
453             sleep(1);
454             kill(9, $tarPid);
455         }
456         exit(1);
457     }
458
459     $xferPid = $xfer->xferPid;
460     if ( $useTar ) {
461         #
462         # The parent must close both handles on the pipe since the children
463         # are using these handles now.
464         #
465         close(RH);
466         close(WH);
467         print(LOG $bpc->timeStamp, $logMsg,
468                                    " (xferPid=$xferPid, tarPid=$tarPid)\n");
469     } elsif ( $xferPid > 0 ) {
470         print(LOG $bpc->timeStamp, $logMsg, " (xferPid=$xferPid)\n");
471     } else {
472         print(LOG $bpc->timeStamp, $logMsg, "\n");
473     }
474     print("started $type dump, pid=$xferPid, tarPid=$tarPid,"
475             . " share=$shareName\n");
476
477     if ( $useTar || $xferPid > 0 ) {
478         #
479         # Parse the output of the transfer program and BackupPC_tarExtract
480         # while they run.  Since we might be reading from two or more children
481         # we use a select.
482         #
483         my($FDread, $tarOut, $mesg);
484         vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
485         $xfer->setSelectMask(\$FDread);
486
487         SCAN: while ( 1 ) {
488             my $ein = $FDread;
489             last if ( $FDread =~ /^\0*$/ );
490             select(my $rout = $FDread, undef, $ein, undef);
491             if ( $useTar ) {
492                 if ( vec($rout, fileno(TAR), 1) ) {
493                     if ( sysread(TAR, $mesg, 8192) <= 0 ) {
494                         vec($FDread, fileno(TAR), 1) = 0;
495                         close(TAR);
496                     } else {
497                         $tarOut .= $mesg;
498                     }
499                 }
500                 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
501                     $_ = $1;
502                     $tarOut = $2;
503                     $XferLOG->write(\"tarExtract: $_\n");
504                     if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
505                         $tarErrs       = $1;
506                         $nFilesExist   = $2;
507                         $sizeExist     = $3;
508                         $sizeExistComp = $4;
509                         $nFilesTotal   = $5;
510                         $sizeTotal     = $6;
511                     }
512                 }
513             }
514             last if ( !$xfer->readOutput(\$FDread, $rout) );
515             while ( my $str = $xfer->logMsgGet ) {
516                 print(LOG $bpc->timeStamp, "xfer: $str\n");
517             }
518             if ( $xfer->getStats->{fileCnt} == 1 ) {
519                 #
520                 # Make sure it is still the machine we expect.  We do this while
521                 # the transfer is running to avoid a potential race condition if
522                 # the ip address was reassigned by dhcp just before we started
523                 # the transfer.
524                 #
525                 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
526                     $stat{hostError} = $errMsg;
527                     last SCAN;
528                 }
529             }
530         }
531     } else {
532         #
533         # otherwise the xfer module does everything for us
534         #
535         ($tarErrs, $nFilesExist, $sizeExist, $sizeExistComp,
536             $nFilesTotal, $sizeTotal) = $xfer->run();
537     }
538
539     #
540     # Merge the xfer status (need to accumulate counts)
541     #
542     my $newStat = $xfer->getStats;
543     foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
544         next if ( !defined($newStat->{$k}) );
545         if ( $k =~ /Cnt$/ ) {
546             $stat{$k} += $newStat->{$k};
547             delete($newStat->{$k});
548             next;
549         }
550         if ( !defined($stat{$k}) ) {
551             $stat{$k} = $newStat->{$k};
552             delete($newStat->{$k});
553             next;
554         }
555     }
556     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
557     if ( !$stat{xferOK} ) {
558         #
559         # kill off the tranfer program, first nicely then forcefully
560         #
561         if ( $xferPid > 0 ) {
562             kill(2, $xferPid);
563             sleep(1);
564             kill(9, $xferPid);
565         }
566         #
567         # kill off the tar process, first nicely then forcefully
568         #
569         if ( $tarPid > 0 ) {
570             kill(2, $tarPid);
571             sleep(1);
572             kill(9, $tarPid);
573         }
574         #
575         # don't do any more shares on this host
576         #
577         last;
578     }
579 }
580 $XferLOG->close();
581 close($newFilesFH) if ( defined($newFilesFH) );
582
583 my $lastNum  = -1;
584
585 #
586 # Do one last check to make sure it is still the machine we expect.
587 #
588 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
589     $stat{hostError} = $errMsg;
590     $stat{xferOK} = 0;
591 }
592 if ( $stat{xferOK} ) {
593     @Backups = $bpc->BackupInfoRead($host);
594     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
595         $lastNum = $Backups[$i]{num} if ( $lastNum < $Backups[$i]{num} );
596     }
597     $lastNum++;
598     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$lastNum")
599                                 if ( -d "$Dir/$lastNum" );
600     if ( !rename("$Dir/new", "$Dir/$lastNum") ) {
601         print(LOG $bpc->timeStamp,
602                   "Rename $Dir/new -> $Dir/$lastNum failed\n");
603         $stat{xferOK} = 0;
604     }
605     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$lastNum$fileExt");
606     rename("$Dir/NewFileList", "$Dir/NewFileList.$lastNum");
607 }
608 my $endTime = time();
609
610 #
611 # If the dump failed, clean up
612 #
613 if ( !$stat{xferOK} ) {
614     #
615     # wait a short while and see if the system is still alive
616     #
617     $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
618     if ( $stat{hostError} ) {
619         print(LOG $bpc->timeStamp,
620                   "Got fatal error during xfer ($stat{hostError})\n");
621     }
622     sleep(10);
623     if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
624         $stat{hostAbort} = 1;
625     }
626     if ( $stat{hostAbort} ) {
627         $stat{hostError} = "lost network connection during backup";
628     }
629     print(LOG $bpc->timeStamp, "Dump aborted ($stat{hostError})\n");
630     unlink("$Dir/timeStamp.level0");
631     unlink("$Dir/SmbLOG.bad");
632     unlink("$Dir/SmbLOG.bad$fileExt");
633     unlink("$Dir/XferLOG.bad");
634     unlink("$Dir/XferLOG.bad$fileExt");
635     unlink("$Dir/NewFileList");
636     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
637     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
638     print("dump failed: $stat{hostError}\n");
639     print("link $host\n") if ( $needLink );
640     exit(1);
641 }
642
643 #
644 # Add the new backup information to the backup file
645 #
646 @Backups = $bpc->BackupInfoRead($host);
647 my $i = @Backups;
648 $Backups[$i]{num}           = $lastNum;
649 $Backups[$i]{type}          = $type;
650 $Backups[$i]{startTime}     = $startTime;
651 $Backups[$i]{endTime}       = $endTime;
652 $Backups[$i]{size}          = $sizeTotal;
653 $Backups[$i]{nFiles}        = $nFilesTotal;
654 $Backups[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
655 $Backups[$i]{xferBadFile}   = $stat{xferBadFileCnt} || 0;
656 $Backups[$i]{xferBadShare}  = $stat{xferBadShareCnt} || 0;
657 $Backups[$i]{nFilesExist}   = $nFilesExist;
658 $Backups[$i]{sizeExist}     = $sizeExist;
659 $Backups[$i]{sizeExistComp} = $sizeExistComp;
660 $Backups[$i]{tarErrs}       = $tarErrs;
661 $Backups[$i]{compress}      = $Conf{CompressLevel};
662 $Backups[$i]{noFill}        = $type eq "full" ? 0 : 1;
663 $Backups[$i]{mangle}        = 1;        # name mangling always on for v1.04+
664 $bpc->BackupInfoWrite($host, @Backups);
665
666 unlink("$Dir/timeStamp.level0");
667
668 #
669 # Now remove the bad files, replacing them if possible with links to
670 # earlier backups.
671 #
672 foreach my $file ( $xfer->getBadFiles ) {
673     my $j;
674     unlink("$Dir/$lastNum/$file");
675     for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
676         next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
677         if ( !link("$Dir/$Backups[$j]{num}/$file", "$Dir/$lastNum/$file") ) {
678             print(LOG $bpc->timeStamp,
679                       "Unable to link $lastNum/$file to"
680                     . " $Backups[$j]{num}/$file\n");
681         } else {
682             print(LOG $bpc->timeStamp,
683                       "Bad file $lastNum/$file replaced by link to"
684                     . " $Backups[$j]{num}/$file\n");
685         }
686         last;
687     }
688     if ( $j < 0 ) {
689         print(LOG $bpc->timeStamp,
690                   "Removed bad file $lastNum/$file (no older"
691                 . " copy to link to)\n");
692     }
693 }
694
695 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
696                                    - $stat{xferBadShareCnt};
697 print(LOG $bpc->timeStamp,
698           "$type backup $lastNum complete, $stat{fileCnt} files,"
699         . " $stat{byteCnt} bytes,"
700         . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
701         . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
702
703 BackupExpire($host);
704
705 print("$type backup complete\n");
706
707 ###########################################################################
708 # Subroutines
709 ###########################################################################
710
711 sub NothingToDo
712 {
713     my($needLink) = @_;
714
715     print("nothing to do\n");
716     print("link $host\n") if ( $needLink );
717     exit(0);
718 }
719
720 sub catch_signal
721 {
722     my $signame = shift;
723     my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
724
725     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
726     $XferLOG->write(\"exiting after signal $signame\n");
727     $XferLOG->close();
728     if ( $xferPid > 0 ) {
729         if ( kill(2, $xferPid) <= 0 ) {
730             sleep(1);
731             kill(9, $xferPid);
732         }
733     }
734     if ( $tarPid > 0 ) {
735         if ( kill(2, $tarPid) <= 0 ) {
736             sleep(1);
737             kill(9, $tarPid);
738         }
739     }
740     unlink("$Dir/timeStamp.level0");
741     unlink("$Dir/NewFileList");
742     unlink("$Dir/XferLOG.bad");
743     unlink("$Dir/XferLOG.bad$fileExt");
744     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
745     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
746     if ( $signame eq "INT" ) {
747         print("dump failed: aborted by user (signal=$signame)\n");
748     } else {
749         print("dump failed: received signal=$signame\n");
750     }
751     print("link $host\n") if ( $needLink );
752     exit(1);
753 }
754
755 #
756 # Decide which old backups should be expired by moving them
757 # to $TopDir/trash.
758 #
759 sub BackupExpire
760 {
761     my($host) = @_;
762     my($Dir) = "$TopDir/pc/$host";
763     my(@Backups) = $bpc->BackupInfoRead($host);
764     my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
765
766     while ( 1 ) {
767         $cntFull = $cntIncr = 0;
768         $oldestIncr = $oldestFull = 0;
769         for ( $i = 0 ; $i < @Backups ; $i++ ) {
770             if ( $Backups[$i]{type} eq "full" ) {
771                 $firstFull = $i if ( $cntFull == 0 );
772                 $cntFull++;
773             } else {
774                 $firstIncr = $i if ( $cntIncr == 0 );
775                 $cntIncr++;
776             }
777         }
778         $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
779                         if ( $cntIncr > 0 );
780         $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
781                         if ( $cntFull > 0 );
782         if ( $cntIncr > $Conf{IncrKeepCnt}
783                 || ($cntIncr > $Conf{IncrKeepCntMin}
784                     && $oldestIncr > $Conf{IncrAgeMax})
785                && (@Backups <= $firstIncr + 1
786                         || $Backups[$firstIncr]{noFill}
787                         || !$Backups[$firstIncr + 1]{noFill}) ) {
788             #
789             # Only delete an incr backup if the Conf settings are satisfied.
790             # We also must make sure that either this backup is the most
791             # recent one, or it is not filled, or the next backup is filled.
792             # (We can't deleted a filled incr if the next backup is not
793             # filled.)
794             # 
795             print(LOG $bpc->timeStamp,
796                       "removing incr backup $Backups[$firstIncr]{num}\n");
797             $bpc->RmTreeDefer("$TopDir/trash",
798                               "$Dir/$Backups[$firstIncr]{num}");
799             unlink("$Dir/SmbLOG.$Backups[$firstIncr]{num}")
800                         if ( -f "$Dir/SmbLOG.$Backups[$firstIncr]{num}" );
801             unlink("$Dir/SmbLOG.$Backups[$firstIncr]{num}.z")
802                         if ( -f "$Dir/SmbLOG.$Backups[$firstIncr]{num}.z" );
803             unlink("$Dir/XferLOG.$Backups[$firstIncr]{num}")
804                         if ( -f "$Dir/XferLOG.$Backups[$firstIncr]{num}" );
805             unlink("$Dir/XferLOG.$Backups[$firstIncr]{num}.z")
806                         if ( -f "$Dir/XferLOG.$Backups[$firstIncr]{num}.z" );
807             splice(@Backups, $firstIncr, 1);
808         } elsif ( ($cntFull > $Conf{FullKeepCnt}
809                     || ($cntFull > $Conf{FullKeepCntMin}
810                         && $oldestFull > $Conf{FullAgeMax}))
811                && (@Backups <= $firstFull + 1
812                         || !$Backups[$firstFull + 1]{noFill}) ) {
813             #
814             # Only delete a full backup if the Conf settings are satisfied.
815             # We also must make sure that either this backup is the most
816             # recent one, or the next backup is filled.
817             # (We can't deleted a full backup if the next backup is not
818             # filled.)
819             # 
820             print(LOG $bpc->timeStamp,
821                    "removing full backup $Backups[$firstFull]{num}\n");
822             $bpc->RmTreeDefer("$TopDir/trash",
823                               "$Dir/$Backups[$firstFull]{num}");
824             unlink("$Dir/SmbLOG.$Backups[$firstFull]{num}")
825                         if ( -f "$Dir/SmbLOG.$Backups[$firstFull]{num}" );
826             unlink("$Dir/SmbLOG.$Backups[$firstFull]{num}.z")
827                         if ( -f "$Dir/SmbLOG.$Backups[$firstFull]{num}.z" );
828             unlink("$Dir/XferLOG.$Backups[$firstFull]{num}")
829                         if ( -f "$Dir/XferLOG.$Backups[$firstFull]{num}" );
830             unlink("$Dir/XferLOG.$Backups[$firstFull]{num}.z")
831                         if ( -f "$Dir/XferLOG.$Backups[$firstFull]{num}.z" );
832             splice(@Backups, $firstFull, 1);
833         } else {
834             last;
835         }
836     }
837     $bpc->BackupInfoWrite($host, @Backups);
838 }
839
840 sub CorrectHostCheck
841 {
842     my($hostIP, $host) = @_;
843     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} );
844     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
845     return "host $host has mismatching netbios name $netBiosHost"
846             if ( $netBiosHost ne $host );
847     return;
848 }