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