* Added Italian translation, it.pm, from Lorenzo Cappelletti
[BackupPC.git] / bin / BackupPC_dump
1 #!/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_dump: Dump a single client.
5 #
6 # DESCRIPTION
7 #
8 #   Usage: BackupPC_dump [-i] [-f] [-d] [-e] [-v] <client>
9 #
10 #   Flags:
11 #
12 #     -i   Do an incremental dump, overriding any scheduling (but a full
13 #          dump will be done if no dumps have yet succeeded)
14 #
15 #     -f   Do a full dump, overriding any scheduling.
16 #
17 #     -d   Host is a DHCP pool address, and the client argument
18 #          just an IP address.  We lookup the NetBios name from
19 #          the IP address.
20 #
21 #     -e   Just do an dump expiry check for the client.  Don't do anything
22 #          else.  This is used periodically by BackupPC to make sure that
23 #          dhcp hosts have correctly expired old backups.  Without this,
24 #          dhcp hosts that are no longer on the network will not expire
25 #          old backups.
26 #
27 #     -v   verbose.  for manual usage: prints failure reasons in more detail.
28 #
29 #   BackupPC_dump is run periodically by BackupPC to backup $client.
30 #   The file $TopDir/pc/$client/backups is read to decide whether a
31 #   full or incremental backup needs to be run.  If no backup is
32 #   scheduled, or a ping to $client fails, then BackupPC_dump quits.
33 #
34 #   The backup is done using the selected XferMethod (smb, tar, rsync etc),
35 #   extracting the dump into $TopDir/pc/$client/new.  The xfer output is
36 #   put into $TopDir/pc/$client/XferLOG.
37 #
38 #   If the dump succeeds (based on parsing the output of the XferMethod):
39 #     - $TopDir/pc/$client/new is renamed to $TopDir/pc/$client/nnn, where
40 #           nnn is the next sequential dump number.
41 #     - $TopDir/pc/$client/XferLOG is renamed to $TopDir/pc/$client/XferLOG.nnn.
42 #     - $TopDir/pc/$client/backups is updated.
43 #
44 #   If the dump fails:
45 #     - $TopDir/pc/$client/new is moved to $TopDir/trash for later removal.
46 #     - $TopDir/pc/$client/XferLOG is renamed to $TopDir/pc/$client/XferLOG.bad
47 #           for later viewing.
48 #
49 #   BackupPC_dump communicates to BackupPC via printing to STDOUT.
50 #
51 # AUTHOR
52 #   Craig Barratt  <cbarratt@users.sourceforge.net>
53 #
54 # COPYRIGHT
55 #   Copyright (C) 2001-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 8 Feb 2004.
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 my $partialNum;
274
275 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
276         || $Conf{FullPeriod} == -2 ) {
277     NothingToDo($needLink);
278 }
279
280 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
281              && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
282     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
283     my($currHours) = $hour + $min / 60 + $sec / 3600;
284     my $blackout;
285
286     #
287     # Handle backward compatibility with original separate scalar
288     # parameters.
289     #
290     if ( defined($Conf{BlackoutHourBegin}) ) {
291         push(@{$Conf{BlackoutPeriods}},
292              {
293                  hourBegin => $Conf{BlackoutHourBegin},
294                  hourEnd   => $Conf{BlackoutHourEnd},
295                  weekDays  => $Conf{BlackoutWeekDays},
296              }
297         );
298     }
299     foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
300         #
301         # Allow blackout to span midnight (specified by BlackoutHourBegin
302         # being greater than BlackoutHourEnd)
303         #
304         if ( $p->{hourBegin} > $p->{hourEnd} ) {
305             $blackout = $p->{hourBegin} <= $currHours
306                           || $currHours <= $p->{hourEnd};
307             if ( $currHours <= $p->{hourEnd} ) {
308                 #
309                 # This is after midnight, so decrement the weekday for the
310                 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
311                 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
312                 #
313                 $wday--;
314                 $wday += 7 if ( $wday < 0 );
315             }
316         } else {
317             $blackout = $p->{hourBegin} <= $currHours
318                           && $currHours <= $p->{hourEnd};
319         }
320         if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
321 #           print(LOG $bpc->timeStamp, "skipping because of blackout"
322 #                      . " (alive $StatusHost{aliveCnt} times)\n");
323             print(STDERR "Skipping $client because of blackout\n")
324                             if ( $opts{v} );
325             NothingToDo($needLink);
326         }
327     }
328 }
329
330 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
331     printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
332                 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
333     NothingToDo($needLink);
334 }
335
336 #
337 # Now see if there are any old backups we should delete
338 #
339 BackupExpire($client);
340
341 #
342 # Read Backup information, and find times of the most recent full and
343 # incremental backups
344 #
345 @Backups = $bpc->BackupInfoRead($client);
346 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
347     $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
348                         || -f "$Dir/NewFileList.$Backups[$i]{num}" );
349     $lastBkupNum = $Backups[$i]{num};
350     if ( $Backups[$i]{type} eq "full" ) {
351         if ( $lastFull < $Backups[$i]{startTime} ) {
352             $lastFull = $Backups[$i]{startTime};
353             $lastFullBkupNum = $Backups[$i]{num};
354         }
355     } elsif ( $Backups[$i]{type} eq "incr" ) {
356         $lastIncr = $Backups[$i]{startTime}
357                 if ( $lastIncr < $Backups[$i]{startTime} );
358     } elsif ( $Backups[$i]{type} eq "partial" ) {
359         $partialIdx = $i;
360         $partialNum = $Backups[$i]{num};
361     }
362 }
363
364 #
365 # Decide whether we do nothing, or a full or incremental backup.
366 #
367 if ( @Backups == 0
368         || $opts{f}
369         || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
370             && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
371     $type = "full";
372 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
373         && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
374     $type = "incr";
375 } else {
376     NothingToDo($needLink);
377 }
378
379 #
380 # Check if $host is alive
381 #
382 my $delay = $bpc->CheckHostAlive($hostIP);
383 if ( $delay < 0 ) {
384     print(LOG $bpc->timeStamp, "no ping response\n");
385     print("no ping response\n");
386     print("link $clientURI\n") if ( $needLink );
387     exit(1);
388 } elsif ( $delay > $Conf{PingMaxMsec} ) {
389     printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
390     printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
391                     $delay, $Conf{PingMaxMsec});
392     print("link $clientURI\n") if ( $needLink );
393     exit(1);
394 }
395
396 #
397 # Make sure it is really the machine we expect (only for fixed addresses,
398 # since we got the DHCP address above).
399 #
400 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
401     print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
402     print("dump failed: $errMsg\n");
403     exit(1);
404 } elsif ( $opts{d} ) {
405     print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
406 }
407
408 #
409 # Get a clean directory $Dir/new
410 #
411 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
412
413 #
414 # Setup file extension for compression and open XferLOG output file
415 #
416 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
417 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
418 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
419                                      $Conf{CompressLevel});
420 if ( !defined($XferLOG) ) {
421     print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
422                              . " $Dir/XferLOG$fileExt\n");
423     print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
424     exit(1);
425 }
426 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
427 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
428 my $startTime = time();
429
430 my $tarErrs       = 0;
431 my $nFilesExist   = 0;
432 my $sizeExist     = 0;
433 my $sizeExistComp = 0;
434 my $nFilesTotal   = 0;
435 my $sizeTotal     = 0;
436 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
437 my $newFilesFH;
438
439 if ( $Conf{XferMethod} eq "tar" ) {
440     $ShareNames = $Conf{TarShareName};
441 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
442     $ShareNames = $Conf{RsyncShareName};
443 } else {
444     $ShareNames = $Conf{SmbShareName};
445 }
446
447 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
448
449 #
450 # Run an optional pre-dump command
451 #
452 UserCommandRun("DumpPreUserCmd");
453 $NeedPostCmd = 1;
454
455 #
456 # Now backup each of the shares
457 #
458 for my $shareName ( @$ShareNames ) {
459     local(*RH, *WH);
460
461     $stat{xferOK} = $stat{hostAbort} = undef;
462     $stat{hostError} = $stat{lastOutputLine} = undef;
463     if ( -d "$Dir/new/$shareName" ) {
464         print(LOG $bpc->timeStamp,
465                   "unexpected repeated share name $shareName skipped\n");
466         next;
467     }
468
469     if ( $Conf{XferMethod} eq "tar" ) {
470         #
471         # Use tar (eg: tar/ssh) as the transport program.
472         #
473         $xfer = BackupPC::Xfer::Tar->new($bpc);
474     } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
475         #
476         # Use rsync as the transport program.
477         #
478         if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
479             my $errStr = BackupPC::Xfer::Rsync::errStr;
480             print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
481             print("dump failed: $errStr\n");
482             UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
483             exit(1);
484         }
485     } else {
486         #
487         # Default is to use smbclient (smb) as the transport program.
488         #
489         $xfer = BackupPC::Xfer::Smb->new($bpc);
490     }
491
492     my $useTar = $xfer->useTar;
493
494     if ( $useTar ) {
495         #
496         # This xfer method outputs a tar format file, so we start a
497         # BackupPC_tarExtract to extract the data.
498         #
499         # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
500         # WH is the write handle for writing, provided to the transport
501         # program, and RH is the other end of the socket for reading,
502         # provided to BackupPC_tarExtract.
503         #
504         if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
505             shutdown(RH, 1);    # no writing to this socket
506             shutdown(WH, 0);    # no reading from this socket
507             setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
508             setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
509         } else {
510             #
511             # Default to pipe() if socketpair() doesn't work.
512             #
513             pipe(RH, WH);
514         }
515
516         #
517         # fork a child for BackupPC_tarExtract.  TAR is a file handle
518         # on which we (the parent) read the stdout & stderr from
519         # BackupPC_tarExtract.
520         #
521         if ( !defined($tarPid = open(TAR, "-|")) ) {
522             print(LOG $bpc->timeStamp, "can't fork to run tar\n");
523             print("can't fork to run tar\n");
524             close(RH);
525             close(WH);
526             last;
527         }
528         binmode(TAR);
529         if ( !$tarPid ) {
530             #
531             # This is the tar child.  Close the write end of the pipe,
532             # clone STDERR to STDOUT, clone STDIN from RH, and then
533             # exec BackupPC_tarExtract.
534             #
535             setpgrp 0,0;
536             close(WH);
537             close(STDERR);
538             open(STDERR, ">&STDOUT");
539             close(STDIN);
540             open(STDIN, "<&RH");
541             alarm(0);
542             exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
543                          $Conf{CompressLevel});
544             print(LOG $bpc->timeStamp,
545                         "can't exec $BinDir/BackupPC_tarExtract\n");
546             exit(0);
547         }
548     } elsif ( !defined($newFilesFH) ) {
549         #
550         # We need to create the NewFileList output file
551         #
552         local(*NEW_FILES);
553         open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
554                      || die("can't open $TopDir/pc/$client/NewFileList");
555         $newFilesFH = *NEW_FILES;
556         binmode(NEW_FILES);
557     }
558
559     #
560     # Run the transport program
561     #
562     $xfer->args({
563         host        => $host,
564         client      => $client,
565         hostIP      => $hostIP,
566         shareName   => $shareName,
567         pipeRH      => *RH,
568         pipeWH      => *WH,
569         XferLOG     => $XferLOG,
570         newFilesFH  => $newFilesFH,
571         outDir      => $Dir,
572         type        => $type,
573         lastFull    => $lastFull,
574         lastBkupNum => $lastBkupNum,
575         lastFullBkupNum => $lastFullBkupNum,
576         backups     => \@Backups,
577         compress    => $Conf{CompressLevel},
578         XferMethod  => $Conf{XferMethod},
579         pidHandler  => \&pidHandler,
580         partialNum  => $partialNum,
581     });
582
583     if ( !defined($logMsg = $xfer->start()) ) {
584         print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
585         print("dump failed: ", $xfer->errStr, "\n");
586         print("link $clientURI\n") if ( $needLink );
587         #
588         # kill off the tar process, first nicely then forcefully
589         #
590         if ( $tarPid > 0 ) {
591             kill(2, $tarPid);
592             sleep(1);
593             kill(9, $tarPid);
594         }
595         if ( @xferPid ) {
596             kill(2, @xferPid);
597             sleep(1);
598             kill(9, @xferPid);
599         }
600         UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
601         exit(1);
602     }
603
604     @xferPid = $xfer->xferPid;
605
606     if ( $useTar ) {
607         #
608         # The parent must close both handles on the pipe since the children
609         # are using these handles now.
610         #
611         close(RH);
612         close(WH);
613     }
614     print(LOG $bpc->timeStamp, $logMsg, "\n");
615     print("started $type dump, share=$shareName\n");
616
617     pidHandler(@xferPid);
618
619     if ( $useTar ) {
620         #
621         # Parse the output of the transfer program and BackupPC_tarExtract
622         # while they run.  Since we might be reading from two or more children
623         # we use a select.
624         #
625         my($FDread, $tarOut, $mesg);
626         vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
627         $xfer->setSelectMask(\$FDread);
628
629         SCAN: while ( 1 ) {
630             my $ein = $FDread;
631             last if ( $FDread =~ /^\0*$/ );
632             select(my $rout = $FDread, undef, $ein, undef);
633             if ( $useTar ) {
634                 if ( vec($rout, fileno(TAR), 1) ) {
635                     if ( sysread(TAR, $mesg, 8192) <= 0 ) {
636                         vec($FDread, fileno(TAR), 1) = 0;
637                         close(TAR);
638                     } else {
639                         $tarOut .= $mesg;
640                     }
641                 }
642                 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
643                     $_ = $1;
644                     $tarOut = $2;
645                     $XferLOG->write(\"tarExtract: $_\n");
646                     if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
647                         $tarErrs       += $1;
648                         $nFilesExist   += $2;
649                         $sizeExist     += $3;
650                         $sizeExistComp += $4;
651                         $nFilesTotal   += $5;
652                         $sizeTotal     += $6;
653                     }
654                 }
655             }
656             last if ( !$xfer->readOutput(\$FDread, $rout) );
657             while ( my $str = $xfer->logMsgGet ) {
658                 print(LOG $bpc->timeStamp, "xfer: $str\n");
659             }
660             if ( $xfer->getStats->{fileCnt} == 1 ) {
661                 #
662                 # Make sure it is still the machine we expect.  We do this while
663                 # the transfer is running to avoid a potential race condition if
664                 # the ip address was reassigned by dhcp just before we started
665                 # the transfer.
666                 #
667                 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
668                     $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
669                     last SCAN;
670                 }
671             }
672         }
673     } else {
674         #
675         # otherwise the xfer module does everything for us
676         #
677         my @results = $xfer->run();
678         $tarErrs       += $results[0];
679         $nFilesExist   += $results[1];
680         $sizeExist     += $results[2];
681         $sizeExistComp += $results[3];
682         $nFilesTotal   += $results[4];
683         $sizeTotal     += $results[5];
684     }
685
686     #
687     # Merge the xfer status (need to accumulate counts)
688     #
689     my $newStat = $xfer->getStats;
690     if ( $newStat->{fileCnt} == 0 ) {
691        $noFilesErr ||= "No files dumped for share $shareName";
692     }
693     foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
694         next if ( !defined($newStat->{$k}) );
695         if ( $k =~ /Cnt$/ ) {
696             $stat{$k} += $newStat->{$k};
697             delete($newStat->{$k});
698             next;
699         }
700         if ( !defined($stat{$k}) ) {
701             $stat{$k} = $newStat->{$k};
702             delete($newStat->{$k});
703             next;
704         }
705     }
706     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
707     if ( !$stat{xferOK} ) {
708         #
709         # kill off the tranfer program, first nicely then forcefully
710         #
711         if ( @xferPid ) {
712             kill(2, @xferPid);
713             sleep(1);
714             kill(9, @xferPid);
715         }
716         #
717         # kill off the tar process, first nicely then forcefully
718         #
719         if ( $tarPid > 0 ) {
720             kill(2, $tarPid);
721             sleep(1);
722             kill(9, $tarPid);
723         }
724         #
725         # don't do any more shares on this host
726         #
727         last;
728     }
729 }
730
731 #
732 # If this is a full, and any share had zero files then consider the dump bad
733 #
734 if ( $type eq "full" && $stat{hostError} eq ""
735             && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
736     $stat{hostError} = $noFilesErr;
737     $stat{xferOK} = 0;
738 }
739
740 #
741 # Do one last check to make sure it is still the machine we expect.
742 #
743 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
744     $stat{hostError} = $errMsg;
745     $stat{xferOK} = 0;
746 }
747
748 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
749 $XferLOG->close();
750 close($newFilesFH) if ( defined($newFilesFH) );
751
752 my $endTime = time();
753
754 #
755 # If the dump failed, clean up
756 #
757 if ( !$stat{xferOK} ) {
758     #
759     # wait a short while and see if the system is still alive
760     #
761     $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
762     if ( $stat{hostError} ) {
763         print(LOG $bpc->timeStamp,
764                   "Got fatal error during xfer ($stat{hostError})\n");
765     }
766     sleep(10);
767     if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
768         $stat{hostAbort} = 1;
769     }
770     if ( $stat{hostAbort} ) {
771         $stat{hostError} = "lost network connection during backup";
772     }
773     print(LOG $bpc->timeStamp, "Dump aborted ($stat{hostError})\n");
774
775     #
776     # This exits.
777     #
778     BackupFailCleanup();
779 }
780
781 my $newNum = BackupSave();
782
783 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
784                                    - $stat{xferBadShareCnt};
785 print(LOG $bpc->timeStamp,
786           "$type backup $newNum complete, $stat{fileCnt} files,"
787         . " $stat{byteCnt} bytes,"
788         . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
789         . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
790
791 BackupExpire($client);
792
793 print("$type backup complete\n");
794
795 ###########################################################################
796 # Subroutines
797 ###########################################################################
798
799 sub NothingToDo
800 {
801     my($needLink) = @_;
802
803     print("nothing to do\n");
804     print("link $clientURI\n") if ( $needLink );
805     exit(0);
806 }
807
808 sub catch_signal
809 {
810     my $signame = shift;
811
812     #
813     # Children quit quietly on ALRM
814     #
815     exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
816
817     #
818     # Ignore other signals in children
819     #
820     return if ( $Pid != $$ );
821
822     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
823     $SIG{$signame} = 'IGNORE';
824     UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
825     $XferLOG->write(\"exiting after signal $signame\n");
826     $XferLOG->close();
827     if ( @xferPid ) {
828         kill(2, @xferPid);
829         sleep(1);
830         kill(9, @xferPid);
831     }
832     if ( $tarPid > 0 ) {
833         kill(2, $tarPid);
834         sleep(1);
835         kill(9, $tarPid);
836     }
837     if ( $signame eq "INT" ) {
838         $stat{hostError} = "aborted by user (signal=$signame)";
839     } else {
840         $stat{hostError} = "received signal=$signame";
841     }
842     BackupFailCleanup();
843 }
844
845 sub BackupFailCleanup
846 {
847     my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
848
849     if ( $type ne "full" ) {
850 #            || ($nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0) ) {
851         #
852         # No point in saving this dump; get rid of eveything.
853         #
854         unlink("$Dir/timeStamp.level0")    if ( -f "$Dir/timeStamp.level0" );
855         unlink("$Dir/SmbLOG.bad")          if ( -f "$Dir/SmbLOG.bad" );
856         unlink("$Dir/SmbLOG.bad$fileExt")  if ( -f "$Dir/SmbLOG.bad$fileExt" );
857         unlink("$Dir/XferLOG.bad")         if ( -f "$Dir/XferLOG.bad" );
858         unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
859         unlink("$Dir/NewFileList")         if ( -f "$Dir/NewFileList" );
860         rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
861         $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
862         print("dump failed: $stat{hostError}\n");
863         print("link $clientURI\n") if ( $needLink );
864         exit(1);
865     }
866     #
867     # Ok, now we should save this as a partial dump
868     #
869     $type = "partial";
870     my $newNum = BackupSave();
871     print("dump failed: $stat{hostError}\n");
872     print("link $clientURI\n") if ( $needLink );
873     print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
874     exit(2);
875 }
876
877 #
878 # Decide which old backups should be expired by moving them
879 # to $TopDir/trash.
880 #
881 sub BackupExpire
882 {
883     my($client) = @_;
884     my($Dir) = "$TopDir/pc/$client";
885     my(@Backups) = $bpc->BackupInfoRead($client);
886     my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
887
888     if ( $Conf{FullKeepCnt} <= 0 ) {
889         print(LOG $bpc->timeStamp,
890                   "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
891         print(STDERR
892             "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
893                             if ( $opts{v} );
894         return;
895     }
896     while ( 1 ) {
897         $cntFull = $cntIncr = 0;
898         $oldestIncr = $oldestFull = 0;
899         for ( my $i = 0 ; $i < @Backups ; $i++ ) {
900             if ( $Backups[$i]{type} eq "full" ) {
901                 $firstFull = $i if ( $cntFull == 0 );
902                 $cntFull++;
903             } else {
904                 $firstIncr = $i if ( $cntIncr == 0 );
905                 $cntIncr++;
906             }
907         }
908         $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
909                         if ( $cntIncr > 0 );
910         $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
911                         if ( $cntFull > 0 );
912         if ( $cntIncr > $Conf{IncrKeepCnt}
913                 || ($cntIncr > $Conf{IncrKeepCntMin}
914                     && $oldestIncr > $Conf{IncrAgeMax})
915                && (@Backups <= $firstIncr + 1
916                         || $Backups[$firstIncr]{noFill}
917                         || !$Backups[$firstIncr + 1]{noFill}) ) {
918             #
919             # Only delete an incr backup if the Conf settings are satisfied.
920             # We also must make sure that either this backup is the most
921             # recent one, or it is not filled, or the next backup is filled.
922             # (We can't deleted a filled incr if the next backup is not
923             # filled.)
924             # 
925             print(LOG $bpc->timeStamp,
926                       "removing incr backup $Backups[$firstIncr]{num}\n");
927             BackupRemove($client, \@Backups, $firstIncr);
928             next;
929         }
930
931         #
932         # Delete any old full backups, according to $Conf{FullKeepCntMin}
933         # and $Conf{FullAgeMax}.
934         #
935         if ( $cntFull > $Conf{FullKeepCntMin}
936                && $oldestFull > $Conf{FullAgeMax}
937                && (@Backups <= $firstFull + 1
938                         || !$Backups[$firstFull + 1]{noFill}) ) {
939             #
940             # Only delete a full backup if the Conf settings are satisfied.
941             # We also must make sure that either this backup is the most
942             # recent one, or the next backup is filled.
943             # (We can't deleted a full backup if the next backup is not
944             # filled.)
945             # 
946             print(LOG $bpc->timeStamp,
947                    "removing old full backup $Backups[$firstFull]{num}\n");
948             BackupRemove($client, \@Backups, $firstFull);
949             next;
950         }
951
952         #
953         # Do new-style full backup expiry, which includes the the case
954         # where $Conf{FullKeepCnt} is an array.
955         #
956         last if ( !BackupFullExpire($client, \@Backups) );
957     }
958     $bpc->BackupInfoWrite($client, @Backups);
959 }
960
961 #
962 # Handle full backup expiry, using exponential periods.
963 #
964 sub BackupFullExpire
965 {
966     my($client, $Backups) = @_;
967     my $fullCnt = 0;
968     my $fullPeriod = $Conf{FullPeriod};
969     my $origFullPeriod = $fullPeriod;
970     my $fullKeepCnt = $Conf{FullKeepCnt};
971     my $fullKeepIdx = 0;
972     my(@delete, @fullList);
973
974     #
975     # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
976     # not defined - possibly a corrupted config.pl file.
977     #
978     return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
979
980     #
981     # If regular backups are still disabled with $Conf{FullPeriod} < 0,
982     # we still expire backups based on a typical FullPeriod value - weekly.
983     #
984     $fullPeriod = 7 if ( $fullPeriod <= 0 );
985
986     $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
987
988     for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
989         next if ( $Backups->[$i]{type} ne "full" );
990         push(@fullList, $i);
991     }
992     for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
993         my $i = $fullList[$k];
994         my $prevFull = $fullList[$k-1] if ( $k > 0 );
995         #
996         # Don't delete any full that is followed by an unfilled backup,
997         # since it is needed for restore.
998         #
999         my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1000
1001         if ( !$noDelete && 
1002               ($fullKeepIdx >= @$fullKeepCnt
1003               || $k > 0
1004                  && $fullKeepIdx > 0
1005                  && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1006                              < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1007                )
1008             ) {
1009             #
1010             # Delete the full backup
1011             #
1012             #printf("Deleting backup $i ($prevFull)\n");
1013             push(@delete, $i);
1014         } else {
1015             $fullCnt++;
1016             while ( $fullKeepIdx < @$fullKeepCnt
1017                      && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1018                 $fullKeepIdx++;
1019                 $fullCnt = 0;
1020                 $fullPeriod = 2 * $fullPeriod;
1021             }
1022         }
1023     }
1024     #
1025     # Now actually delete the backups
1026     #
1027     for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1028         print(LOG $bpc->timeStamp,
1029                "removing full backup $Backups->[$delete[$i]]{num}\n");
1030         BackupRemove($client, $Backups, $delete[$i]);
1031     }
1032     return @delete;
1033 }
1034
1035 #
1036 # Removes any partial backups
1037 #
1038 sub BackupPartialRemove
1039 {
1040     my($client, $Backups) = @_;
1041
1042     for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1043         next if ( $Backups->[$i]{type} ne "partial" );
1044         BackupRemove($client, $Backups, $i);
1045     }
1046 }
1047
1048 sub BackupSave
1049 {
1050     my @Backups = $bpc->BackupInfoRead($client);
1051     my $num  = -1;
1052
1053     #
1054     # Since we got a good backup we should remove any partial dumps
1055     # (the new backup might also be a partial, but that's ok).
1056     #
1057     BackupPartialRemove($client, \@Backups);
1058
1059     #
1060     # Number the new backup
1061     #
1062     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1063         $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1064     }
1065     $num++;
1066     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num")
1067                                 if ( -d "$Dir/$num" );
1068     if ( !rename("$Dir/new", "$Dir/$num") ) {
1069         print(LOG $bpc->timeStamp,
1070                   "Rename $Dir/new -> $Dir/$num failed\n");
1071         $stat{xferOK} = 0;
1072     }
1073     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1074     rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1075
1076     #
1077     # Add the new backup information to the backup file
1078     #
1079     my $i = @Backups;
1080     $Backups[$i]{num}           = $num;
1081     $Backups[$i]{type}          = $type;
1082     $Backups[$i]{startTime}     = $startTime;
1083     $Backups[$i]{endTime}       = $endTime;
1084     $Backups[$i]{size}          = $sizeTotal;
1085     $Backups[$i]{nFiles}        = $nFilesTotal;
1086     $Backups[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
1087     $Backups[$i]{xferBadFile}   = $stat{xferBadFileCnt} || 0;
1088     $Backups[$i]{xferBadShare}  = $stat{xferBadShareCnt} || 0;
1089     $Backups[$i]{nFilesExist}   = $nFilesExist;
1090     $Backups[$i]{sizeExist}     = $sizeExist;
1091     $Backups[$i]{sizeExistComp} = $sizeExistComp;
1092     $Backups[$i]{tarErrs}       = $tarErrs;
1093     $Backups[$i]{compress}      = $Conf{CompressLevel};
1094     $Backups[$i]{noFill}        = $type eq "incr" ? 1 : 0;
1095     $Backups[$i]{level}         = $type eq "incr" ? 1 : 0;
1096     $Backups[$i]{mangle}        = 1;        # name mangling always on for v1.04+
1097     $bpc->BackupInfoWrite($client, @Backups);
1098
1099     unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1100     foreach my $ext ( qw(bad bad.z) ) {
1101         next if ( !-f "$Dir/XferLOG.$ext" );
1102         unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1103         rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1104     }
1105
1106     #
1107     # Now remove the bad files, replacing them if possible with links to
1108     # earlier backups.
1109     #
1110     foreach my $f ( $xfer->getBadFiles ) {
1111         my $j;
1112         my $shareM = $bpc->fileNameEltMangle($f->{share});
1113         my $fileM  = $bpc->fileNameMangle($f->{file});
1114         unlink("$Dir/$num/$shareM/$fileM");
1115         for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1116             my $file;
1117             if ( $Backups[$j]{mangle} ) {
1118                 $file = "$shareM/$fileM";
1119             } else {
1120                 $file = "$f->{share}/$f->{file}";
1121             }
1122             next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1123             if ( !link("$Dir/$Backups[$j]{num}/$file",
1124                                 "$Dir/$num/$shareM/$fileM") ) {
1125                 print(LOG $bpc->timeStamp,
1126                           "Unable to link $num/$shareM/$fileM to"
1127                         . " $Backups[$j]{num}/$file\n");
1128             } else {
1129                 print(LOG $bpc->timeStamp,
1130                           "Bad file $num/$shareM/$fileM replaced by link to"
1131                         . " $Backups[$j]{num}/$file\n");
1132             }
1133             last;
1134         }
1135         if ( $j < 0 ) {
1136             print(LOG $bpc->timeStamp,
1137                       "Removed bad file $num/$shareM/$fileM (no older"
1138                     . " copy to link to)\n");
1139         }
1140     }
1141     return $num;
1142 }
1143
1144 #
1145 # Removes a specific backup
1146 #
1147 sub BackupRemove
1148 {
1149     my($client, $Backups, $idx) = @_;
1150     my($Dir) = "$TopDir/pc/$client";
1151
1152     $bpc->RmTreeDefer("$TopDir/trash",
1153                       "$Dir/$Backups->[$idx]{num}");
1154     unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1155                 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1156     unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1157                 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1158     unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1159                 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1160     unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1161                 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1162     splice(@{$Backups}, $idx, 1);
1163 }
1164
1165 sub CorrectHostCheck
1166 {
1167     my($hostIP, $host) = @_;
1168     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1169                 || $Conf{NmbLookupCmd} eq "" );
1170     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1171     return "host $host has mismatching netbios name $netBiosHost"
1172                 if ( $netBiosHost ne $host );
1173     return;
1174 }
1175
1176 #
1177 # The Xfer method might tell us from time to time about processes
1178 # it forks.  We tell BackupPC about this (for status displays) and
1179 # keep track of the pids in case we cancel the backup
1180 #
1181 sub pidHandler
1182 {
1183     @xferPid = @_;
1184     @xferPid = grep(/./, @xferPid);
1185     return if ( !@xferPid && $tarPid < 0 );
1186     my @pids = @xferPid;
1187     push(@pids, $tarPid) if ( $tarPid > 0 );
1188     my $str = join(",", @pids);
1189     $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1190     print("xferPids $str\n");
1191 }
1192
1193 #
1194 # Run an optional pre- or post-dump command
1195 #
1196 sub UserCommandRun
1197 {
1198     my($type) = @_;
1199
1200     return if ( !defined($Conf{$type}) );
1201     my $vars = {
1202         xfer       => $xfer,
1203         client     => $client,
1204         host       => $host,
1205         hostIP     => $hostIP,
1206         user       => $Hosts->{$client}{user},
1207         moreUsers  => $Hosts->{$client}{moreUsers},
1208         share      => $ShareNames->[0],
1209         shares     => $ShareNames,
1210         XferMethod => $Conf{XferMethod},
1211         sshPath    => $Conf{SshPath},
1212         LOG        => *LOG,
1213         XferLOG    => $XferLOG,
1214         stat       => \%stat,
1215         xferOK     => $stat{xferOK} || 0,
1216         hostError  => $stat{hostError},
1217         type       => $type,
1218     };
1219     my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
1220     $XferLOG->write(\"Executing $type: @$cmd\n");
1221     #
1222     # Run the user's command, dumping the stdout/stderr into the
1223     # Xfer log file.  Also supply the optional $vars and %Conf in
1224     # case the command is really perl code instead of a shell
1225     # command.
1226     #
1227     $bpc->cmdSystemOrEval($cmd,
1228             sub {
1229                 $XferLOG->write(\$_[0]);
1230             },
1231             $vars, \%Conf);
1232 }