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