v1.5.0
[BackupPC.git] / bin / BackupPC_dump
1 #!/bin/perl -T
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_dump: Dump a single PC.
5 #
6 # DESCRIPTION
7 #
8 #   Usage: BackupPC_dump [-i] [-f] [-d] [-e] <host>
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, so initially we have no
18 #          idea which machine this actually is.  BackupPC_dump
19 #          determines the actual PC host name by using the NetBios
20 #          name.
21 #
22 #     -e   Just do an dump expiry check for the host.  Don't do anything else.  #          This is used periodically by BackupPC to make sure that dhcp hosts
23 #          have correctly expired old backups.  Without this, dhcp hosts that
24 #          are no longer on the network will not expire old backups.
25 #
26 #   BackupPC_dump is run periodically by BackupPC to backup $host.
27 #   The file $TopDir/pc/$host/backups is read to decide whether a
28 #   full or incremental backup needs to be run.  If no backup is
29 #   scheduled, or a ping to $host fails, then BackupPC_dump quits.
30 #
31 #   The backup is done using smbclient, extracting the dump into
32 #   $TopDir/pc/$host/new.  The smbclient output is put into
33 #   $TopDir/pc/$host/XferLOG.
34 #
35 #   If the dump succeeds (based on parsing the output of smbclient):
36 #     - $TopDir/pc/$host/new is renamed to $TopDir/pc/$host/nnn, where
37 #           nnn is the next sequential dump number.
38 #     - $TopDir/pc/$host/XferLOG is renamed to $TopDir/pc/$host/XferLOG.nnn.
39 #     - $TopDir/pc/$host/backups is updated.
40 #
41 #   If the dump fails:
42 #     - $TopDir/pc/$host/new is moved to $TopDir/trash for later removal.
43 #     - $TopDir/pc/$host/XferLOG is renamed to $TopDir/pc/$host/XferLOG.bad
44 #           for later viewing.
45 #
46 #   BackupPC_dump communicates to BackupPC via printing to STDOUT.
47 #
48 # AUTHOR
49 #   Craig Barratt  <cbarratt@users.sourceforge.net>
50 #
51 # COPYRIGHT
52 #   Copyright (C) 2001  Craig Barratt
53 #
54 #   This program is free software; you can redistribute it and/or modify
55 #   it under the terms of the GNU General Public License as published by
56 #   the Free Software Foundation; either version 2 of the License, or
57 #   (at your option) any later version.
58 #
59 #   This program is distributed in the hope that it will be useful,
60 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
61 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
62 #   GNU General Public License for more details.
63 #
64 #   You should have received a copy of the GNU General Public License
65 #   along with this program; if not, write to the Free Software
66 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
67 #
68 #========================================================================
69 #
70 # Version 1.5.0, released 2 Aug 2002.
71 #
72 # See http://backuppc.sourceforge.net.
73 #
74 #========================================================================
75
76 use strict;
77 use lib "__INSTALLDIR__/lib";
78 use BackupPC::Lib;
79 use BackupPC::FileZIO;
80 use BackupPC::Xfer::Smb;
81 use BackupPC::Xfer::Tar;
82
83 use File::Path;
84 use Getopt::Std;
85
86 ###########################################################################
87 # Initialize
88 ###########################################################################
89
90 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
91 my $TopDir = $bpc->TopDir();
92 my $BinDir = $bpc->BinDir();
93 my %Conf   = $bpc->Conf();
94
95 $bpc->ChildInit();
96
97 my %opts;
98 getopts("defi", \%opts);
99 if ( @ARGV != 1 ) {
100     print("usage: $0 [-d] [-e] [-f] [-i] <host>\n");
101     exit(1);
102 }
103 if ( $ARGV[0] !~ /^([\w\.-]+)$/ ) {
104     print("$0: bad host name '$ARGV[0]'\n");
105     exit(1);
106 }
107 my $hostIP = $1;
108 my($host, $user);
109
110 if ( $opts{d} ) {
111     #
112     # The host name $hostIP is simply a DHCP address.  We need to check
113     # if there is any machine at this address, and if so, get the actual
114     # host name via NetBios using nmblookup.
115     #
116     exit(1) if ( $bpc->CheckHostAlive($hostIP) < 0 );
117     ($host, $user) = $bpc->NetBiosInfoGet($hostIP);
118     exit(1) if ( $host !~ /^([\w\.-]+)$/ );
119     my $hosts = $bpc->HostInfoRead($host);
120     exit(1) if ( !defined($hosts->{$host}) );
121 } else {
122     $host = $hostIP;
123 }
124
125 my $Dir     = "$TopDir/pc/$host";
126 my $xferPid = -1;
127 my $tarPid  = -1;
128
129 #
130 # Re-read config file, so we can include the PC-specific config
131 #
132 $bpc->ConfigRead($host);
133 %Conf = $bpc->Conf();
134
135 #
136 # Catch various signals
137 #
138 $SIG{INT}  = \&catch_signal;
139 $SIG{ALRM} = \&catch_signal;
140 $SIG{TERM} = \&catch_signal;
141
142 #
143 # Make sure we eventually timeout if there is no activity from
144 # the data transport program.
145 #
146 alarm($Conf{SmbClientTimeout});
147
148 mkpath($Dir, 0, 0777) if ( !-d $Dir );
149 if ( !-f "$Dir/LOCK" ) {
150     open(LOCK, ">$Dir/LOCK") && close(LOCK);
151 }
152 open(LOG, ">>$Dir/LOG");
153 select(LOG); $| = 1; select(STDOUT);
154
155 ###########################################################################
156 # Figure out what to do and do it
157 ###########################################################################
158
159 #
160 # For the -e option we just expire backups and quit
161 #
162 if ( $opts{e} ) {
163     BackupExpire($host);
164     exit(0);
165 }
166
167 #
168 # See if we should skip this host during a certain range
169 # of times.
170 #
171 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
172 if ( $err ne "" ) {
173     print("Can't connect to server ($err)\n");
174     print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
175     exit(1);
176 }
177 my $reply = $bpc->ServerMesg("status host($host)");
178 $reply = $1 if ( $reply =~ /(.*)/s );
179 my(%StatusHost);
180 eval($reply);
181 $bpc->ServerDisconnect();
182
183 #
184 # For DHCP tell BackupPC which host this is
185 #
186 if ( $opts{d} ) {
187     if ( $StatusHost{activeJob} ) {
188         # oops, something is already running for this host
189         exit(0);
190     }
191     print("DHCP $hostIP $host\n");
192 }
193
194 my($needLink, @Backups, $type);
195 my $lastFull = 0;
196 my $lastIncr = 0;
197
198 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
199              && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
200     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
201     my($currHours) = $hour + $min / 60 + $sec / 3600;
202     if ( $Conf{BlackoutHourBegin} <= $currHours
203               && $currHours <= $Conf{BlackoutHourEnd}
204               && grep($_ == $wday, @{$Conf{BlackoutWeekDays}}) ) {
205         print(LOG $bpc->timeStamp, "skipping because of blackout"
206                     . " (alive $StatusHost{aliveCnt} times)\n");
207         print("nothing to do\n");
208         print("link $host\n") if ( $needLink );
209         exit(1);
210     }
211 }
212
213 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
214     printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
215                 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
216     print("nothing to do\n");
217     print("link $host\n") if ( $needLink );
218     exit(1);
219 }
220
221 #
222 # Now see if there are any old backups we should delete
223 #
224 BackupExpire($host);
225
226 #
227 # Read Backup information, and find times of the most recent full and
228 # incremental backups
229 #
230 @Backups = $bpc->BackupInfoRead($host);
231 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
232     $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
233                         || -f "$Dir/NewFileList.$Backups[$i]{num}" );
234     if ( $Backups[$i]{type} eq "full" ) {
235         $lastFull = $Backups[$i]{startTime}
236                 if ( $lastFull < $Backups[$i]{startTime} );
237     } else {
238         $lastIncr = $Backups[$i]{startTime}
239                 if ( $lastIncr < $Backups[$i]{startTime} );
240     }
241 }
242
243 #
244 # Decide whether we do nothing, or a full or incremental backup.
245 #
246 if ( @Backups == 0
247         || $opts{f}
248         || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
249             && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
250     $type = "full";
251 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
252         && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
253     $type = "incr";
254 } else {
255     print("nothing to do\n");
256     print("link $host\n") if ( $needLink );
257     exit(0);
258 }
259
260 #
261 # Check if $host is alive
262 #
263 my $delay = $bpc->CheckHostAlive($hostIP);
264 if ( $delay < 0 ) {
265     print(LOG $bpc->timeStamp, "no ping response\n");
266     print("no ping response\n");
267     print("link $host\n") if ( $needLink );
268     exit(1);
269 } elsif ( $delay > $Conf{PingMaxMsec} ) {
270     printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
271     printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
272                     $delay, $Conf{PingMaxMsec});
273     print("link $host\n") if ( $needLink );
274     exit(1);
275 }
276
277 #
278 # Make sure it is really the machine we expect (only for fixed addresses,
279 # since we got the DHCP address above).
280 #
281 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
282     print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
283     print("dump failed: $errMsg\n");
284     exit(1);
285 } elsif ( $opts{d} ) {
286     print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
287 }
288
289 #
290 # Get a clean directory $Dir/new
291 #
292 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
293
294 #
295 # Setup file extension for compression and open XferLOG output file
296 #
297 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
298 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
299 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
300                                      $Conf{CompressLevel});
301 if ( !defined($XferLOG) ) {
302     print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
303                              . " $Dir/XferLOG$fileExt\n");
304     print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
305     exit(1);
306 }
307 unlink("$Dir/NewFileList");
308 my $startTime = time();
309
310 my $tarErrs       = 0;
311 my $nFilesExist   = 0;
312 my $sizeExist     = 0;
313 my $sizeExistComp = 0;
314 my $nFilesTotal   = 0;
315 my $sizeTotal     = 0;
316 my($logMsg, %stat, $xfer, $ShareNames);
317
318 if ( $Conf{XferMethod} eq "tar" ) {
319     $ShareNames = $Conf{TarShareName};
320 } else {
321     $ShareNames = $Conf{SmbShareName};
322 }
323
324 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
325
326 #
327 # Now backup each of the shares
328 #
329 for my $shareName ( @$ShareNames ) {
330     local(*RH, *WH);
331
332     $stat{xferOK} = $stat{hostAbort} = undef;
333     $stat{hostError} = $stat{lastOutputLine} = undef;
334     if ( -d "$Dir/new/$shareName" ) {
335         print(LOG $bpc->timeStamp,
336                   "unexpected repeated share name $shareName skipped\n");
337         next;
338     }
339
340     #
341     # Create a pipe to connect smbclient to BackupPC_tarExtract
342     # WH is the write handle for writing, provided to the transport
343     # program, and RH is the other end of the pipe for reading,
344     # provided to BackupPC_tarExtract.
345     #
346     pipe(RH, WH);
347
348     #
349     # fork a child for BackupPC_tarExtract.  TAR is a file handle
350     # on which we (the parent) read the stdout & stderr from
351     # BackupPC_tarExtract.
352     #
353     if ( !defined($tarPid = open(TAR, "-|")) ) {
354         print(LOG $bpc->timeStamp, "can't fork to run tar\n");
355         print("can't fork to run tar\n");
356         close(RH);
357         close(WH);
358         last;
359     }
360     if ( !$tarPid ) {
361         #
362         # This is the tar child.  Close the write end of the pipe,
363         # clone STDERR to STDOUT, clone STDIN from RH, and then
364         # exec BackupPC_tarExtract.
365         #
366         setpgrp 0,0;
367         close(WH);
368         close(STDERR);
369         open(STDERR, ">&STDOUT");
370         close(STDIN);
371         open(STDIN, "<&RH");
372         exec("$BinDir/BackupPC_tarExtract '$host' '$shareName'"
373              . " $Conf{CompressLevel}");
374         print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarExtract\n");
375         exit(0);
376     }
377
378     #
379     # Run the transport program
380     #
381     my $xferArgs = {
382         host      => $host,
383         hostIP    => $hostIP,
384         shareName => $shareName,
385         pipeRH    => *RH,
386         pipeWH    => *WH,
387         XferLOG   => $XferLOG,
388         outDir    => $Dir,
389         type      => $type,
390         lastFull  => $lastFull,
391     };
392     if ( $Conf{XferMethod} eq "tar" ) {
393         #
394         # Use tar (eg: tar/ssh) as the transport program.
395         #
396         $xfer = BackupPC::Xfer::Tar->new($bpc, $xferArgs);
397     } else {
398         #
399         # Default is to use smbclient (smb) as the transport program.
400         #
401         $xfer = BackupPC::Xfer::Smb->new($bpc, $xferArgs);
402     }
403     if ( !defined($logMsg = $xfer->start()) ) {
404         print(LOG $bpc->timeStamp, $xfer->errStr, "\n");
405         print($xfer->errStr, "\n");
406         print("link $host\n") if ( $needLink );
407         #
408         # kill off the tar process, first nicely then forcefully
409         #
410         kill(2, $tarPid);
411         sleep(1);
412         kill(9, $tarPid);
413         exit(1);
414     }
415     #
416     # The parent must close both handles on the pipe since the children
417     # are using these handles now.
418     #
419     close(RH);
420     close(WH);
421     $xferPid = $xfer->xferPid;
422     print(LOG $bpc->timeStamp, $logMsg,
423                                " (xferPid=$xferPid, tarPid=$tarPid)\n");
424     print("started $type dump, pid=$xferPid, tarPid=$tarPid\n");
425
426     #
427     # Parse the output of the transfer program and BackupPC_tarExtract
428     # while they run.  Since we are reading from two or more children
429     # we use a select.
430     #
431     my($FDread, $tarOut, $mesg);
432     vec($FDread, fileno(TAR), 1) = 1;
433     $xfer->setSelectMask(\$FDread);
434
435     SCAN: while ( 1 ) {
436         my $ein = $FDread;
437         last if ( $FDread =~ /^\0*$/ );
438         select(my $rout = $FDread, undef, $ein, undef);
439         if ( vec($rout, fileno(TAR), 1) ) {
440             if ( sysread(TAR, $mesg, 8192) <= 0 ) {
441                 vec($FDread, fileno(TAR), 1) = 0;
442                 close(TAR);
443             } else {
444                 $tarOut .= $mesg;
445             }
446         }
447         while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
448             $_ = $1;
449             $tarOut = $2;
450             $XferLOG->write(\"tarExtract: $_\n");
451             if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
452                 $tarErrs       = $1;
453                 $nFilesExist   = $2;
454                 $sizeExist     = $3;
455                 $sizeExistComp = $4;
456                 $nFilesTotal   = $5;
457                 $sizeTotal     = $6;
458             }
459         }
460         last if ( !$xfer->readOutput(\$FDread, $rout) );
461         while ( my $str = $xfer->logMsgGet ) {
462             print(LOG $bpc->timeStamp, "xfer: $str\n");
463         }
464         if ( $xfer->getStats->{fileCnt} == 1 ) {
465             #
466             # Make sure it is still the machine we expect.  We do this while
467             # the transfer is running to avoid a potential race condition if
468             # the ip address was reassigned by dhcp just before we started
469             # the transfer.
470             #
471             if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
472                 $stat{hostError} = $errMsg;
473                 last SCAN;
474             }
475         }
476     }
477     #
478     # Merge the xfer status (need to accumulate counts)
479     #
480     my $newStat = $xfer->getStats;
481     foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
482         next if ( !defined($newStat->{$k}) );
483         if ( $k =~ /Cnt$/ ) {
484             $stat{$k} += $newStat->{$k};
485             delete($newStat->{$k});
486             next;
487         }
488         if ( !defined($stat{$k}) ) {
489             $stat{$k} = $newStat->{$k};
490             delete($newStat->{$k});
491             next;
492         }
493     }
494     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
495     if ( !$stat{xferOK} ) {
496         #
497         # kill off the tranfer program, first nicely then forcefully
498         #
499         kill(2, $xferPid);
500         sleep(1);
501         kill(9, $xferPid);
502         #
503         # kill off the tar process, first nicely then forcefully
504         #
505         kill(2, $tarPid);
506         sleep(1);
507         kill(9, $tarPid);
508         #
509         # don't do any more shares on this host
510         #
511         last;
512     }
513 }
514 $XferLOG->close();
515
516 my $lastNum  = -1;
517
518 #
519 # Do one last check to make sure it is still the machine we expect.
520 #
521 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
522     $stat{hostError} = $errMsg;
523     $stat{xferOK} = 0;
524 }
525 if ( $stat{xferOK} ) {
526     @Backups = $bpc->BackupInfoRead($host);
527     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
528         $lastNum = $Backups[$i]{num} if ( $lastNum < $Backups[$i]{num} );
529     }
530     $lastNum++;
531     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$lastNum")
532                                 if ( -d "$Dir/$lastNum" );
533     if ( !rename("$Dir/new", "$Dir/$lastNum") ) {
534         print(LOG $bpc->timeStamp,
535                   "Rename $Dir/new -> $Dir/$lastNum failed\n");
536         $stat{xferOK} = 0;
537     }
538     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$lastNum$fileExt");
539     rename("$Dir/NewFileList", "$Dir/NewFileList.$lastNum");
540 }
541 my $endTime = time();
542
543 #
544 # If the dump failed, clean up
545 #
546 if ( !$stat{xferOK} ) {
547     #
548     # wait a short while and see if the system is still alive
549     #
550     $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
551     if ( $stat{hostError} ) {
552         print(LOG $bpc->timeStamp,
553                   "Got fatal error during xfer ($stat{hostError})\n");
554     }
555     sleep(10);
556     if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
557         $stat{hostAbort} = 1;
558     }
559     if ( $stat{hostAbort} ) {
560         $stat{hostError} = "lost network connection during backup";
561     }
562     print(LOG $bpc->timeStamp, "Dump aborted ($stat{hostError})\n");
563     unlink("$Dir/timeStamp.level0");
564     unlink("$Dir/SmbLOG.bad");
565     unlink("$Dir/SmbLOG.bad$fileExt");
566     unlink("$Dir/XferLOG.bad");
567     unlink("$Dir/XferLOG.bad$fileExt");
568     unlink("$Dir/NewFileList");
569     rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
570     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
571     print("dump failed: $stat{hostError}\n");
572     print("link $host\n") if ( $needLink );
573     exit(1);
574 }
575
576 #
577 # Add the new backup information to the backup file
578 #
579 @Backups = $bpc->BackupInfoRead($host);
580 my $i = @Backups;
581 $Backups[$i]{num}           = $lastNum;
582 $Backups[$i]{type}          = $type;
583 $Backups[$i]{startTime}     = $startTime;
584 $Backups[$i]{endTime}       = $endTime;
585 $Backups[$i]{size}          = $sizeTotal;
586 $Backups[$i]{nFiles}        = $nFilesTotal;
587 $Backups[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
588 $Backups[$i]{xferBadFile}   = $stat{xferBadFileCnt} || 0;
589 $Backups[$i]{xferBadShare}  = $stat{xferBadShareCnt} || 0;
590 $Backups[$i]{nFilesExist}   = $nFilesExist;
591 $Backups[$i]{sizeExist}     = $sizeExist;
592 $Backups[$i]{sizeExistComp} = $sizeExistComp;
593 $Backups[$i]{tarErrs}       = $tarErrs;
594 $Backups[$i]{compress}      = $Conf{CompressLevel};
595 $Backups[$i]{noFill}        = $type eq "full" ? 0 : 1;
596 $Backups[$i]{mangle}        = 1;        # name mangling always on for v1.04+
597 $bpc->BackupInfoWrite($host, @Backups);
598
599 unlink("$Dir/timeStamp.level0");
600
601 #
602 # Now remove the bad files, replacing them if possible with links to
603 # earlier backups.
604 #
605 foreach my $file ( $xfer->getBadFiles ) {
606     my $j;
607     unlink("$Dir/$lastNum/$file");
608     for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
609         next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
610         if ( !link("$Dir/$Backups[$j]{num}/$file", "$Dir/$lastNum/$file") ) {
611             print(LOG $bpc->timeStamp,
612                       "Unable to link $lastNum/$file to"
613                     . " $Backups[$j]{num}/$file\n");
614         } else {
615             print(LOG $bpc->timeStamp,
616                       "Bad file $lastNum/$file replaced by link to"
617                     . " $Backups[$j]{num}/$file\n");
618         }
619         last;
620     }
621     if ( $j < 0 ) {
622         print(LOG $bpc->timeStamp,
623                   "Removed bad file $lastNum/$file (no older"
624                 . " copy to link to)\n");
625     }
626 }
627
628 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
629                                    - $stat{xferBadShareCnt};
630 print(LOG $bpc->timeStamp,
631           "$type backup $lastNum complete, $stat{fileCnt} files,"
632         . " $stat{byteCnt} bytes,"
633         . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
634         . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
635
636 BackupExpire($host);
637
638 print("$type backup complete\n");
639
640 ###########################################################################
641 # Subroutines
642 ###########################################################################
643
644 sub catch_signal
645 {
646     my $signame = shift;
647
648     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
649     if ( $xferPid > 0 ) {
650         if ( kill(2, $xferPid) <= 0 ) {
651             sleep(1);
652             kill(9, $xferPid);
653         }
654     }
655     if ( $tarPid > 0 ) {
656         if ( kill(2, $tarPid) <= 0 ) {
657             sleep(1);
658             kill(9, $tarPid);
659         }
660     }
661     unlink("$Dir/timeStamp.level0");
662     unlink("$Dir/NewFileList");
663     $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
664     print("exiting after signal $signame\n");
665     print("link $host\n") if ( $needLink );
666     exit(1);
667 }
668
669 #
670 # Decide which old backups should be expired by moving them
671 # to $TopDir/trash.
672 #
673 sub BackupExpire
674 {
675     my($host) = @_;
676     my($Dir) = "$TopDir/pc/$host";
677     my(@Backups) = $bpc->BackupInfoRead($host);
678     my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
679
680     while ( 1 ) {
681         $cntFull = $cntIncr = 0;
682         $oldestIncr = $oldestFull = 0;
683         for ( $i = 0 ; $i < @Backups ; $i++ ) {
684             if ( $Backups[$i]{type} eq "full" ) {
685                 $firstFull = $i if ( $cntFull == 0 );
686                 $cntFull++;
687             } else {
688                 $firstIncr = $i if ( $cntIncr == 0 );
689                 $cntIncr++;
690             }
691         }
692         $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
693                         if ( $cntIncr > 0 );
694         $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
695                         if ( $cntFull > 0 );
696         if ( $cntIncr > $Conf{IncrKeepCnt}
697                 || ($cntIncr > $Conf{IncrKeepCntMin}
698                     && $oldestIncr > $Conf{IncrAgeMax})
699                && (@Backups <= $firstIncr + 1
700                         || $Backups[$firstIncr]{noFill}
701                         || !$Backups[$firstIncr + 1]{noFill}) ) {
702             #
703             # Only delete an incr backup if the Conf settings are satisfied.
704             # We also must make sure that either this backup is the most
705             # recent one, or it is not filled, or the next backup is filled.
706             # (We can't deleted a filled incr if the next backup is not
707             # filled.)
708             # 
709             print(LOG $bpc->timeStamp,
710                       "removing incr backup $Backups[$firstIncr]{num}\n");
711             $bpc->RmTreeDefer("$TopDir/trash",
712                               "$Dir/$Backups[$firstIncr]{num}");
713             unlink("$Dir/SmbLOG.$Backups[$firstIncr]{num}")
714                         if ( -f "$Dir/SmbLOG.$Backups[$firstIncr]{num}" );
715             unlink("$Dir/SmbLOG.$Backups[$firstIncr]{num}.z")
716                         if ( -f "$Dir/SmbLOG.$Backups[$firstIncr]{num}.z" );
717             unlink("$Dir/XferLOG.$Backups[$firstIncr]{num}")
718                         if ( -f "$Dir/XferLOG.$Backups[$firstIncr]{num}" );
719             unlink("$Dir/XferLOG.$Backups[$firstIncr]{num}.z")
720                         if ( -f "$Dir/XferLOG.$Backups[$firstIncr]{num}.z" );
721             splice(@Backups, $firstIncr, 1);
722         } elsif ( ($cntFull > $Conf{FullKeepCnt}
723                     || ($cntFull > $Conf{FullKeepCntMin}
724                         && $oldestFull > $Conf{FullAgeMax}))
725                && (@Backups <= $firstFull + 1
726                         || !$Backups[$firstFull + 1]{noFill}) ) {
727             #
728             # Only delete a full backup if the Conf settings are satisfied.
729             # We also must make sure that either this backup is the most
730             # recent one, or the next backup is filled.
731             # (We can't deleted a full backup if the next backup is not
732             # filled.)
733             # 
734             print(LOG $bpc->timeStamp,
735                    "removing full backup $Backups[$firstFull]{num}\n");
736             $bpc->RmTreeDefer("$TopDir/trash",
737                               "$Dir/$Backups[$firstFull]{num}");
738             unlink("$Dir/SmbLOG.$Backups[$firstFull]{num}")
739                         if ( -f "$Dir/SmbLOG.$Backups[$firstFull]{num}" );
740             unlink("$Dir/SmbLOG.$Backups[$firstFull]{num}.z")
741                         if ( -f "$Dir/SmbLOG.$Backups[$firstFull]{num}.z" );
742             unlink("$Dir/XferLOG.$Backups[$firstFull]{num}")
743                         if ( -f "$Dir/XferLOG.$Backups[$firstFull]{num}" );
744             unlink("$Dir/XferLOG.$Backups[$firstFull]{num}.z")
745                         if ( -f "$Dir/XferLOG.$Backups[$firstFull]{num}.z" );
746             splice(@Backups, $firstFull, 1);
747         } else {
748             last;
749         }
750     }
751     $bpc->BackupInfoWrite($host, @Backups);
752 }
753
754 sub CorrectHostCheck
755 {
756     my($hostIP, $host) = @_;
757     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} );
758     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
759     return "host $host has mismatching netbios name $netBiosHost"
760             if ( $netBiosHost ne $host );
761     return;
762 }