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