2 #============================================================= -*-perl-*-
4 # BackupPC: Main program for PC backups.
8 # BackupPC reads the configuration and status information from
9 # $TopDir/conf. It then runs and manages all the backup activity.
11 # As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
12 # to queue backups on all the PCs. This is a four step process:
13 # 1) For each host and DHCP address backup requests are queued on the
14 # background command queue.
15 # 2) For each PC, BackupPC_dump is forked. Several of these may
16 # be run in parallel, based on the configuration.
17 # 3) For each complete, good, backup, BackupPC_link is forked.
18 # Only one of these tasks runs at a time.
19 # 4) In the background BackupPC_trashClean is run to remove any expired
20 # backups. Once each night, BackupPC_nightly is run to complete some
21 # additional administrative tasks (pool cleaning etc).
23 # BackupPC also listens for connections on a unix domain socket and
24 # the tcp port $Conf{ServerPort}, which are used by various
25 # sub-programs and the CGI script BackupPC_Admin for status reporting
26 # and user-initiated backup or backup cancel requests.
29 # Craig Barratt <cbarratt@users.sourceforge.net>
32 # Copyright (C) 2001-2003 Craig Barratt
34 # This program is free software; you can redistribute it and/or modify
35 # it under the terms of the GNU General Public License as published by
36 # the Free Software Foundation; either version 2 of the License, or
37 # (at your option) any later version.
39 # This program is distributed in the hope that it will be useful,
40 # but WITHOUT ANY WARRANTY; without even the implied warranty of
41 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 # GNU General Public License for more details.
44 # You should have received a copy of the GNU General Public License
45 # along with this program; if not, write to the Free Software
46 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
48 #========================================================================
50 # Version 2.1.0_CVS, released 3 Jul 2003.
52 # See http://backuppc.sourceforge.net.
54 #========================================================================
58 use vars qw(%Status %Info $Hosts);
59 use lib "/usr/local/BackupPC/lib";
61 use BackupPC::FileZIO;
70 ###########################################################################
71 # Handle command line options
72 ###########################################################################
74 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
75 print("usage: $0 [-d]\n");
79 ###########################################################################
80 # Initialize major data structures and variables
81 ###########################################################################
84 # Get an instance of BackupPC::Lib and get some shortcuts.
86 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
87 my $TopDir = $bpc->TopDir();
88 my $BinDir = $bpc->BinDir();
89 my %Conf = $bpc->Conf();
92 # Verify we are running as the correct user
94 if ( $Conf{BackupPCUserVerify}
95 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
96 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
100 # %Status maintain status information about each host.
101 # It is a hash of hashes, whose first index is the host.
106 # %Info is a hash giving general information about BackupPC status.
113 if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
114 die "couldn't parse $TopDir/log/status.pl: $@" if $@;
115 die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
116 die "couldn't run $TopDir/log/status.pl";
120 # %Jobs maintains information about currently running jobs.
121 # It is a hash of hashes, whose first index is the host.
126 # There are three command queues:
127 # - @UserQueue is a queue of user initiated backup requests.
128 # - @BgQueue is a queue of automatically scheduled backup requests.
129 # - @CmdQueue is a queue of administrative jobs, including tasks
130 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
131 # Each queue is an array of hashes. Each hash stores information
132 # about the command request.
139 # To quickly lookup if a given host is on a given queue, we keep
140 # a hash of flags for each queue type.
142 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
145 # One or more clients can connect to the server to get status information
146 # or request/cancel backups etc. The %Clients hash maintains information
147 # about each of these socket connections. The hash key is an incrementing
148 # number stored in $ClientConnCnt. Each entry is a hash that contains
149 # various information about the client connection.
155 # Read file descriptor mask used by select(). Every file descriptor
156 # on which we expect to read (or accept) has the corresponding bit
162 # Unix seconds when we next wakeup. A value of zero forces the scheduler
163 # to compute the next wakeup time.
168 # Name of signal saved by catch_signal
175 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
178 # Complete the rest of the initialization
182 ###########################################################################
184 ###########################################################################
188 # Check if we can/should run BackupPC_nightly
190 Main_TryToRun_nightly();
193 # Check if we can run a new command from @CmdQueue.
195 Main_TryToRun_CmdQueue();
198 # Check if we can run a new command from @UserQueue or @BgQueue.
200 Main_TryToRun_Bg_or_User_Queue();
203 # Do a select() to wait for the next interesting thing to happen
204 # (timeout, signal, someone sends a message, child dies etc).
206 my $fdRead = Main_Select();
209 # Process a signal if we received one.
212 Main_Process_Signal();
217 # Check if a timeout has occurred.
219 Main_Check_Timeout();
222 # Check for, and process, any messages (output) from our jobs
224 Main_Check_Job_Messages($fdRead);
227 # Check for, and process, any output from our clients. Also checks
228 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
230 Main_Check_Client_Messages($fdRead);
233 ############################################################################
236 # Main initialization routine. Called once at statup.
237 ############################################################################
240 umask($Conf{UmaskMode});
243 # Check for another running process, check that PASSWD is set and
244 # verify executables are configured correctly.
246 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
247 print(STDERR $bpc->timeStamp,
248 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
251 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
252 SendmailPath SshPath) ) {
253 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
254 print(STDERR $bpc->timeStamp,
255 "\$Conf{$progName} = '$Conf{$progName}' is not a"
256 . " valid executable program\n");
262 # daemonize by forking
264 defined(my $pid = fork) or die "Can't fork: $!";
265 exit if $pid; # parent exits
269 # Open the LOG file and redirect STDOUT, STDERR etc
274 # Read the hosts file (force a read).
276 exit(1) if ( !HostsUpdate(1) );
279 # Clean up %ENV for taint checking
281 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
282 $ENV{PATH} = $Conf{MyPath};
285 # Initialize server sockets
290 # Catch various signals
292 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
293 $SIG{$sig} = \&catch_signal;
297 # Report that we started, and update %Info.
299 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
300 $Info{ConfigModTime} = $bpc->ConfigMTime();
302 $Info{startTime} = time;
303 $Info{Version} = $bpc->{Version};
306 # Update the status left over form the last time BackupPC ran.
307 # Requeue any pending links.
309 foreach my $host ( sort(keys(%$Hosts)) ) {
310 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
312 # should we restart it? skip it for now.
314 $Status{$host}{state} = "Status_idle";
315 } elsif ( $Status{$host}{state} eq "Status_link_pending"
316 || $Status{$host}{state} eq "Status_link_running" ) {
319 $Status{$host}{state} = "Status_idle";
321 $Status{$host}{activeJob} = 0;
323 foreach my $host ( sort(keys(%Status)) ) {
324 next if ( defined($Hosts->{$host}) );
325 delete($Status{$host});
329 # Write out our initial status and save our PID
332 if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
338 # For unknown reasons there is a very infrequent error about not
339 # being able to coerce GLOBs inside the XS Data::Dumper. I've
340 # only seen this on a particular platform and perl version.
341 # For now the workaround appears to be use the perl version of
344 $Data::Dumper::Useqq = 1;
347 ############################################################################
348 # Main_TryToRun_nightly()
350 # Checks to see if we can/should run BackupPC_nightly or
351 # BackupPC_trashClean. If so we push the appropriate command onto
353 ############################################################################
354 sub Main_TryToRun_nightly
357 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
358 # BackupPC_nightly is run when the current job queue is empty.
359 # BackupPC_trashClean is run in the background always.
361 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
362 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
364 # This should only happen once at startup, but just in case this
365 # code will re-start BackupPC_trashClean if it quits
368 host => $bpc->trashJob,
371 cmd => ["$BinDir/BackupPC_trashClean"],
373 $CmdQueueOn{$bpc->trashJob} = 1;
375 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
377 host => $bpc->adminJob,
380 cmd => ["$BinDir/BackupPC_nightly"],
382 $CmdQueueOn{$bpc->adminJob} = 1;
383 $RunNightlyWhenIdle = 2;
387 ############################################################################
388 # Main_TryToRun_CmdQueue()
390 # Decide if we can run a new command from the @CmdQueue.
391 # We only run one of these at a time. The @CmdQueue is
392 # used to run BackupPC_link (for the corresponding host),
393 # BackupPC_trashClean, and BackupPC_nightly using a fake
394 # host name of $bpc->adminJob.
395 ############################################################################
396 sub Main_TryToRun_CmdQueue
399 if ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1 ) {
401 $req = pop(@CmdQueue);
403 $host = $req->{host};
404 if ( defined($Jobs{$host}) ) {
405 print(LOG $bpc->timeStamp,
406 "Botch on admin job for $host: already in use!!\n");
408 # This could happen during normal opertion: a user could
409 # request a backup while a BackupPC_link is queued from
410 # a previous backup. But it is unlikely. Just put this
411 # request back on the end of the queue.
413 unshift(@CmdQueue, $req);
416 $CmdQueueOn{$host} = 0;
417 my $cmd = $req->{cmd};
418 my $pid = open(FH, "-|");
419 if ( !defined($pid) ) {
420 print(LOG $bpc->timeStamp,
421 "can't fork for $host, request by $req->{user}\n");
428 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
431 $Jobs{$host}{pid} = $pid;
432 $Jobs{$host}{fh} = *FH;
433 $Jobs{$host}{fn} = fileno(FH);
434 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
435 $Jobs{$host}{startTime} = time;
436 $Jobs{$host}{reqTime} = $req->{reqTime};
437 $cmd = join(" ", @$cmd);
438 $Jobs{$host}{cmd} = $cmd;
439 $Jobs{$host}{type} = $Status{$host}{type};
440 $Status{$host}{state} = "Status_link_running";
441 $Status{$host}{activeJob} = 1;
442 $Status{$host}{endTime} = time;
443 $CmdJob = $host if ( $host ne $bpc->trashJob );
444 $cmd =~ s/$BinDir\///g;
445 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
449 ############################################################################
450 # Main_TryToRun_Bg_or_User_Queue()
452 # Decide if we can run any new backup requests from @BgQueue
453 # or @UserQueue. Several of these can be run at the same time
454 # based on %Conf settings. Jobs from @UserQueue take priority,
455 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
456 # simultaneous jobs can run from @UserQueue. After @UserQueue
457 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
459 ############################################################################
460 sub Main_TryToRun_Bg_or_User_Queue
463 while ( $RunNightlyWhenIdle == 0 ) {
465 my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
466 my $nJobs = keys(%Jobs);
468 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
470 $nJobs-- if ( $CmdJob ne "" );
471 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
472 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
473 && @UserQueue > 0 ) {
474 $req = pop(@UserQueue);
475 if ( defined($Jobs{$req->{host}}) ) {
476 push(@deferUserQueue, $req);
479 push(@args, $req->{doFull} ? "-f" : "-i")
480 if ( !$req->{restore} );
481 $UserQueueOn{$req->{host}} = 0;
482 } elsif ( $nJobs < $Conf{MaxBackups}
483 && (@CmdQueue + $nJobs)
484 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
487 if ( time - $Info{DUlastValueTime} >= 60 ) {
489 # Update our notion of disk usage no more than
492 $du = $bpc->CheckFileSystemUsage($TopDir);
493 $Info{DUlastValue} = $du;
494 $Info{DUlastValueTime} = time;
497 # if we recently checked it then just use the old value
499 $du = $Info{DUlastValue};
501 if ( $Info{DUDailyMaxReset} ) {
502 $Info{DUDailyMaxStartTime} = time;
503 $Info{DUDailyMaxReset} = 0;
504 $Info{DUDailyMax} = 0;
506 if ( $du > $Info{DUDailyMax} ) {
507 $Info{DUDailyMax} = $du;
508 $Info{DUDailyMaxTime} = time;
510 if ( $du > $Conf{DfMaxUsagePct} ) {
511 my $nSkip = @BgQueue + @deferBgQueue;
512 print(LOG $bpc->timeStamp,
513 "Disk too full ($du%%); skipping $nSkip hosts\n");
514 $Info{DUDailySkipHostCnt} += $nSkip;
520 $req = pop(@BgQueue);
521 if ( defined($Jobs{$req->{host}}) ) {
522 push(@deferBgQueue, $req);
525 $BgQueueOn{$req->{host}} = 0;
527 while ( @deferBgQueue ) {
528 push(@BgQueue, pop(@deferBgQueue));
530 while ( @deferUserQueue ) {
531 push(@UserQueue, pop(@deferUserQueue));
535 $host = $req->{host};
536 my $user = $req->{user};
537 if ( $req->{restore} ) {
538 $progName = "BackupPC_restore";
540 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
542 $progName = "BackupPC_dump";
544 push(@args, "-d") if ( $req->{dhcp} );
545 push(@args, "-e") if ( $req->{dumpExpire} );
548 my $pid = open(FH, "-|");
549 if ( !defined($pid) ) {
550 print(LOG $bpc->timeStamp,
551 "can't fork to run $progName for $host, request by $user\n");
557 exec("$BinDir/$progName", @args);
558 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
561 $Jobs{$host}{pid} = $pid;
562 $Jobs{$host}{fh} = *FH;
563 $Jobs{$host}{fn} = fileno(FH);
564 $Jobs{$host}{dhcp} = $req->{dhcp};
565 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
566 $Jobs{$host}{startTime} = time;
567 $Jobs{$host}{reqTime} = $req->{reqTime};
568 $Jobs{$host}{userReq} = $req->{userReq};
569 $Jobs{$host}{cmd} = join(" ", $progName, @args);
570 $Jobs{$host}{user} = $user;
571 $Jobs{$host}{type} = $type;
572 $Status{$host}{userReq} = $req->{userReq}
573 if ( defined($Hosts->{$host}) );
574 if ( !$req->{dhcp} ) {
575 $Status{$host}{state} = "Status_".$type."_starting";
576 $Status{$host}{activeJob} = 1;
577 $Status{$host}{startTime} = time;
578 $Status{$host}{endTime} = "";
583 ############################################################################
586 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
587 # and then do a select() to wait for the next thing to happen
588 # (timeout, signal, someone sends a message, child dies etc).
589 ############################################################################
592 if ( $NextWakeup <= 0 ) {
594 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
596 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
598 my($currHours) = $hour + $min / 60 + $sec / 3600;
599 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
600 my($mesg) = $bpc->ConfigRead()
601 || "Re-read config file because mtime changed";
602 print(LOG $bpc->timeStamp, "$mesg\n");
603 %Conf = $bpc->Conf();
604 $Info{ConfigModTime} = $bpc->ConfigMTime();
605 umask($Conf{UmaskMode});
609 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
610 next if ( $t < 0 || $t > 24 );
611 my $tomorrow = $t + 24;
613 || ($tomorrow - $currHours > 0
614 && $delta > $tomorrow - $currHours) ) {
615 $delta = $tomorrow - $currHours;
616 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
619 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
620 $delta = $t - $currHours;
621 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
624 $NextWakeup = time + $delta * 3600;
625 $Info{nextWakeup} = $NextWakeup;
626 print(LOG $bpc->timeStamp, "Next wakeup is ",
627 $bpc->timeStamp($NextWakeup, 1), "\n");
630 # Call select(), waiting until either a signal, a timeout,
631 # any output from our jobs, or any messages from clients
633 # select() is where we (hopefully) spend most of our time blocked...
635 my $timeout = $NextWakeup - time;
636 $timeout = 1 if ( $timeout <= 0 );
638 select(my $rout = $FDread, undef, $ein, $timeout);
643 ############################################################################
644 # Main_Process_Signal()
647 ############################################################################
648 sub Main_Process_Signal
653 if ( $SigName eq "HUP" ) {
654 my($mesg) = $bpc->ConfigRead()
655 || "Re-read config file because of a SIG_HUP";
656 print(LOG $bpc->timeStamp, "$mesg\n");
657 $Info{ConfigModTime} = $bpc->ConfigMTime();
658 %Conf = $bpc->Conf();
659 umask($Conf{UmaskMode});
663 } elsif ( $SigName ) {
664 print(LOG $bpc->timeStamp, "Got signal $SigName... cleaning up\n");
666 foreach my $host ( keys(%Jobs) ) {
667 kill(2, $Jobs{$host}{pid});
670 foreach my $host ( keys(%Jobs) ) {
671 kill(9, $Jobs{$host}{pid});
676 unlink("$TopDir/log/BackupPC.pid");
682 ############################################################################
683 # Main_Check_Timeout()
685 # Check if a timeout has occured, and if so, queue all the PCs for backups.
686 # Also does log file aging on the first timeout after midnight.
687 ############################################################################
688 sub Main_Check_Timeout
693 return if ( time < $NextWakeup || $NextWakeup <= 0 );
695 if ( $FirstWakeup ) {
697 # This is the first wakeup after midnight. Do log file aging
698 # and various house keeping.
701 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
702 . " %d skipped hosts\n",
703 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
704 $Info{DUDailySkipHostCnt});
705 $Info{DUDailyMaxReset} = 1;
706 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
707 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
708 $Info{DUDailySkipHostCnt} = 0;
709 my $lastLog = $Conf{MaxOldLogFiles} - 1;
710 if ( -f "$TopDir/log/LOG.$lastLog" ) {
711 print(LOG $bpc->timeStamp,
712 "Removing $TopDir/log/LOG.$lastLog\n");
713 unlink("$TopDir/log/LOG.$lastLog");
715 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
716 print(LOG $bpc->timeStamp,
717 "Removing $TopDir/log/LOG.$lastLog.z\n");
718 unlink("$TopDir/log/LOG.$lastLog.z");
720 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
721 . "LOG.1 -> ... -> LOG.$lastLog\n");
723 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
725 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
726 if ( -f "$TopDir/log/LOG.$i" );
727 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
728 if ( -f "$TopDir/log/LOG.$i.z" );
731 # Compress the log file LOG -> LOG.0.z (if enabled).
732 # Otherwise, just rename LOG -> LOG.0.
734 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
735 "$TopDir/log/LOG.0.z",
737 $Conf{CompressLevel}, 1);
740 # Remember to run nightly script after current jobs are done
742 $RunNightlyWhenIdle = 1;
745 # Write out the current status and then queue all the PCs
749 %BgQueueOn = () if ( @BgQueue == 0 );
750 %UserQueueOn = () if ( @UserQueue == 0 );
751 %CmdQueueOn = () if ( @CmdQueue == 0 );
755 ############################################################################
756 # Main_Check_Job_Messages($fdRead)
758 # Check if select() says we have bytes waiting from any of our jobs.
759 # Handle each of the messages when complete (newline terminated).
760 ############################################################################
761 sub Main_Check_Job_Messages
764 foreach my $host ( keys(%Jobs) ) {
765 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
768 # do a last check to make sure there is something to read so
769 # we are absolutely sure we won't block.
771 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
772 if ( !select($readMask, undef, undef, 0.0) ) {
773 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
774 . " nothing to read from $host. Debug dump:\n");
775 my($dump) = Data::Dumper->new(
776 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
777 [qw(*Clients, *Jobs *FDread, *fdRead)]);
779 print(LOG $dump->Dump);
782 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
783 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
785 # Process any complete lines of output from this jobs.
786 # Any output to STDOUT or STDERR from the children is processed here.
788 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
790 $Jobs{$host}{mesg} = $2;
791 if ( $Jobs{$host}{dhcp} ) {
792 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
793 my $newHost = $bpc->uriUnesc($2);
794 if ( defined($Jobs{$newHost}) ) {
795 print(LOG $bpc->timeStamp,
796 "Backup on $newHost is already running\n");
797 kill(2, $Jobs{$host}{pid});
801 $Jobs{$host}{dhcpHostIP} = $host;
802 $Status{$newHost}{dhcpHostIP} = $host;
803 $Jobs{$newHost} = $Jobs{$host};
804 delete($Jobs{$host});
806 $Status{$host}{state} = "Status_backup_starting";
807 $Status{$host}{activeJob} = 1;
808 $Status{$host}{startTime} = $Jobs{$host}{startTime};
809 $Status{$host}{endTime} = "";
810 $Jobs{$host}{dhcp} = 0;
812 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
814 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
815 $Jobs{$host}{type} = $1;
816 $Jobs{$host}{shareName} = $2;
817 print(LOG $bpc->timeStamp,
818 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
819 $Jobs{$host}{dhcpHostIP}
820 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
821 ", share=$Jobs{$host}{shareName})\n");
822 $Status{$host}{state} = "Status_backup_in_progress";
823 $Status{$host}{reason} = "";
824 $Status{$host}{type} = $1;
825 $Status{$host}{startTime} = time;
826 $Status{$host}{deadCnt} = 0;
827 $Status{$host}{aliveCnt}++;
828 $Status{$host}{dhcpCheckCnt}--
829 if ( $Status{$host}{dhcpCheckCnt} > 0 );
830 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
831 $Jobs{$host}{xferPid} = $1;
832 } elsif ( $mesg =~ /^started_restore/ ) {
833 $Jobs{$host}{type} = "restore";
834 print(LOG $bpc->timeStamp,
835 "Started restore on $host"
836 . " (pid=$Jobs{$host}{pid})\n");
837 $Status{$host}{state} = "Status_restore_in_progress";
838 $Status{$host}{reason} = "";
839 $Status{$host}{type} = "restore";
840 $Status{$host}{startTime} = time;
841 $Status{$host}{deadCnt} = 0;
842 $Status{$host}{aliveCnt}++;
843 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
844 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
845 $Status{$host}{reason} = "Reason_backup_done";
846 delete($Status{$host}{error});
847 delete($Status{$host}{errorTime});
848 $Status{$host}{endTime} = time;
849 } elsif ( $mesg =~ /^restore complete/ ) {
850 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
851 $Status{$host}{reason} = "Reason_restore_done";
852 delete($Status{$host}{error});
853 delete($Status{$host}{errorTime});
854 $Status{$host}{endTime} = time;
855 } elsif ( $mesg =~ /^nothing to do/ ) {
856 if ( $Status{$host}{reason} ne "Reason_backup_failed"
857 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
858 $Status{$host}{state} = "Status_idle";
859 $Status{$host}{reason} = "Reason_nothing_to_do";
860 $Status{$host}{startTime} = time;
862 $Status{$host}{dhcpCheckCnt}--
863 if ( $Status{$host}{dhcpCheckCnt} > 0 );
864 } elsif ( $mesg =~ /^no ping response/
865 || $mesg =~ /^ping too slow/
866 || $mesg =~ /^host not found/ ) {
867 $Status{$host}{state} = "Status_idle";
868 if ( $Status{$host}{userReq}
869 || $Status{$host}{reason} ne "Reason_backup_failed"
870 || $Status{$host}{error} =~ /^aborted by user/ ) {
871 $Status{$host}{reason} = "Reason_no_ping";
872 $Status{$host}{error} = $mesg;
873 $Status{$host}{startTime} = time;
875 $Status{$host}{deadCnt}++;
876 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
877 $Status{$host}{aliveCnt} = 0;
879 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
880 $Status{$host}{state} = "Status_idle";
881 $Status{$host}{reason} = "Reason_backup_failed";
882 $Status{$host}{error} = $1;
883 $Status{$host}{errorTime} = time;
884 $Status{$host}{endTime} = time;
885 print(LOG $bpc->timeStamp, "Backup failed on $host ($1)\n");
886 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
887 $Status{$host}{state} = "Status_idle";
888 $Status{$host}{reason} = "Reason_restore_failed";
889 $Status{$host}{error} = $1;
890 $Status{$host}{errorTime} = time;
891 $Status{$host}{endTime} = time;
892 print(LOG $bpc->timeStamp, "Restore failed on $host ($1)\n");
893 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
894 print(LOG $bpc->timeStamp, "$1\n");
895 } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
896 my @f = split(/,/, $1);
897 $Info{"$f[0]FileCnt"} = $f[1];
898 $Info{"$f[0]DirCnt"} = $f[2];
899 $Info{"$f[0]Kb"} = $f[3];
900 $Info{"$f[0]Kb2"} = $f[4];
901 $Info{"$f[0]KbRm"} = $f[5];
902 $Info{"$f[0]FileCntRm"} = $f[6];
903 $Info{"$f[0]FileCntRep"} = $f[7];
904 $Info{"$f[0]FileRepMax"} = $f[8];
905 $Info{"$f[0]FileCntRename"} = $f[9];
906 $Info{"$f[0]FileLinkMax"} = $f[10];
907 $Info{"$f[0]Time"} = time;
908 printf(LOG "%s%s nightly clean removed %d files of"
910 $bpc->timeStamp, ucfirst($f[0]),
911 $Info{"$f[0]FileCntRm"},
912 $Info{"$f[0]KbRm"} / (1000 * 1024));
913 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
914 . "%d max chain, %d max links), %d directories\n",
915 $bpc->timeStamp, ucfirst($f[0]),
916 $Info{"$f[0]Kb"} / (1000 * 1024),
917 $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
918 $Info{"$f[0]FileRepMax"},
919 $Info{"$f[0]FileLinkMax"}, $Info{"$f[0]DirCnt"});
920 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
921 $RunNightlyWhenIdle = 0;
922 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
923 $Jobs{$host}{processState} = $1;
924 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
926 $Status{$h}{needLink} = 1;
928 print(LOG $bpc->timeStamp, "$host: $mesg\n");
932 # shut down the client connection if we read EOF
934 if ( $nbytes <= 0 ) {
935 close($Jobs{$host}{fh});
936 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
937 if ( $CmdJob eq $host ) {
938 my $cmd = $Jobs{$host}{cmd};
939 $cmd =~ s/$BinDir\///g;
940 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
941 $Status{$host}{state} = "Status_idle";
942 $Status{$host}{endTime} = time;
944 $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
945 && $RunNightlyWhenIdle );
948 # Queue BackupPC_link to complete the backup
949 # processing for this host.
951 if ( defined($Status{$host})
952 && ($Status{$host}{reason} eq "Reason_backup_done"
953 || $Status{$host}{needLink}) ) {
955 } elsif ( defined($Status{$host}) ) {
956 $Status{$host}{state} = "Status_idle";
959 delete($Jobs{$host});
960 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
964 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
965 # do a pass over %Status updating the deadCnt and aliveCnt for
966 # DHCP hosts. The reason we need to do this later is we can't
967 # be sure whether a DHCP host is alive or dead until we have passed
968 # over all the DHCP pool.
970 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
971 foreach my $host ( keys(%Status) ) {
972 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
973 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
974 $Status{$host}{dhcpCheckCnt} = 0;
975 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
976 $Status{$host}{aliveCnt} = 0;
981 ############################################################################
982 # Main_Check_Client_Messages($fdRead)
984 # Check for, and process, any output from our clients. Also checks
985 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
986 ############################################################################
987 sub Main_Check_Client_Messages
990 foreach my $client ( keys(%Clients) ) {
991 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
994 # do a last check to make sure there is something to read so
995 # we are absolutely sure we won't block.
997 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
998 if ( !select($readMask, undef, undef, 0.0) ) {
999 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1000 . " nothing to read from $client. Debug dump:\n");
1001 my($dump) = Data::Dumper->new(
1002 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1003 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1005 print(LOG $dump->Dump);
1008 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1009 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1011 # Process any complete lines received from this client.
1013 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1016 $Clients{$client}{mesg} = $2;
1018 # Authenticate the message by checking the MD5 digest
1020 my $md5 = Digest::MD5->new;
1021 if ( $cmd !~ /^(.{22}) (.*)/
1022 || ($md5->add($Clients{$client}{seed}
1023 . $Clients{$client}{mesgCnt}
1024 . $Conf{ServerMesgSecret} . $2),
1025 $md5->b64digest ne $1) ) {
1026 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1027 . " client '$Clients{$client}{clientName}':"
1028 . " shutting down client connection\n");
1032 $Clients{$client}{mesgCnt}++;
1034 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1038 $host = $bpc->uriUnesc($host);
1039 if ( $CmdJob ne $host && defined($Status{$host})
1040 && defined($Jobs{$host}) ) {
1041 print(LOG $bpc->timeStamp,
1042 "Stopping current $Jobs{$host}{type} of $host,"
1043 . " request by $user (backoff=$backoff)\n");
1044 kill(2, $Jobs{$host}{pid});
1046 # Don't close the pipe now; wait until the child
1047 # really exits later. Otherwise close() will
1048 # block until the child has exited.
1050 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1051 ##close($Jobs{$host}{fh});
1052 ##delete($Jobs{$host});
1054 $Status{$host}{state} = "Status_idle";
1055 if ( $Jobs{$host}{type} eq "restore" ) {
1056 $Status{$host}{reason}
1057 = "Reason_restore_canceled_by_user";
1059 $Status{$host}{reason}
1060 = "Reason_backup_canceled_by_user";
1062 $Status{$host}{activeJob} = 0;
1063 $Status{$host}{startTime} = time;
1064 $reply = "ok: $Jobs{$host}{type} of $host cancelled";
1065 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1066 print(LOG $bpc->timeStamp,
1067 "Stopping pending backup of $host,"
1068 . " request by $user (backoff=$backoff)\n");
1069 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1070 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1071 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1072 $reply = "ok: pending backup of $host cancelled";
1074 print(LOG $bpc->timeStamp,
1075 "Nothing to do for stop backup of $host,"
1076 . " request by $user (backoff=$backoff)\n");
1077 $reply = "ok: no backup was pending or running";
1079 if ( defined($Status{$host}) && $backoff ne "" ) {
1080 if ( $backoff > 0 ) {
1081 $Status{$host}{backoffTime} = time + $backoff * 3600;
1083 delete($Status{$host}{backoffTime});
1086 } elsif ( $cmd =~ /^backup all$/ ) {
1088 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1093 $host = $bpc->uriUnesc($host);
1094 $hostIP = $bpc->uriUnesc($hostIP);
1095 if ( !defined($Status{$host}) ) {
1096 print(LOG $bpc->timeStamp,
1097 "User $user requested backup of unknown host"
1099 $reply = "error: unknown host $host";
1100 } elsif ( defined($Jobs{$host})
1101 && $Jobs{$host}{type} ne "restore" ) {
1102 print(LOG $bpc->timeStamp,
1103 "User $user requested backup of $host,"
1104 . " but one is currently running\n");
1105 $reply = "error: backup of $host is already running";
1107 print(LOG $bpc->timeStamp,
1108 "User $user requested backup of $host"
1110 if ( $BgQueueOn{$hostIP} ) {
1111 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1112 $BgQueueOn{$hostIP} = 0;
1114 if ( $UserQueueOn{$hostIP} ) {
1115 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1116 $UserQueueOn{$hostIP} = 0;
1118 unshift(@UserQueue, {
1124 dhcp => $hostIP eq $host ? 0 : 1,
1126 $UserQueueOn{$hostIP} = 1;
1127 $reply = "ok: requested backup of $host";
1129 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1133 my $reqFileName = $4;
1134 $host = $bpc->uriUnesc($host);
1135 $hostIP = $bpc->uriUnesc($hostIP);
1136 if ( !defined($Status{$host}) ) {
1137 print(LOG $bpc->timeStamp,
1138 "User $user requested restore to unknown host"
1140 $reply = "restore error: unknown host $host";
1142 print(LOG $bpc->timeStamp,
1143 "User $user requested restore to $host"
1145 unshift(@UserQueue, {
1148 reqFileName => $reqFileName,
1154 $UserQueueOn{$host} = 1;
1155 if ( defined($Jobs{$host}) ) {
1156 $reply = "ok: requested restore of $host, but a"
1157 . " job is currently running,"
1158 . " so this request will start later";
1160 $reply = "ok: requested restore of $host";
1163 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1165 my($dump, @values, @names);
1166 foreach my $type ( split(/\s+/, $args) ) {
1167 if ( $type =~ /^queues/ ) {
1168 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1169 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1170 } elsif ( $type =~ /^jobs/ ) {
1171 push(@values, \%Jobs);
1172 push(@names, qw(*Jobs));
1173 } elsif ( $type =~ /^queueLen/ ) {
1175 BgQueue => scalar(@BgQueue),
1176 UserQueue => scalar(@UserQueue),
1177 CmdQueue => scalar(@CmdQueue),
1179 push(@names, qw(*QueueLen));
1180 } elsif ( $type =~ /^info/ ) {
1181 push(@values, \%Info);
1182 push(@names, qw(*Info));
1183 } elsif ( $type =~ /^hosts/ ) {
1184 push(@values, \%Status);
1185 push(@names, qw(*Status));
1186 } elsif ( $type =~ /^host\((.*)\)/ ) {
1187 my $h = $bpc->uriUnesc($1);
1188 if ( defined($Status{$h}) ) {
1191 BgQueueOn => $BgQueueOn{$h},
1192 UserQueueOn => $UserQueueOn{$h},
1193 CmdQueueOn => $CmdQueueOn{$h},
1195 push(@names, qw(*StatusHost));
1197 print(LOG $bpc->timeStamp,
1198 "Unknown host $h for status request\n");
1201 print(LOG $bpc->timeStamp,
1202 "Unknown status request $type\n");
1205 $dump = Data::Dumper->new(\@values, \@names);
1207 $reply = $dump->Dump;
1208 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1210 $host = $bpc->uriUnesc($host);
1212 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1213 print(LOG $bpc->timeStamp, "$1\n");
1214 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1218 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1219 $reply = "error: bad command $cmd";
1222 # send a reply to the client, at a minimum "ok\n".
1224 $reply = "ok" if ( $reply eq "" );
1226 syswrite($Clients{$client}{fh}, $reply, length($reply));
1229 # Detect possible denial-of-service attack from sending a huge line
1230 # (ie: never terminated). 32K seems to be plenty big enough as
1233 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1234 print(LOG $bpc->timeStamp, "Line too long from client"
1235 . " '$Clients{$client}{clientName}':"
1236 . " shutting down client connection\n");
1240 # Shut down the client connection if we read EOF
1242 if ( $nbytes <= 0 ) {
1243 close($Clients{$client}{fh});
1244 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1245 delete($Clients{$client});
1249 # Accept any new connections on each of our listen sockets
1251 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1253 my $paddr = accept(CLIENT, SERVER_UNIX);
1255 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1256 $Clients{$ClientConnCnt}{mesg} = "";
1257 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1258 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1259 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1261 # Generate and send unique seed for MD5 digests to avoid
1262 # replay attacks. See BackupPC::Lib::ServerMesg().
1264 my $seed = time . ",$ClientConnCnt,$$,0\n";
1265 $Clients{$ClientConnCnt}{seed} = $seed;
1266 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1267 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1269 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1271 my $paddr = accept(CLIENT, SERVER_INET);
1272 my($port,$iaddr) = sockaddr_in($paddr);
1273 my $name = gethostbyaddr($iaddr, AF_INET);
1275 $Clients{$ClientConnCnt}{mesg} = "";
1276 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1277 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1278 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1279 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1281 # Generate and send unique seed for MD5 digests to avoid
1282 # replay attacks. See BackupPC::Lib::ServerMesg().
1284 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1285 $Clients{$ClientConnCnt}{seed} = $seed;
1286 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1287 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1291 ###########################################################################
1292 # Miscellaneous subroutines
1293 ###########################################################################
1296 # Write the current status to $TopDir/log/status.pl
1300 my($dump) = Data::Dumper->new(
1301 [ \%Info, \%Status],
1302 [qw(*Info *Status)]);
1304 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1305 print(STATUS $dump->Dump);
1311 # Queue all the hosts for backup. This means queuing all the fixed
1312 # ip hosts and all the dhcp address ranges. We also additionally
1313 # queue the dhcp hosts with a -e flag to check for expired dumps.
1317 foreach my $host ( sort(keys(%$Hosts)) ) {
1318 delete($Status{$host}{backoffTime})
1319 if ( defined($Status{$host}{backoffTime})
1320 && $Status{$host}{backoffTime} < time );
1321 next if ( defined($Jobs{$host})
1322 || $BgQueueOn{$host}
1323 || $UserQueueOn{$host}
1324 || $CmdQueueOn{$host} );
1325 if ( $Hosts->{$host}{dhcp} ) {
1326 $Status{$host}{dhcpCheckCnt}++;
1327 if ( $RunNightlyWhenIdle ) {
1329 # Once per night queue a check for DHCP hosts that just
1330 # checks for expired dumps. We need to do this to handle
1331 # the case when a DHCP host has not been on the network for
1332 # a long time, and some of the old dumps need to be expired.
1333 # Normally expiry checks are done by BackupPC_dump only
1334 # after the DHCP hosts has been detected on the network.
1337 {host => $host, user => "BackupPC", reqTime => time,
1338 dhcp => 0, dumpExpire => 1});
1339 $BgQueueOn{$host} = 1;
1343 # this is a fixed ip host: queue it
1346 {host => $host, user => "BackupPC", reqTime => time,
1347 dhcp => $Hosts->{$host}{dhcp}});
1348 $BgQueueOn{$host} = 1;
1351 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1352 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1353 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1354 next if ( defined($Jobs{$ipAddr})
1355 || $BgQueueOn{$ipAddr}
1356 || $UserQueueOn{$ipAddr}
1357 || $CmdQueueOn{$ipAddr} );
1359 # this is a potential dhcp ip address (we don't know the
1360 # host name yet): queue it
1363 {host => $ipAddr, user => "BackupPC", reqTime => time,
1365 $BgQueueOn{$ipAddr} = 1;
1371 # Queue a BackupPC_link for the given host
1377 return if ( $CmdQueueOn{$host} );
1378 $Status{$host}{state} = "Status_link_pending";
1379 $Status{$host}{needLink} = 0;
1380 unshift(@CmdQueue, {
1384 cmd => ["$BinDir/BackupPC_link", $host],
1386 $CmdQueueOn{$host} = 1;
1390 # Read the hosts file, and update Status if any hosts have been
1391 # added or deleted. We also track the mtime so the only need to
1392 # update the hosts file on changes.
1394 # This function is called at startup, SIGHUP, and on each wakeup.
1395 # It returns 1 on success and undef on failure.
1402 # Nothing to do if we already have the current hosts file
1404 return 1 if ( !$force && defined($Hosts)
1405 && $Info{HostsModTime} == $bpc->HostsMTime() );
1406 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1407 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1410 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1412 $Info{HostsModTime} = $bpc->HostsMTime();
1414 # Now update %Status in case any hosts have been added or deleted
1416 foreach my $host ( sort(keys(%$Hosts)) ) {
1417 next if ( defined($Status{$host}) );
1418 $Status{$host}{state} = "Status_idle";
1419 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1421 foreach my $host ( sort(keys(%Status)) ) {
1422 next if ( $host eq $bpc->trashJob
1423 || $host eq $bpc->adminJob
1424 || defined($Hosts->{$host})
1425 || defined($Jobs{$host})
1426 || $BgQueueOn{$host}
1427 || $UserQueueOn{$host}
1428 || $CmdQueueOn{$host} );
1429 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1430 delete($Status{$host});
1436 # Remember the signal name for later processing
1442 foreach my $host ( keys(%Jobs) ) {
1443 kill(2, $Jobs{$host}{pid});
1446 # In case we are inside the exit handler, reopen the log file
1450 print(LOG "Fatal error: unhandled signal $SigName\n");
1451 unlink("$TopDir/log/BackupPC.pid");
1452 confess("Got new signal $SigName... quitting\n");
1459 # Open the log file and point STDOUT and STDERR there too
1463 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1464 open(LOG, ">>$TopDir/log/LOG")
1465 || die("Can't create LOG file $TopDir/log/LOG");
1468 open(STDOUT, ">&LOG");
1469 open(STDERR, ">&LOG");
1470 select(LOG); $| = 1;
1471 select(STDERR); $| = 1;
1472 select(STDOUT); $| = 1;
1476 # Initialize the unix-domain and internet-domain sockets that
1477 # we listen to for client connections (from the CGI script and
1478 # some of the BackupPC sub-programs).
1480 sub ServerSocketInit
1482 if ( !defined(fileno(SERVER_UNIX)) ) {
1484 # one-time only: initialize unix-domain socket
1486 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1487 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1490 my $sockFile = "$TopDir/log/BackupPC.sock";
1492 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1493 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1496 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1497 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1500 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1502 return if ( $ServerInetPort == $Conf{ServerPort} );
1503 if ( $ServerInetPort > 0 ) {
1504 vec($FDread, fileno(SERVER_INET), 1) = 0;
1506 $ServerInetPort = -1;
1508 if ( $Conf{ServerPort} > 0 ) {
1510 # Setup a socket to listen on $Conf{ServerPort}
1512 my $proto = getprotobyname('tcp');
1513 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1514 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1517 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1518 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1521 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1522 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1525 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1526 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1529 vec($FDread, fileno(SERVER_INET), 1) = 1;
1530 $ServerInetPort = $Conf{ServerPort};