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