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