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