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