- Large set of changes for config editing, rsync hardlinks etc
[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, released 20 Jun 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 File::Find;
90 use Getopt::Std;
91
92 ###########################################################################
93 # Initialize
94 ###########################################################################
95
96 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
97 my $TopDir = $bpc->TopDir();
98 my $BinDir = $bpc->BinDir();
99 my %Conf   = $bpc->Conf();
100 my $NeedPostCmd;
101 my $Hosts;
102 my $SigName;
103 my $Abort;
104
105 $bpc->ChildInit();
106
107 my %opts;
108 if ( !getopts("defiv", \%opts) || @ARGV != 1 ) {
109     print("usage: $0 [-d] [-e] [-f] [-i] [-v] <client>\n");
110     exit(1);
111 }
112 if ( $ARGV[0] !~ /^([\w\.\s-]+)$/ ) {
113     print("$0: bad client name '$ARGV[0]'\n");
114     exit(1);
115 }
116 my $client = $1;   # BackupPC's client name (might not be real host name)
117 my $hostIP;        # this is the IP address
118 my $host;          # this is the real host name
119
120 my($clientURI, $user);
121
122 $bpc->verbose(1) if ( $opts{v} );
123
124 if ( $opts{d} ) {
125     #
126     # The client name $client is simply a DHCP address.  We need to check
127     # if there is any machine at this address, and if so, get the actual
128     # host name via NetBios using nmblookup.
129     #
130     $hostIP = $client;
131     if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
132         print(STDERR "Exiting because CheckHostAlive($hostIP) failed\n")
133                             if ( $opts{v} );
134         exit(1);
135     }
136     if ( $Conf{NmbLookupCmd} eq "" ) {
137         print(STDERR "Exiting because \$Conf{NmbLookupCmd} is empty\n")
138                             if ( $opts{v} );
139         exit(1);
140     }
141     ($client, $user) = $bpc->NetBiosInfoGet($hostIP);
142     if ( $client !~ /^([\w\.\s-]+)$/ ) {
143         print(STDERR "Exiting because NetBiosInfoGet($hostIP) returned"
144                    . " '$client', an invalid host name\n") if ( $opts{v} );
145         exit(1)
146     }
147     $Hosts = $bpc->HostInfoRead($client);
148     $host = $client;
149 } else {
150     $Hosts = $bpc->HostInfoRead($client);
151 }
152 if ( !defined($Hosts->{$client}) ) {
153     print(STDERR "Exiting because host $client does not exist in the"
154                . " hosts file\n") if ( $opts{v} );
155     exit(1)
156 }
157
158 my $Dir     = "$TopDir/pc/$client";
159 my @xferPid = ();
160 my $tarPid  = -1;
161
162 #
163 # Re-read config file, so we can include the PC-specific config
164 #
165 $clientURI = $bpc->uriEsc($client);
166 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
167     print("dump failed: Can't read PC's config file: $error\n");
168     exit(1);
169 }
170 %Conf = $bpc->Conf();
171
172 #
173 # Catch various signals
174 #
175 $SIG{INT}  = \&catch_signal;
176 $SIG{ALRM} = \&catch_signal;
177 $SIG{TERM} = \&catch_signal;
178 $SIG{PIPE} = \&catch_signal;
179 $SIG{STOP} = \&catch_signal;
180 $SIG{TSTP} = \&catch_signal;
181 $SIG{TTIN} = \&catch_signal;
182 my $Pid = $$;
183
184 #
185 # Make sure we eventually timeout if there is no activity from
186 # the data transport program.
187 #
188 alarm($Conf{ClientTimeout});
189
190 mkpath($Dir, 0, 0777) if ( !-d $Dir );
191 if ( !-f "$Dir/LOCK" ) {
192     open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
193 }
194 open(LOG, ">>", "$Dir/LOG");
195 select(LOG); $| = 1; select(STDOUT);
196
197 #
198 # For the -e option we just expire backups and quit
199 #
200 if ( $opts{e} ) {
201     BackupExpire($client);
202     exit(0);
203 }
204
205 #
206 # For archive hosts we don't bother any further
207 #
208 if ($Conf{XferMethod} eq "archive" ) {
209     print(STDERR "Exiting because the XferMethod is set to archive\n")
210                 if ( $opts{v} );
211     exit(0);
212 }
213
214 if ( !$opts{d} ) {
215     #
216     # In the non-DHCP case, make sure the host can be looked up
217     # via NS, or otherwise find the IP address via NetBios.
218     #
219     if ( $Conf{ClientNameAlias} ne "" ) {
220         $host = $Conf{ClientNameAlias};
221     } else {
222         $host = $client;
223     }
224     if ( !defined(gethostbyname($host)) ) {
225         #
226         # Ok, NS doesn't know about it.  Maybe it is a NetBios name
227         # instead.
228         #
229         print(STDERR "Name server doesn't know about $host; trying NetBios\n")
230                         if ( $opts{v} );
231         if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
232             print(LOG $bpc->timeStamp, "Can't find host $host via netbios\n");
233             print("host not found\n");
234             exit(1);
235         }
236     } else {
237         $hostIP = $host;
238     }
239 }
240
241 ###########################################################################
242 # Figure out what to do and do it
243 ###########################################################################
244
245 #
246 # See if we should skip this host during a certain range
247 # of times.
248 #
249 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
250 if ( $err ne "" ) {
251     print("Can't connect to server ($err)\n");
252     print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
253     exit(1);
254 }
255 my $reply = $bpc->ServerMesg("status host($clientURI)");
256 $reply = $1 if ( $reply =~ /(.*)/s );
257 my(%StatusHost);
258 eval($reply);
259 $bpc->ServerDisconnect();
260
261 #
262 # For DHCP tell BackupPC which host this is
263 #
264 if ( $opts{d} ) {
265     if ( $StatusHost{activeJob} ) {
266         # oops, something is already running for this host
267         print(STDERR "Exiting because backup is already running for $client\n")
268                         if ( $opts{v} );
269         exit(0);
270     }
271     print("DHCP $hostIP $clientURI\n");
272 }
273
274 my($needLink, @Backups, $type, $lastBkupNum, $lastFullBkupNum);
275 my $lastFull = 0;
276 my $lastIncr = 0;
277 my $partialIdx = -1;
278 my $partialNum;
279 my $lastPartial = 0;
280
281 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
282         || $Conf{FullPeriod} == -2 ) {
283     print(STDERR "Exiting because backups are disabled with"
284                . " \$Conf{FullPeriod} = $Conf{FullPeriod}\n") if ( $opts{v} );
285     #
286     # Tell BackupPC to ignore old failed backups on hosts that
287     # have backups disabled.
288     #
289     print("backups disabled\n")
290                 if ( defined($StatusHost{errorTime})
291                      && $StatusHost{reason} ne "Reason_backup_done"
292                      && time - $StatusHost{errorTime} > 4 * 24 * 3600 );
293     NothingToDo($needLink);
294 }
295
296 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
297              && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
298     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
299     my($currHours) = $hour + $min / 60 + $sec / 3600;
300     my $blackout;
301
302     #
303     # Handle backward compatibility with original separate scalar
304     # parameters.
305     #
306     if ( defined($Conf{BlackoutHourBegin}) ) {
307         push(@{$Conf{BlackoutPeriods}},
308              {
309                  hourBegin => $Conf{BlackoutHourBegin},
310                  hourEnd   => $Conf{BlackoutHourEnd},
311                  weekDays  => $Conf{BlackoutWeekDays},
312              }
313         );
314     }
315     foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
316         #
317         # Allow blackout to span midnight (specified by BlackoutHourBegin
318         # being greater than BlackoutHourEnd)
319         #
320         next if ( ref($p->{weekDays}) ne "ARRAY" 
321                     || !defined($p->{hourBegin})
322                     || !defined($p->{hourEnd})
323                 );
324         if ( $p->{hourBegin} > $p->{hourEnd} ) {
325             $blackout = $p->{hourBegin} <= $currHours
326                           || $currHours <= $p->{hourEnd};
327             if ( $currHours <= $p->{hourEnd} ) {
328                 #
329                 # This is after midnight, so decrement the weekday for the
330                 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
331                 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
332                 #
333                 $wday--;
334                 $wday += 7 if ( $wday < 0 );
335             }
336         } else {
337             $blackout = $p->{hourBegin} <= $currHours
338                           && $currHours <= $p->{hourEnd};
339         }
340         if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
341 #           print(LOG $bpc->timeStamp, "skipping because of blackout"
342 #                      . " (alive $StatusHost{aliveCnt} times)\n");
343             print(STDERR "Skipping $client because of blackout\n")
344                             if ( $opts{v} );
345             NothingToDo($needLink);
346         }
347     }
348 }
349
350 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
351     printf(LOG "%sskipping because of user requested delay (%.1f hours left)\n",
352                 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
353     NothingToDo($needLink);
354 }
355
356 #
357 # Now see if there are any old backups we should delete
358 #
359 BackupExpire($client);
360
361 #
362 # Read Backup information, and find times of the most recent full and
363 # incremental backups
364 #
365 @Backups = $bpc->BackupInfoRead($client);
366 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
367     $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
368                         || -f "$Dir/NewFileList.$Backups[$i]{num}" );
369     $lastBkupNum = $Backups[$i]{num};
370     if ( $Backups[$i]{type} eq "full" ) {
371         if ( $lastFull < $Backups[$i]{startTime} ) {
372             $lastFull = $Backups[$i]{startTime};
373             $lastFullBkupNum = $Backups[$i]{num};
374         }
375     } elsif ( $Backups[$i]{type} eq "incr" ) {
376         $lastIncr = $Backups[$i]{startTime}
377                 if ( $lastIncr < $Backups[$i]{startTime} );
378     } elsif ( $Backups[$i]{type} eq "partial" ) {
379         $partialIdx  = $i;
380         $lastPartial = $Backups[$i]{startTime};
381         $partialNum  = $Backups[$i]{num};
382     }
383 }
384
385 #
386 # Decide whether we do nothing, or a full or incremental backup.
387 #
388 if ( @Backups == 0
389         || $opts{f}
390         || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
391             && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
392     $type = "full";
393 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
394         && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
395     $type = "incr";
396 } else {
397     NothingToDo($needLink);
398 }
399
400 #
401 # Check if $host is alive
402 #
403 my $delay = $bpc->CheckHostAlive($hostIP);
404 if ( $delay < 0 ) {
405     print(LOG $bpc->timeStamp, "no ping response\n");
406     print("no ping response\n");
407     print("link $clientURI\n") if ( $needLink );
408     exit(1);
409 } elsif ( $delay > $Conf{PingMaxMsec} ) {
410     printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
411     printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
412                     $delay, $Conf{PingMaxMsec});
413     print("link $clientURI\n") if ( $needLink );
414     exit(1);
415 }
416
417 #
418 # Make sure it is really the machine we expect (only for fixed addresses,
419 # since we got the DHCP address above).
420 #
421 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
422     print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
423     print("dump failed: $errMsg\n");
424     exit(1);
425 } elsif ( $opts{d} ) {
426     print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
427 }
428
429 #
430 # Get a clean directory $Dir/new
431 #
432 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
433
434 #
435 # Setup file extension for compression and open XferLOG output file
436 #
437 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
438 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
439 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
440                                      $Conf{CompressLevel});
441 if ( !defined($XferLOG) ) {
442     print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
443                              . " $Dir/XferLOG$fileExt\n");
444     print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
445     exit(1);
446 }
447
448 #
449 # Ignore the partial dump in the case of an incremental
450 # or when the partial is too old.  A partial is a partial full.
451 #
452 if ( $type ne "full" || time - $lastPartial > $Conf{PartialAgeMax} * 24*3600 ) {
453     $partialNum = undef;
454     $partialIdx = -1;
455 }
456
457 #
458 # If this is a partial, copy the old XferLOG file
459 #
460 if ( $partialNum ) {
461     my($compress, $fileName);
462     if ( -f "$Dir/XferLOG.$partialNum.z" ) {
463         $fileName = "$Dir/XferLOG.$partialNum.z";
464         $compress = 1;
465     } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
466         $fileName = "$Dir/XferLOG.$partialNum";
467         $compress = 0;
468     }
469     if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
470         my $data;
471         while ( $oldLOG->read(\$data, 65536) > 0 ) {
472             $XferLOG->write(\$data);
473         }
474         $oldLOG->close;
475     }
476 }
477
478 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
479 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
480
481 my $startTime     = time();
482 my $tarErrs       = 0;
483 my $nFilesExist   = 0;
484 my $sizeExist     = 0;
485 my $sizeExistComp = 0;
486 my $nFilesTotal   = 0;
487 my $sizeTotal     = 0;
488 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
489 my $newFilesFH;
490
491 if ( $Conf{XferMethod} eq "tar" ) {
492     $ShareNames = $Conf{TarShareName};
493 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
494     $ShareNames = $Conf{RsyncShareName};
495 } else {
496     $ShareNames = $Conf{SmbShareName};
497 }
498
499 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
500
501 #
502 # Run an optional pre-dump command
503 #
504 UserCommandRun("DumpPreUserCmd");
505 $NeedPostCmd = 1;
506
507 #
508 # Now backup each of the shares
509 #
510 for my $shareName ( @$ShareNames ) {
511     local(*RH, *WH);
512
513     $stat{xferOK} = $stat{hostAbort} = undef;
514     $stat{hostError} = $stat{lastOutputLine} = undef;
515     if ( -d "$Dir/new/$shareName" ) {
516         print(LOG $bpc->timeStamp,
517                   "unexpected repeated share name $shareName skipped\n");
518         next;
519     }
520
521     UserCommandRun("DumpPreShareCmd", $shareName);
522
523     if ( $Conf{XferMethod} eq "tar" ) {
524         #
525         # Use tar (eg: tar/ssh) as the transport program.
526         #
527         $xfer = BackupPC::Xfer::Tar->new($bpc);
528     } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
529         #
530         # Use rsync as the transport program.
531         #
532         if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
533             my $errStr = BackupPC::Xfer::Rsync::errStr;
534             print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
535             print("dump failed: $errStr\n");
536             UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
537             UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
538             exit(1);
539         }
540     } else {
541         #
542         # Default is to use smbclient (smb) as the transport program.
543         #
544         $xfer = BackupPC::Xfer::Smb->new($bpc);
545     }
546
547     my $useTar = $xfer->useTar;
548
549     if ( $useTar ) {
550         #
551         # This xfer method outputs a tar format file, so we start a
552         # BackupPC_tarExtract to extract the data.
553         #
554         # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
555         # WH is the write handle for writing, provided to the transport
556         # program, and RH is the other end of the socket for reading,
557         # provided to BackupPC_tarExtract.
558         #
559         if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
560             shutdown(RH, 1);    # no writing to this socket
561             shutdown(WH, 0);    # no reading from this socket
562             setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
563             setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
564         } else {
565             #
566             # Default to pipe() if socketpair() doesn't work.
567             #
568             pipe(RH, WH);
569         }
570
571         #
572         # fork a child for BackupPC_tarExtract.  TAR is a file handle
573         # on which we (the parent) read the stdout & stderr from
574         # BackupPC_tarExtract.
575         #
576         if ( !defined($tarPid = open(TAR, "-|")) ) {
577             print(LOG $bpc->timeStamp, "can't fork to run tar\n");
578             print("can't fork to run tar\n");
579             close(RH);
580             close(WH);
581             last;
582         }
583         binmode(TAR);
584         if ( !$tarPid ) {
585             #
586             # This is the tar child.  Close the write end of the pipe,
587             # clone STDERR to STDOUT, clone STDIN from RH, and then
588             # exec BackupPC_tarExtract.
589             #
590             setpgrp 0,0;
591             close(WH);
592             close(STDERR);
593             open(STDERR, ">&STDOUT");
594             close(STDIN);
595             open(STDIN, "<&RH");
596             alarm(0);
597             exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
598                          $Conf{CompressLevel});
599             print(LOG $bpc->timeStamp,
600                         "can't exec $BinDir/BackupPC_tarExtract\n");
601             exit(0);
602         }
603     } elsif ( !defined($newFilesFH) ) {
604         #
605         # We need to create the NewFileList output file
606         #
607         local(*NEW_FILES);
608         open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
609                      || die("can't open $TopDir/pc/$client/NewFileList");
610         $newFilesFH = *NEW_FILES;
611         binmode(NEW_FILES);
612     }
613
614     #
615     # Run the transport program
616     #
617     $xfer->args({
618         host        => $host,
619         client      => $client,
620         hostIP      => $hostIP,
621         shareName   => $shareName,
622         pipeRH      => *RH,
623         pipeWH      => *WH,
624         XferLOG     => $XferLOG,
625         newFilesFH  => $newFilesFH,
626         outDir      => $Dir,
627         type        => $type,
628         lastFull    => $lastFull,
629         lastBkupNum => $lastBkupNum,
630         lastFullBkupNum => $lastFullBkupNum,
631         backups     => \@Backups,
632         compress    => $Conf{CompressLevel},
633         XferMethod  => $Conf{XferMethod},
634         logLevel    => $Conf{XferLogLevel},
635         pidHandler  => \&pidHandler,
636         partialNum  => $partialNum,
637     });
638
639     if ( !defined($logMsg = $xfer->start()) ) {
640         print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
641         print("dump failed: ", $xfer->errStr, "\n");
642         print("link $clientURI\n") if ( $needLink );
643         #
644         # kill off the tar process, first nicely then forcefully
645         #
646         if ( $tarPid > 0 ) {
647             kill($bpc->sigName2num("INT"), $tarPid);
648             sleep(1);
649             kill($bpc->sigName2num("KILL"), $tarPid);
650         }
651         if ( @xferPid ) {
652             kill($bpc->sigName2num("INT"), @xferPid);
653             sleep(1);
654             kill($bpc->sigName2num("KILL"), @xferPid);
655         }
656         UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
657         UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
658         exit(1);
659     }
660
661     @xferPid = $xfer->xferPid;
662
663     if ( $useTar ) {
664         #
665         # The parent must close both handles on the pipe since the children
666         # are using these handles now.
667         #
668         close(RH);
669         close(WH);
670     }
671     print(LOG $bpc->timeStamp, $logMsg, "\n");
672     print("started $type dump, share=$shareName\n");
673
674     pidHandler(@xferPid);
675
676     if ( $useTar ) {
677         #
678         # Parse the output of the transfer program and BackupPC_tarExtract
679         # while they run.  Since we might be reading from two or more children
680         # we use a select.
681         #
682         my($FDread, $tarOut, $mesg);
683         vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
684         $xfer->setSelectMask(\$FDread);
685
686         SCAN: while ( 1 ) {
687             my $ein = $FDread;
688             last if ( $FDread =~ /^\0*$/ );
689             select(my $rout = $FDread, undef, $ein, undef);
690             if ( $useTar ) {
691                 if ( vec($rout, fileno(TAR), 1) ) {
692                     if ( sysread(TAR, $mesg, 8192) <= 0 ) {
693                         vec($FDread, fileno(TAR), 1) = 0;
694                         close(TAR);
695                     } else {
696                         $tarOut .= $mesg;
697                     }
698                 }
699                 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
700                     $_ = $1;
701                     $tarOut = $2;
702                     if ( /^  / ) {
703                         $XferLOG->write(\"$_\n");
704                     } else {
705                         $XferLOG->write(\"tarExtract: $_\n");
706                     }
707                     if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
708                         $stat{hostError} = $1;
709                     }
710                     if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
711                         $tarErrs       += $1;
712                         $nFilesExist   += $2;
713                         $sizeExist     += $3;
714                         $sizeExistComp += $4;
715                         $nFilesTotal   += $5;
716                         $sizeTotal     += $6;
717                     }
718                 }
719             }
720             last if ( !$xfer->readOutput(\$FDread, $rout) );
721             while ( my $str = $xfer->logMsgGet ) {
722                 print(LOG $bpc->timeStamp, "xfer: $str\n");
723             }
724             if ( $xfer->getStats->{fileCnt} == 1 ) {
725                 #
726                 # Make sure it is still the machine we expect.  We do this while
727                 # the transfer is running to avoid a potential race condition if
728                 # the ip address was reassigned by dhcp just before we started
729                 # the transfer.
730                 #
731                 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
732                     $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
733                     last SCAN;
734                 }
735             }
736         }
737     } else {
738         #
739         # otherwise the xfer module does everything for us
740         #
741         my @results = $xfer->run();
742         $tarErrs       += $results[0];
743         $nFilesExist   += $results[1];
744         $sizeExist     += $results[2];
745         $sizeExistComp += $results[3];
746         $nFilesTotal   += $results[4];
747         $sizeTotal     += $results[5];
748     }
749
750     #
751     # Merge the xfer status (need to accumulate counts)
752     #
753     my $newStat = $xfer->getStats;
754     if ( $newStat->{fileCnt} == 0 ) {
755        $noFilesErr ||= "No files dumped for share $shareName";
756     }
757     foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
758         next if ( !defined($newStat->{$k}) );
759         if ( $k =~ /Cnt$/ ) {
760             $stat{$k} += $newStat->{$k};
761             delete($newStat->{$k});
762             next;
763         }
764         if ( !defined($stat{$k}) ) {
765             $stat{$k} = $newStat->{$k};
766             delete($newStat->{$k});
767             next;
768         }
769     }
770
771     UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
772
773     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
774     if ( !$stat{xferOK} ) {
775         #
776         # kill off the tranfer program, first nicely then forcefully
777         #
778         if ( @xferPid ) {
779             kill($bpc->sigName2num("INT"), @xferPid);
780             sleep(1);
781             kill($bpc->sigName2num("KILL"), @xferPid);
782         }
783         #
784         # kill off the tar process, first nicely then forcefully
785         #
786         if ( $tarPid > 0 ) {
787             kill($bpc->sigName2num("INT"), $tarPid);
788             sleep(1);
789             kill($bpc->sigName2num("KILL"), $tarPid);
790         }
791         #
792         # don't do any more shares on this host
793         #
794         last;
795     }
796 }
797
798 #
799 # If this is a full, and any share had zero files then consider the dump bad
800 #
801 if ( $type eq "full" && $stat{hostError} eq ""
802             && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
803     $stat{hostError} = $noFilesErr;
804     $stat{xferOK} = 0;
805 }
806
807 $stat{xferOK} = 0 if ( $Abort );
808
809 #
810 # Do one last check to make sure it is still the machine we expect.
811 #
812 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
813     $stat{hostError} = $errMsg;
814     $stat{xferOK} = 0;
815 }
816
817 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
818 close($newFilesFH) if ( defined($newFilesFH) );
819
820 my $endTime = time();
821
822 #
823 # If the dump failed, clean up
824 #
825 if ( !$stat{xferOK} ) {
826     $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
827     if ( $stat{hostError} ) {
828         print(LOG $bpc->timeStamp,
829                   "Got fatal error during xfer ($stat{hostError})\n");
830         $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
831     }
832     if ( !$Abort ) {
833         #
834         # wait a short while and see if the system is still alive
835         #
836         sleep(5);
837         if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
838             $stat{hostAbort} = 1;
839         }
840         if ( $stat{hostAbort} ) {
841             $stat{hostError} = "lost network connection during backup";
842         }
843         print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
844         $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
845     } else {
846         $XferLOG->write(\"Backup aborted by user signal\n");
847     }
848
849     #
850     # Close the log file and call BackupFailCleanup, which exits.
851     #
852     BackupFailCleanup();
853 }
854
855 my $newNum = BackupSave();
856
857 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
858                                    - $stat{xferBadShareCnt};
859 print(LOG $bpc->timeStamp,
860           "$type backup $newNum complete, $stat{fileCnt} files,"
861         . " $stat{byteCnt} bytes,"
862         . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
863         . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
864
865 BackupExpire($client);
866
867 print("$type backup complete\n");
868
869 ###########################################################################
870 # Subroutines
871 ###########################################################################
872
873 sub NothingToDo
874 {
875     my($needLink) = @_;
876
877     print("nothing to do\n");
878     print("link $clientURI\n") if ( $needLink );
879     exit(0);
880 }
881
882 sub catch_signal
883 {
884     my $sigName = shift;
885
886     #
887     # The first time we receive a signal we try to gracefully
888     # abort the backup.  This allows us to keep a partial dump
889     # with the in-progress file deleted and attribute caches
890     # flushed to disk etc.
891     #
892     if ( !length($SigName) ) {
893         my $reason;
894         if ( $sigName eq "INT" ) {
895             $reason = "aborted by user (signal=$sigName)";
896         } else {
897             $reason = "aborted by signal=$sigName";
898         }
899         if ( $Pid == $$ ) {
900             #
901             # Parent logs a message
902             #
903             print(LOG $bpc->timeStamp,
904                     "Aborting backup up after signal $sigName\n");
905
906             #
907             # Tell xfer to abort
908             #
909             $xfer->abort($reason);
910
911             #
912             # Send ALRMs to BackupPC_tarExtract if we are using it
913             #
914             if ( $tarPid > 0 ) {
915                 kill($bpc->sigName2num("ARLM"), $tarPid);
916             }
917
918             #
919             # Schedule a 20 second timer in case the clean
920             # abort doesn't complete
921             #
922             alarm(20);
923         } else {
924             #
925             # Children ignore anything other than ALRM and INT
926             #
927             if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
928                 return;
929             }
930
931             #
932             # The child also tells xfer to abort
933             #
934             $xfer->abort($reason);
935
936             #
937             # Schedule a 15 second timer in case the clean
938             # abort doesn't complete
939             #
940             alarm(15);
941         }
942         $SigName = $sigName;
943         $Abort = 1;
944         return;
945     }
946
947     #
948     # This is a second signal: time to clean up.
949     #
950     if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
951         #
952         # Children quit quietly on ALRM or INT
953         #
954         exit(1)
955     }
956
957     #
958     # Ignore other signals in children
959     #
960     return if ( $Pid != $$ );
961
962     $SIG{$sigName} = 'IGNORE';
963     UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
964     $XferLOG->write(\"exiting after signal $sigName\n");
965     if ( @xferPid ) {
966         kill($bpc->sigName2num("INT"), @xferPid);
967         sleep(1);
968         kill($bpc->sigName2num("KILL"), @xferPid);
969     }
970     if ( $tarPid > 0 ) {
971         kill($bpc->sigName2num("INT"), $tarPid);
972         sleep(1);
973         kill($bpc->sigName2num("KILL"), $tarPid);
974     }
975     if ( $sigName eq "INT" ) {
976         $stat{hostError} = "aborted by user (signal=$sigName)";
977     } else {
978         $stat{hostError} = "received signal=$sigName";
979     }
980     BackupFailCleanup();
981 }
982
983 sub CheckForNewFiles
984 {
985     if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
986         $nFilesTotal++;
987     } elsif ( -d _ ) {
988         #
989         # No need to check entire tree
990         #
991         $File::Find::prune = 1 if ( $nFilesTotal );
992     }
993 }
994
995 sub BackupFailCleanup
996 {
997     my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
998     my $keepPartial = 0;
999
1000     #
1001     # We keep this backup if it is a full and we actually backed
1002     # up some files.
1003     #
1004     if ( $type eq "full" ) {
1005         if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
1006             #
1007             # Xfer didn't report any files, but check in the new
1008             # directory just in case.
1009             #
1010             find(\&CheckForNewFiles, "$Dir/new");
1011             $keepPartial = 1 if ( $nFilesTotal );
1012         } else {
1013             #
1014             # Xfer reported some files
1015             #
1016             $keepPartial = 1;
1017         }
1018     }
1019
1020     #
1021     # Don't keep partials if they are disabled
1022     #
1023     $keepPartial = 0 if ( $Conf{PartialAgeMax} < 0 );
1024
1025     if ( !$keepPartial ) {
1026         #
1027         # No point in saving this dump; get rid of eveything.
1028         #
1029         $XferLOG->close();
1030         unlink("$Dir/timeStamp.level0")    if ( -f "$Dir/timeStamp.level0" );
1031         unlink("$Dir/SmbLOG.bad")          if ( -f "$Dir/SmbLOG.bad" );
1032         unlink("$Dir/SmbLOG.bad$fileExt")  if ( -f "$Dir/SmbLOG.bad$fileExt" );
1033         unlink("$Dir/XferLOG.bad")         if ( -f "$Dir/XferLOG.bad" );
1034         unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1035         unlink("$Dir/NewFileList")         if ( -f "$Dir/NewFileList" );
1036         rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1037         $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1038         print("dump failed: $stat{hostError}\n");
1039         $XferLOG->close();
1040         print("link $clientURI\n") if ( $needLink );
1041         exit(1);
1042     }
1043     #
1044     # Ok, now we should save this as a partial dump
1045     #
1046     $type = "partial";
1047     my $newNum = BackupSave();
1048     print("dump failed: $stat{hostError}\n");
1049     print("link $clientURI\n") if ( $needLink );
1050     print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1051     exit(2);
1052 }
1053
1054 #
1055 # Decide which old backups should be expired by moving them
1056 # to $TopDir/trash.
1057 #
1058 sub BackupExpire
1059 {
1060     my($client) = @_;
1061     my($Dir) = "$TopDir/pc/$client";
1062     my(@Backups) = $bpc->BackupInfoRead($client);
1063     my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
1064
1065     if ( $Conf{FullKeepCnt} <= 0 ) {
1066         print(LOG $bpc->timeStamp,
1067                   "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1068         print(STDERR
1069             "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1070                             if ( $opts{v} );
1071         return;
1072     }
1073     while ( 1 ) {
1074         $cntFull = $cntIncr = 0;
1075         $oldestIncr = $oldestFull = 0;
1076         for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1077             if ( $Backups[$i]{type} eq "full" ) {
1078                 $firstFull = $i if ( $cntFull == 0 );
1079                 $cntFull++;
1080             } else {
1081                 $firstIncr = $i if ( $cntIncr == 0 );
1082                 $cntIncr++;
1083             }
1084         }
1085         $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1086                         if ( $cntIncr > 0 );
1087         $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1088                         if ( $cntFull > 0 );
1089         if ( $cntIncr > $Conf{IncrKeepCnt}
1090                 || ($cntIncr > $Conf{IncrKeepCntMin}
1091                     && $oldestIncr > $Conf{IncrAgeMax})
1092                && (@Backups <= $firstIncr + 1
1093                         || $Backups[$firstIncr]{noFill}
1094                         || !$Backups[$firstIncr + 1]{noFill}) ) {
1095             #
1096             # Only delete an incr backup if the Conf settings are satisfied.
1097             # We also must make sure that either this backup is the most
1098             # recent one, or it is not filled, or the next backup is filled.
1099             # (We can't deleted a filled incr if the next backup is not
1100             # filled.)
1101             # 
1102             print(LOG $bpc->timeStamp,
1103                       "removing incr backup $Backups[$firstIncr]{num}\n");
1104             BackupRemove($client, \@Backups, $firstIncr);
1105             next;
1106         }
1107
1108         #
1109         # Delete any old full backups, according to $Conf{FullKeepCntMin}
1110         # and $Conf{FullAgeMax}.
1111         #
1112         # First make sure that $Conf{FullAgeMax} is at least bigger
1113         # than $Conf{FullPeriod} * $Conf{FullKeepCnt}, including
1114         # the exponential array case.
1115         #
1116         my $fullKeepCnt = $Conf{FullKeepCnt};
1117         $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1118         my $fullAgeMax;
1119         my $fullPeriod = int(0.5 + $Conf{FullPeriod});
1120         for ( my $i = 0 ; $i < @$fullKeepCnt ; $i++ ) {
1121             $fullAgeMax += $fullKeepCnt->[$i] * $fullPeriod;
1122             $fullPeriod *= 2;
1123         }
1124         $fullAgeMax += $fullPeriod;     # add some buffer
1125
1126         if ( $cntFull > $Conf{FullKeepCntMin}
1127                && $oldestFull > $Conf{FullAgeMax}
1128                && $oldestFull > $fullAgeMax
1129                && $Conf{FullKeepCntMin} > 0
1130                && $Conf{FullAgeMax} > 0
1131                && (@Backups <= $firstFull + 1
1132                         || !$Backups[$firstFull + 1]{noFill}) ) {
1133             #
1134             # Only delete a full backup if the Conf settings are satisfied.
1135             # We also must make sure that either this backup is the most
1136             # recent one, or the next backup is filled.
1137             # (We can't deleted a full backup if the next backup is not
1138             # filled.)
1139             # 
1140             print(LOG $bpc->timeStamp,
1141                    "removing old full backup $Backups[$firstFull]{num}\n");
1142             BackupRemove($client, \@Backups, $firstFull);
1143             next;
1144         }
1145
1146         #
1147         # Do new-style full backup expiry, which includes the the case
1148         # where $Conf{FullKeepCnt} is an array.
1149         #
1150         last if ( !BackupFullExpire($client, \@Backups) );
1151     }
1152     $bpc->BackupInfoWrite($client, @Backups);
1153 }
1154
1155 #
1156 # Handle full backup expiry, using exponential periods.
1157 #
1158 sub BackupFullExpire
1159 {
1160     my($client, $Backups) = @_;
1161     my $fullCnt = 0;
1162     my $fullPeriod = $Conf{FullPeriod};
1163     my $origFullPeriod = $fullPeriod;
1164     my $fullKeepCnt = $Conf{FullKeepCnt};
1165     my $fullKeepIdx = 0;
1166     my(@delete, @fullList);
1167
1168     #
1169     # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1170     # not defined - possibly a corrupted config.pl file.
1171     #
1172     return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1173
1174     #
1175     # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1176     # we still expire backups based on a typical FullPeriod value - weekly.
1177     #
1178     $fullPeriod = 7 if ( $fullPeriod <= 0 );
1179
1180     $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1181
1182     for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1183         next if ( $Backups->[$i]{type} ne "full" );
1184         push(@fullList, $i);
1185     }
1186     for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1187         my $i = $fullList[$k];
1188         my $prevFull = $fullList[$k-1] if ( $k > 0 );
1189         #
1190         # Don't delete any full that is followed by an unfilled backup,
1191         # since it is needed for restore.
1192         #
1193         my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1194
1195         if ( !$noDelete && 
1196               ($fullKeepIdx >= @$fullKeepCnt
1197               || $k > 0
1198                  && $fullKeepIdx > 0
1199                  && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1200                              < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1201                )
1202             ) {
1203             #
1204             # Delete the full backup
1205             #
1206             #printf("Deleting backup $i ($prevFull)\n");
1207             push(@delete, $i);
1208         } else {
1209             $fullCnt++;
1210             while ( $fullKeepIdx < @$fullKeepCnt
1211                      && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1212                 $fullKeepIdx++;
1213                 $fullCnt = 0;
1214                 $fullPeriod = 2 * $fullPeriod;
1215             }
1216         }
1217     }
1218     #
1219     # Now actually delete the backups
1220     #
1221     for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1222         print(LOG $bpc->timeStamp,
1223                "removing full backup $Backups->[$delete[$i]]{num}\n");
1224         BackupRemove($client, $Backups, $delete[$i]);
1225     }
1226     return @delete;
1227 }
1228
1229 #
1230 # Removes any partial backups
1231 #
1232 sub BackupPartialRemove
1233 {
1234     my($client, $Backups) = @_;
1235
1236     for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1237         next if ( $Backups->[$i]{type} ne "partial" );
1238         BackupRemove($client, $Backups, $i);
1239     }
1240 }
1241
1242 sub BackupSave
1243 {
1244     my @Backups = $bpc->BackupInfoRead($client);
1245     my $num  = -1;
1246
1247     #
1248     # Since we got a good backup we should remove any partial dumps
1249     # (the new backup might also be a partial, but that's ok).
1250     #
1251     BackupPartialRemove($client, \@Backups);
1252
1253     #
1254     # Number the new backup
1255     #
1256     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1257         $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1258     }
1259     $num++;
1260     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1261     if ( !rename("$Dir/new", "$Dir/$num") ) {
1262         print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1263         $stat{xferOK} = 0;
1264     }
1265     $needLink = 1 if ( -f "$Dir/NewFileList" );
1266
1267     #
1268     # Add the new backup information to the backup file
1269     #
1270     my $i = @Backups;
1271     $Backups[$i]{num}           = $num;
1272     $Backups[$i]{type}          = $type;
1273     $Backups[$i]{startTime}     = $startTime;
1274     $Backups[$i]{endTime}       = $endTime;
1275     $Backups[$i]{size}          = $sizeTotal;
1276     $Backups[$i]{nFiles}        = $nFilesTotal;
1277     $Backups[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
1278     $Backups[$i]{xferBadFile}   = $stat{xferBadFileCnt} || 0;
1279     $Backups[$i]{xferBadShare}  = $stat{xferBadShareCnt} || 0;
1280     $Backups[$i]{nFilesExist}   = $nFilesExist;
1281     $Backups[$i]{sizeExist}     = $sizeExist;
1282     $Backups[$i]{sizeExistComp} = $sizeExistComp;
1283     $Backups[$i]{tarErrs}       = $tarErrs;
1284     $Backups[$i]{compress}      = $Conf{CompressLevel};
1285     $Backups[$i]{noFill}        = $type eq "incr" ? 1 : 0;
1286     $Backups[$i]{level}         = $type eq "incr" ? 1 : 0;
1287     $Backups[$i]{mangle}        = 1;        # name mangling always on for v1.04+
1288     $bpc->BackupInfoWrite($client, @Backups);
1289
1290     unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1291     foreach my $ext ( qw(bad bad.z) ) {
1292         next if ( !-f "$Dir/XferLOG.$ext" );
1293         unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1294         rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1295     }
1296
1297     #
1298     # Now remove the bad files, replacing them if possible with links to
1299     # earlier backups.
1300     #
1301     foreach my $f ( $xfer->getBadFiles ) {
1302         my $j;
1303         my $shareM = $bpc->fileNameEltMangle($f->{share});
1304         my $fileM  = $bpc->fileNameMangle($f->{file});
1305         unlink("$Dir/$num/$shareM/$fileM");
1306         for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1307             my $file;
1308             if ( $Backups[$j]{mangle} ) {
1309                 $file = "$shareM/$fileM";
1310             } else {
1311                 $file = "$f->{share}/$f->{file}";
1312             }
1313             next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1314             if ( !link("$Dir/$Backups[$j]{num}/$file",
1315                                 "$Dir/$num/$shareM/$fileM") ) {
1316                 my $str = \"Unable to link $num/$f->{share}/$f->{file} to"
1317                          . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1318                 $XferLOG->write(\$str);
1319             } else {
1320                 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1321                         . " by link to"
1322                         . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1323                 $XferLOG->write(\$str);
1324             }
1325             last;
1326         }
1327         if ( $j < 0 ) {
1328             my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1329                     . " (no older copy to link to)\n";
1330             $XferLOG->write(\$str);
1331         }
1332     }
1333     $XferLOG->close();
1334     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1335     rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1336
1337     return $num;
1338 }
1339
1340 #
1341 # Removes a specific backup
1342 #
1343 sub BackupRemove
1344 {
1345     my($client, $Backups, $idx) = @_;
1346     my($Dir) = "$TopDir/pc/$client";
1347
1348     $bpc->RmTreeDefer("$TopDir/trash",
1349                       "$Dir/$Backups->[$idx]{num}");
1350     unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1351                 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1352     unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1353                 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1354     unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1355                 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1356     unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1357                 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1358     splice(@{$Backups}, $idx, 1);
1359 }
1360
1361 sub CorrectHostCheck
1362 {
1363     my($hostIP, $host) = @_;
1364     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1365                 || $Conf{NmbLookupCmd} eq "" );
1366     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1367     return "host $host has mismatching netbios name $netBiosHost"
1368                 if ( $netBiosHost ne $host );
1369     return;
1370 }
1371
1372 #
1373 # The Xfer method might tell us from time to time about processes
1374 # it forks.  We tell BackupPC about this (for status displays) and
1375 # keep track of the pids in case we cancel the backup
1376 #
1377 sub pidHandler
1378 {
1379     @xferPid = @_;
1380     @xferPid = grep(/./, @xferPid);
1381     return if ( !@xferPid && $tarPid < 0 );
1382     my @pids = @xferPid;
1383     push(@pids, $tarPid) if ( $tarPid > 0 );
1384     my $str = join(",", @pids);
1385     $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1386     print("xferPids $str\n");
1387 }
1388
1389 #
1390 # Run an optional pre- or post-dump command
1391 #
1392 sub UserCommandRun
1393 {
1394     my($cmdType, $sharename) = @_;
1395
1396     return if ( !defined($Conf{$cmdType}) );
1397     my $vars = {
1398         xfer       => $xfer,
1399         client     => $client,
1400         host       => $host,
1401         hostIP     => $hostIP,
1402         user       => $Hosts->{$client}{user},
1403         moreUsers  => $Hosts->{$client}{moreUsers},
1404         share      => $ShareNames->[0],
1405         shares     => $ShareNames,
1406         XferMethod => $Conf{XferMethod},
1407         sshPath    => $Conf{SshPath},
1408         LOG        => *LOG,
1409         XferLOG    => $XferLOG,
1410         stat       => \%stat,
1411         xferOK     => $stat{xferOK} || 0,
1412         hostError  => $stat{hostError},
1413         type       => $type,
1414         cmdType    => $cmdType,
1415     };
1416
1417     if ($cmdType eq 'DumpPreShareCmd' || $cmdType eq 'DumpPostShareCmd') {
1418         $vars->{share} = $sharename;
1419     }
1420
1421     my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
1422     $XferLOG->write(\"Executing $cmdType: @$cmd\n");
1423     #
1424     # Run the user's command, dumping the stdout/stderr into the
1425     # Xfer log file.  Also supply the optional $vars and %Conf in
1426     # case the command is really perl code instead of a shell
1427     # command.
1428     #
1429     $bpc->cmdSystemOrEval($cmd,
1430             sub {
1431                 $XferLOG->write(\$_[0]);
1432             },
1433             $vars, \%Conf);
1434 }