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