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