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