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