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