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