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