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