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 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.0.0beta2, released 13 Apr 2003.
52 # See http://backuppc.sourceforge.net.
54 #========================================================================
57 use vars qw(%Status %Info $Hosts);
58 use lib "/usr/local/BackupPC/lib";
60 use BackupPC::FileZIO;
69 ###########################################################################
70 # Handle command line options
71 ###########################################################################
73 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
74 print("usage: $0 [-d]\n");
78 ###########################################################################
79 # Initialize major data structures and variables
80 ###########################################################################
83 # Get an instance of BackupPC::Lib and get some shortcuts.
85 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
86 my $TopDir = $bpc->TopDir();
87 my $BinDir = $bpc->BinDir();
88 my %Conf = $bpc->Conf();
91 # Verify we are running as the correct user
93 if ( $Conf{BackupPCUserVerify}
94 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
95 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
99 # %Status maintain status information about each host.
100 # It is a hash of hashes, whose first index is the host.
105 # %Info is a hash giving general information about BackupPC status.
112 if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
113 die "couldn't parse $TopDir/log/status.pl: $@" if $@;
114 die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
115 die "couldn't run $TopDir/log/status.pl";
119 # %Jobs maintains information about currently running jobs.
120 # It is a hash of hashes, whose first index is the host.
125 # There are three command queues:
126 # - @UserQueue is a queue of user initiated backup requests.
127 # - @BgQueue is a queue of automatically scheduled backup requests.
128 # - @CmdQueue is a queue of administrative jobs, including tasks
129 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
130 # Each queue is an array of hashes. Each hash stores information
131 # about the command request.
138 # To quickly lookup if a given host is on a given queue, we keep
139 # a hash of flags for each queue type.
141 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
144 # One or more clients can connect to the server to get status information
145 # or request/cancel backups etc. The %Clients hash maintains information
146 # about each of these socket connections. The hash key is an incrementing
147 # number stored in $ClientConnCnt. Each entry is a hash that contains
148 # various information about the client connection.
154 # Read file descriptor mask used by select(). Every file descriptor
155 # on which we expect to read (or accept) has the corresponding bit
161 # Unix seconds when we next wakeup. A value of zero forces the scheduler
162 # to compute the next wakeup time.
167 # Name of signal saved by catch_signal
174 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
177 # Complete the rest of the initialization
181 ###########################################################################
183 ###########################################################################
187 # Check if we can/should run BackupPC_nightly
189 Main_TryToRun_nightly();
192 # Check if we can run a new command from @CmdQueue.
194 Main_TryToRun_CmdQueue();
197 # Check if we can run a new command from @UserQueue or @BgQueue.
199 Main_TryToRun_Bg_or_User_Queue();
202 # Do a select() to wait for the next interesting thing to happen
203 # (timeout, signal, someone sends a message, child dies etc).
205 my $fdRead = Main_Select();
208 # Process a signal if we received one.
211 Main_Process_Signal();
216 # Check if a timeout has occurred.
218 Main_Check_Timeout();
221 # Check for, and process, any messages (output) from our jobs
223 Main_Check_Job_Messages($fdRead);
226 # Check for, and process, any output from our clients. Also checks
227 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
229 Main_Check_Client_Messages($fdRead);
232 ############################################################################
235 # Main initialization routine. Called once at statup.
236 ############################################################################
239 umask($Conf{UmaskMode});
242 # Check for another running process, check that PASSWD is set and
243 # verify executables are configured correctly.
245 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
246 print(STDERR $bpc->timeStamp,
247 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
250 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
251 SendmailPath SshPath) ) {
252 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
253 print(STDERR $bpc->timeStamp,
254 "\$Conf{$progName} = '$Conf{$progName}' is not a"
255 . " valid executable program\n");
261 # daemonize by forking
263 defined(my $pid = fork) or die "Can't fork: $!";
264 exit if $pid; # parent exits
268 # Open the LOG file and redirect STDOUT, STDERR etc
273 # Read the hosts file (force a read).
275 exit(1) if ( !HostsUpdate(1) );
278 # Clean up %ENV for taint checking
280 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
281 $ENV{PATH} = $Conf{MyPath};
284 # Initialize server sockets
289 # Catch various signals
291 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
292 $SIG{$sig} = \&catch_signal;
296 # Report that we started, and update %Info.
298 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
299 $Info{ConfigModTime} = $bpc->ConfigMTime();
301 $Info{startTime} = time;
302 $Info{Version} = $bpc->{Version};
305 # Update the status left over form the last time BackupPC ran.
306 # Requeue any pending links.
308 foreach my $host ( sort(keys(%$Hosts)) ) {
309 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
311 # should we restart it? skip it for now.
313 $Status{$host}{state} = "Status_idle";
314 } elsif ( $Status{$host}{state} eq "Status_link_pending"
315 || $Status{$host}{state} eq "Status_link_running" ) {
318 $Status{$host}{state} = "Status_idle";
320 $Status{$host}{activeJob} = 0;
322 foreach my $host ( sort(keys(%Status)) ) {
323 next if ( defined($Hosts->{$host}) );
324 delete($Status{$host});
328 # Write out our initial status and save our PID
331 if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
337 # For unknown reasons there is a very infrequent error about not
338 # being able to coerce GLOBs inside the XS Data::Dumper. I've
339 # only seen this on a particular platform and perl version.
340 # For now the workaround appears to be use the perl version of
343 $Data::Dumper::Useqq = 1;
346 ############################################################################
347 # Main_TryToRun_nightly()
349 # Checks to see if we can/should run BackupPC_nightly or
350 # BackupPC_trashClean. If so we push the appropriate command onto
352 ############################################################################
353 sub Main_TryToRun_nightly
356 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
357 # BackupPC_nightly is run when the current job queue is empty.
358 # BackupPC_trashClean is run in the background always.
360 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
361 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
363 # This should only happen once at startup, but just in case this
364 # code will re-start BackupPC_trashClean if it quits
367 host => $bpc->trashJob,
370 cmd => ["$BinDir/BackupPC_trashClean"],
372 $CmdQueueOn{$bpc->trashJob} = 1;
374 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
376 host => $bpc->adminJob,
379 cmd => ["$BinDir/BackupPC_nightly"],
381 $CmdQueueOn{$bpc->adminJob} = 1;
382 $RunNightlyWhenIdle = 2;
386 ############################################################################
387 # Main_TryToRun_CmdQueue()
389 # Decide if we can run a new command from the @CmdQueue.
390 # We only run one of these at a time. The @CmdQueue is
391 # used to run BackupPC_link (for the corresponding host),
392 # BackupPC_trashClean, and BackupPC_nightly using a fake
393 # host name of $bpc->adminJob.
394 ############################################################################
395 sub Main_TryToRun_CmdQueue
398 if ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1 ) {
400 $req = pop(@CmdQueue);
402 $host = $req->{host};
403 if ( defined($Jobs{$host}) ) {
404 print(LOG $bpc->timeStamp,
405 "Botch on admin job for $host: already in use!!\n");
407 # This could happen during normal opertion: a user could
408 # request a backup while a BackupPC_link is queued from
409 # a previous backup. But it is unlikely. Just put this
410 # request back on the end of the queue.
412 unshift(@CmdQueue, $req);
415 $CmdQueueOn{$host} = 0;
416 my $cmd = $req->{cmd};
417 my $pid = open(FH, "-|");
418 if ( !defined($pid) ) {
419 print(LOG $bpc->timeStamp,
420 "can't fork for $host, request by $req->{user}\n");
427 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
430 $Jobs{$host}{pid} = $pid;
431 $Jobs{$host}{fh} = *FH;
432 $Jobs{$host}{fn} = fileno(FH);
433 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
434 $Jobs{$host}{startTime} = time;
435 $Jobs{$host}{reqTime} = $req->{reqTime};
436 $cmd = join(" ", @$cmd);
437 $Jobs{$host}{cmd} = $cmd;
438 $Jobs{$host}{type} = $Status{$host}{type};
439 $Status{$host}{state} = "Status_link_running";
440 $Status{$host}{activeJob} = 1;
441 $Status{$host}{endTime} = time;
442 $CmdJob = $host if ( $host ne $bpc->trashJob );
443 $cmd =~ s/$BinDir\///g;
444 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
448 ############################################################################
449 # Main_TryToRun_Bg_or_User_Queue()
451 # Decide if we can run any new backup requests from @BgQueue
452 # or @UserQueue. Several of these can be run at the same time
453 # based on %Conf settings. Jobs from @UserQueue take priority,
454 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
455 # simultaneous jobs can run from @UserQueue. After @UserQueue
456 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
458 ############################################################################
459 sub Main_TryToRun_Bg_or_User_Queue
462 while ( $RunNightlyWhenIdle == 0 ) {
464 my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
465 my $nJobs = keys(%Jobs);
467 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
469 $nJobs-- if ( $CmdJob ne "" );
470 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
471 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
472 && @UserQueue > 0 ) {
473 $req = pop(@UserQueue);
474 if ( defined($Jobs{$req->{host}}) ) {
475 push(@deferUserQueue, $req);
478 push(@args, $req->{doFull} ? "-f" : "-i")
479 if ( !$req->{restore} );
480 $UserQueueOn{$req->{host}} = 0;
481 } elsif ( $nJobs < $Conf{MaxBackups}
482 && (@CmdQueue + $nJobs)
483 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
486 if ( time - $Info{DUlastValueTime} >= 60 ) {
488 # Update our notion of disk usage no more than
491 $du = $bpc->CheckFileSystemUsage($TopDir);
492 $Info{DUlastValue} = $du;
493 $Info{DUlastValueTime} = time;
496 # if we recently checked it then just use the old value
498 $du = $Info{DUlastValue};
500 if ( $Info{DUDailyMaxReset} ) {
501 $Info{DUDailyMaxStartTime} = time;
502 $Info{DUDailyMaxReset} = 0;
503 $Info{DUDailyMax} = 0;
505 if ( $du > $Info{DUDailyMax} ) {
506 $Info{DUDailyMax} = $du;
507 $Info{DUDailyMaxTime} = time;
509 if ( $du > $Conf{DfMaxUsagePct} ) {
510 my $nSkip = @BgQueue + @deferBgQueue;
511 print(LOG $bpc->timeStamp,
512 "Disk too full ($du%%); skipping $nSkip hosts\n");
513 $Info{DUDailySkipHostCnt} += $nSkip;
519 $req = pop(@BgQueue);
520 if ( defined($Jobs{$req->{host}}) ) {
521 push(@deferBgQueue, $req);
524 $BgQueueOn{$req->{host}} = 0;
526 while ( @deferBgQueue ) {
527 push(@BgQueue, pop(@deferBgQueue));
529 while ( @deferUserQueue ) {
530 push(@UserQueue, pop(@deferUserQueue));
534 $host = $req->{host};
535 my $user = $req->{user};
536 if ( $req->{restore} ) {
537 $progName = "BackupPC_restore";
539 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
541 $progName = "BackupPC_dump";
543 push(@args, "-d") if ( $req->{dhcp} );
544 push(@args, "-e") if ( $req->{dumpExpire} );
547 my $pid = open(FH, "-|");
548 if ( !defined($pid) ) {
549 print(LOG $bpc->timeStamp,
550 "can't fork to run $progName for $host, request by $user\n");
556 exec("$BinDir/$progName", @args);
557 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
560 $Jobs{$host}{pid} = $pid;
561 $Jobs{$host}{fh} = *FH;
562 $Jobs{$host}{fn} = fileno(FH);
563 $Jobs{$host}{dhcp} = $req->{dhcp};
564 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
565 $Jobs{$host}{startTime} = time;
566 $Jobs{$host}{reqTime} = $req->{reqTime};
567 $Jobs{$host}{userReq} = $req->{userReq};
568 $Jobs{$host}{cmd} = join(" ", $progName, @args);
569 $Jobs{$host}{user} = $user;
570 $Jobs{$host}{type} = $type;
571 $Status{$host}{userReq} = $req->{userReq}
572 if ( defined($Hosts->{$host}) );
573 if ( !$req->{dhcp} ) {
574 $Status{$host}{state} = "Status_".$type."_starting";
575 $Status{$host}{activeJob} = 1;
576 $Status{$host}{startTime} = time;
577 $Status{$host}{endTime} = "";
582 ############################################################################
585 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
586 # and then do a select() to wait for the next thing to happen
587 # (timeout, signal, someone sends a message, child dies etc).
588 ############################################################################
591 if ( $NextWakeup <= 0 ) {
593 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
595 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
597 my($currHours) = $hour + $min / 60 + $sec / 3600;
598 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
599 my($mesg) = $bpc->ConfigRead()
600 || "Re-read config file because mtime changed";
601 print(LOG $bpc->timeStamp, "$mesg\n");
602 %Conf = $bpc->Conf();
603 $Info{ConfigModTime} = $bpc->ConfigMTime();
604 umask($Conf{UmaskMode});
608 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
609 next if ( $t < 0 || $t > 24 );
610 my $tomorrow = $t + 24;
612 || ($tomorrow - $currHours > 0
613 && $delta > $tomorrow - $currHours) ) {
614 $delta = $tomorrow - $currHours;
615 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
618 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
619 $delta = $t - $currHours;
620 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
623 $NextWakeup = time + $delta * 3600;
624 $Info{nextWakeup} = $NextWakeup;
625 print(LOG $bpc->timeStamp, "Next wakeup is ",
626 $bpc->timeStamp($NextWakeup, 1), "\n");
629 # Call select(), waiting until either a signal, a timeout,
630 # any output from our jobs, or any messages from clients
632 # select() is where we (hopefully) spend most of our time blocked...
634 my $timeout = $NextWakeup - time;
635 $timeout = 1 if ( $timeout <= 0 );
637 select(my $rout = $FDread, undef, $ein, $timeout);
642 ############################################################################
643 # Main_Process_Signal()
646 ############################################################################
647 sub Main_Process_Signal
652 if ( $SigName eq "HUP" ) {
653 my($mesg) = $bpc->ConfigRead()
654 || "Re-read config file because of a SIG_HUP";
655 print(LOG $bpc->timeStamp, "$mesg\n");
656 $Info{ConfigModTime} = $bpc->ConfigMTime();
657 %Conf = $bpc->Conf();
658 umask($Conf{UmaskMode});
662 } elsif ( $SigName ) {
663 print(LOG $bpc->timeStamp, "Got signal $SigName... cleaning up\n");
664 foreach my $host ( keys(%Jobs) ) {
665 kill(2, $Jobs{$host}{pid});
668 unlink("$TopDir/log/BackupPC.pid");
674 ############################################################################
675 # Main_Check_Timeout()
677 # Check if a timeout has occured, and if so, queue all the PCs for backups.
678 # Also does log file aging on the first timeout after midnight.
679 ############################################################################
680 sub Main_Check_Timeout
685 return if ( time < $NextWakeup || $NextWakeup <= 0 );
687 if ( $FirstWakeup ) {
689 # This is the first wakeup after midnight. Do log file aging
690 # and various house keeping.
693 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
694 . " %d skipped hosts\n",
695 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
696 $Info{DUDailySkipHostCnt});
697 $Info{DUDailyMaxReset} = 1;
698 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
699 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
700 $Info{DUDailySkipHostCnt} = 0;
701 my $lastLog = $Conf{MaxOldLogFiles} - 1;
702 if ( -f "$TopDir/log/LOG.$lastLog" ) {
703 print(LOG $bpc->timeStamp,
704 "Removing $TopDir/log/LOG.$lastLog\n");
705 unlink("$TopDir/log/LOG.$lastLog");
707 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
708 print(LOG $bpc->timeStamp,
709 "Removing $TopDir/log/LOG.$lastLog.z\n");
710 unlink("$TopDir/log/LOG.$lastLog.z");
712 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
713 . "LOG.1 -> ... -> LOG.$lastLog\n");
715 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
717 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
718 if ( -f "$TopDir/log/LOG.$i" );
719 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
720 if ( -f "$TopDir/log/LOG.$i.z" );
723 # Compress the log file LOG -> LOG.0.z (if enabled).
724 # Otherwise, just rename LOG -> LOG.0.
726 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
727 "$TopDir/log/LOG.0.z",
729 $Conf{CompressLevel}, 1);
732 # Remember to run nightly script after current jobs are done
734 $RunNightlyWhenIdle = 1;
737 # Write out the current status and then queue all the PCs
741 %BgQueueOn = () if ( @BgQueue == 0 );
742 %UserQueueOn = () if ( @UserQueue == 0 );
743 %CmdQueueOn = () if ( @CmdQueue == 0 );
747 ############################################################################
748 # Main_Check_Job_Messages($fdRead)
750 # Check if select() says we have bytes waiting from any of our jobs.
751 # Handle each of the messages when complete (newline terminated).
752 ############################################################################
753 sub Main_Check_Job_Messages
756 foreach my $host ( keys(%Jobs) ) {
757 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
760 # do a last check to make sure there is something to read so
761 # we are absolutely sure we won't block.
763 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
764 if ( !select($readMask, undef, undef, 0.0) ) {
765 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
766 . " nothing to read from $host. Debug dump:\n");
767 my($dump) = Data::Dumper->new(
768 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
769 [qw(*Clients, *Jobs *FDread, *fdRead)]);
771 print(LOG $dump->Dump);
774 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
775 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
777 # Process any complete lines of output from this jobs.
778 # Any output to STDOUT or STDERR from the children is processed here.
780 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
782 $Jobs{$host}{mesg} = $2;
783 if ( $Jobs{$host}{dhcp} ) {
784 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
785 my $newHost = $bpc->uriUnesc($2);
786 if ( defined($Jobs{$newHost}) ) {
787 print(LOG $bpc->timeStamp,
788 "Backup on $newHost is already running\n");
789 kill(2, $Jobs{$host}{pid});
793 $Jobs{$host}{dhcpHostIP} = $host;
794 $Status{$newHost}{dhcpHostIP} = $host;
795 $Jobs{$newHost} = $Jobs{$host};
796 delete($Jobs{$host});
798 $Status{$host}{state} = "Status_backup_starting";
799 $Status{$host}{activeJob} = 1;
800 $Status{$host}{startTime} = $Jobs{$host}{startTime};
801 $Status{$host}{endTime} = "";
802 $Jobs{$host}{dhcp} = 0;
804 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
806 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
807 $Jobs{$host}{type} = $1;
808 $Jobs{$host}{shareName} = $2;
809 print(LOG $bpc->timeStamp,
810 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
811 $Jobs{$host}{dhcpHostIP}
812 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
813 ", share=$Jobs{$host}{shareName})\n");
814 $Status{$host}{state} = "Status_backup_in_progress";
815 $Status{$host}{reason} = "";
816 $Status{$host}{type} = $1;
817 $Status{$host}{startTime} = time;
818 $Status{$host}{deadCnt} = 0;
819 $Status{$host}{aliveCnt}++;
820 $Status{$host}{dhcpCheckCnt}--
821 if ( $Status{$host}{dhcpCheckCnt} > 0 );
822 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
823 $Jobs{$host}{xferPid} = $1;
824 } elsif ( $mesg =~ /^started_restore/ ) {
825 $Jobs{$host}{type} = "restore";
826 print(LOG $bpc->timeStamp,
827 "Started restore on $host"
828 . " (pid=$Jobs{$host}{pid})\n");
829 $Status{$host}{state} = "Status_restore_in_progress";
830 $Status{$host}{reason} = "";
831 $Status{$host}{type} = "restore";
832 $Status{$host}{startTime} = time;
833 $Status{$host}{deadCnt} = 0;
834 $Status{$host}{aliveCnt}++;
835 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
836 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
837 $Status{$host}{reason} = "Reason_backup_done";
838 delete($Status{$host}{error});
839 delete($Status{$host}{errorTime});
840 $Status{$host}{endTime} = time;
841 } elsif ( $mesg =~ /^restore complete/ ) {
842 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
843 $Status{$host}{reason} = "Reason_restore_done";
844 delete($Status{$host}{error});
845 delete($Status{$host}{errorTime});
846 $Status{$host}{endTime} = time;
847 } elsif ( $mesg =~ /^nothing to do/ ) {
848 $Status{$host}{state} = "Status_idle";
849 $Status{$host}{reason} = "Reason_nothing_to_do";
850 $Status{$host}{startTime} = time;
851 $Status{$host}{dhcpCheckCnt}--
852 if ( $Status{$host}{dhcpCheckCnt} > 0 );
853 } elsif ( $mesg =~ /^no ping response/
854 || $mesg =~ /^ping too slow/
855 || $mesg =~ /^host not found/ ) {
856 $Status{$host}{state} = "Status_idle";
857 if ( $Status{$host}{userReq}
858 || $Status{$host}{reason} ne "Reason_backup_failed"
859 || $Status{$host}{error} =~ /^aborted by user/ ) {
860 $Status{$host}{reason} = "Reason_no_ping";
861 $Status{$host}{error} = $mesg;
862 $Status{$host}{startTime} = time;
864 $Status{$host}{deadCnt}++;
865 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
866 $Status{$host}{aliveCnt} = 0;
868 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
869 $Status{$host}{state} = "Status_idle";
870 $Status{$host}{reason} = "Reason_backup_failed";
871 $Status{$host}{error} = $1;
872 $Status{$host}{errorTime} = time;
873 $Status{$host}{endTime} = time;
874 print(LOG $bpc->timeStamp, "backup failed on $host ($1)\n");
875 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
876 print(LOG $bpc->timeStamp, "$1\n");
877 } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
878 my @f = split(/,/, $1);
879 $Info{"$f[0]FileCnt"} = $f[1];
880 $Info{"$f[0]DirCnt"} = $f[2];
881 $Info{"$f[0]Kb"} = $f[3];
882 $Info{"$f[0]Kb2"} = $f[4];
883 $Info{"$f[0]KbRm"} = $f[5];
884 $Info{"$f[0]FileCntRm"} = $f[6];
885 $Info{"$f[0]FileCntRep"} = $f[7];
886 $Info{"$f[0]FileRepMax"} = $f[8];
887 $Info{"$f[0]FileCntRename"} = $f[9];
888 $Info{"$f[0]FileLinkMax"} = $f[10];
889 $Info{"$f[0]Time"} = time;
890 printf(LOG "%s%s nightly clean removed %d files of"
892 $bpc->timeStamp, ucfirst($f[0]),
893 $Info{"$f[0]FileCntRm"},
894 $Info{"$f[0]KbRm"} / (1000 * 1024));
895 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
896 . "%d max chain, %d max links), %d directories\n",
897 $bpc->timeStamp, ucfirst($f[0]),
898 $Info{"$f[0]Kb"} / (1000 * 1024),
899 $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
900 $Info{"$f[0]FileRepMax"},
901 $Info{"$f[0]FileLinkMax"}, $Info{"$f[0]DirCnt"});
902 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
903 $RunNightlyWhenIdle = 0;
904 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
905 $Jobs{$host}{processState} = $1;
906 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
908 $Status{$h}{needLink} = 1;
910 print(LOG $bpc->timeStamp, "$host: $mesg\n");
914 # shut down the client connection if we read EOF
916 if ( $nbytes <= 0 ) {
917 close($Jobs{$host}{fh});
918 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
919 if ( $CmdJob eq $host ) {
920 my $cmd = $Jobs{$host}{cmd};
921 $cmd =~ s/$BinDir\///g;
922 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
923 $Status{$host}{state} = "Status_idle";
924 $Status{$host}{endTime} = time;
926 $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
927 && $RunNightlyWhenIdle );
930 # Queue BackupPC_link to complete the backup
931 # processing for this host.
933 if ( defined($Status{$host})
934 && ($Status{$host}{reason} eq "Reason_backup_done"
935 || $Status{$host}{needLink}) ) {
937 } elsif ( defined($Status{$host}) ) {
938 $Status{$host}{state} = "Status_idle";
941 delete($Jobs{$host});
942 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
946 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
947 # do a pass over %Status updating the deadCnt and aliveCnt for
948 # DHCP hosts. The reason we need to do this later is we can't
949 # be sure whether a DHCP host is alive or dead until we have passed
950 # over all the DHCP pool.
952 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
953 foreach my $host ( keys(%Status) ) {
954 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
955 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
956 $Status{$host}{dhcpCheckCnt} = 0;
957 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
958 $Status{$host}{aliveCnt} = 0;
963 ############################################################################
964 # Main_Check_Client_Messages($fdRead)
966 # Check for, and process, any output from our clients. Also checks
967 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
968 ############################################################################
969 sub Main_Check_Client_Messages
972 foreach my $client ( keys(%Clients) ) {
973 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
976 # do a last check to make sure there is something to read so
977 # we are absolutely sure we won't block.
979 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
980 if ( !select($readMask, undef, undef, 0.0) ) {
981 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
982 . " nothing to read from $client. Debug dump:\n");
983 my($dump) = Data::Dumper->new(
984 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
985 [qw(*Clients, *Jobs *FDread, *fdRead)]);
987 print(LOG $dump->Dump);
990 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
991 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
993 # Process any complete lines received from this client.
995 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
998 $Clients{$client}{mesg} = $2;
1000 # Authenticate the message by checking the MD5 digest
1002 my $md5 = Digest::MD5->new;
1003 if ( $cmd !~ /^(.{22}) (.*)/
1004 || ($md5->add($Clients{$client}{seed}
1005 . $Clients{$client}{mesgCnt}
1006 . $Conf{ServerMesgSecret} . $2),
1007 $md5->b64digest ne $1) ) {
1008 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1009 . " client '$Clients{$client}{clientName}':"
1010 . " shutting down client connection\n");
1014 $Clients{$client}{mesgCnt}++;
1016 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1020 $host = $bpc->uriUnesc($host);
1021 if ( $CmdJob ne $host && defined($Status{$host})
1022 && defined($Jobs{$host}) ) {
1023 print(LOG $bpc->timeStamp,
1024 "Stopping current backup of $host,"
1025 . " request by $user (backoff=$backoff)\n");
1026 kill(2, $Jobs{$host}{pid});
1028 # Don't close the pipe now; wait until the child
1029 # really exits later. Otherwise close() will
1030 # block until the child has exited.
1032 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1033 ##close($Jobs{$host}{fh});
1034 ##delete($Jobs{$host});
1036 $Status{$host}{state} = "Status_idle";
1037 $Status{$host}{reason} = "Reason_backup_canceled_by_user";
1038 $Status{$host}{activeJob} = 0;
1039 $Status{$host}{startTime} = time;
1040 $reply = "ok: backup of $host cancelled";
1041 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1042 print(LOG $bpc->timeStamp,
1043 "Stopping pending backup of $host,"
1044 . " request by $user (backoff=$backoff)\n");
1045 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1046 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1047 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1048 $reply = "ok: pending backup of $host cancelled";
1050 print(LOG $bpc->timeStamp,
1051 "Nothing to do for stop backup of $host,"
1052 . " request by $user (backoff=$backoff)\n");
1053 $reply = "ok: no backup was pending or running";
1055 if ( defined($Status{$host}) && $backoff ne "" ) {
1056 if ( $backoff > 0 ) {
1057 $Status{$host}{backoffTime} = time + $backoff * 3600;
1059 delete($Status{$host}{backoffTime});
1062 } elsif ( $cmd =~ /^backup all$/ ) {
1064 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1069 $host = $bpc->uriUnesc($host);
1070 $hostIP = $bpc->uriUnesc($hostIP);
1071 if ( !defined($Status{$host}) ) {
1072 print(LOG $bpc->timeStamp,
1073 "User $user requested backup of unknown host"
1075 $reply = "error: unknown host $host";
1076 } elsif ( defined($Jobs{$host})
1077 && $Jobs{$host}{type} ne "restore" ) {
1078 print(LOG $bpc->timeStamp,
1079 "User $user requested backup of $host,"
1080 . " but one is currently running\n");
1081 $reply = "error: backup of $host is already running";
1083 print(LOG $bpc->timeStamp,
1084 "User $user requested backup of $host"
1086 if ( $BgQueueOn{$hostIP} ) {
1087 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1088 $BgQueueOn{$hostIP} = 0;
1090 if ( $UserQueueOn{$hostIP} ) {
1091 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1092 $UserQueueOn{$hostIP} = 0;
1094 unshift(@UserQueue, {
1100 dhcp => $hostIP eq $host ? 0 : 1,
1102 $UserQueueOn{$hostIP} = 1;
1103 $reply = "ok: requested backup of $host";
1105 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1109 my $reqFileName = $4;
1110 $host = $bpc->uriUnesc($host);
1111 $hostIP = $bpc->uriUnesc($hostIP);
1112 if ( !defined($Status{$host}) ) {
1113 print(LOG $bpc->timeStamp,
1114 "User $user requested restore to unknown host"
1116 $reply = "restore error: unknown host $host";
1118 print(LOG $bpc->timeStamp,
1119 "User $user requested restore to $host"
1121 unshift(@UserQueue, {
1124 reqFileName => $reqFileName,
1130 $UserQueueOn{$host} = 1;
1131 if ( defined($Jobs{$host}) ) {
1132 $reply = "ok: requested restore of $host, but a"
1133 . " job is currently running,"
1134 . " so this request will start later";
1136 $reply = "ok: requested restore of $host";
1139 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1141 my($dump, @values, @names);
1142 foreach my $type ( split(/\s+/, $args) ) {
1143 if ( $type =~ /^queues/ ) {
1144 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1145 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1146 } elsif ( $type =~ /^jobs/ ) {
1147 push(@values, \%Jobs);
1148 push(@names, qw(*Jobs));
1149 } elsif ( $type =~ /^queueLen/ ) {
1151 BgQueue => scalar(@BgQueue),
1152 UserQueue => scalar(@UserQueue),
1153 CmdQueue => scalar(@CmdQueue),
1155 push(@names, qw(*QueueLen));
1156 } elsif ( $type =~ /^info/ ) {
1157 push(@values, \%Info);
1158 push(@names, qw(*Info));
1159 } elsif ( $type =~ /^hosts/ ) {
1160 push(@values, \%Status);
1161 push(@names, qw(*Status));
1162 } elsif ( $type =~ /^host\((.*)\)/ ) {
1163 my $h = $bpc->uriUnesc($1);
1164 if ( defined($Status{$h}) ) {
1167 BgQueueOn => $BgQueueOn{$h},
1168 UserQueueOn => $UserQueueOn{$h},
1169 CmdQueueOn => $CmdQueueOn{$h},
1171 push(@names, qw(*StatusHost));
1173 print(LOG $bpc->timeStamp,
1174 "Unknown host $h for status request\n");
1177 print(LOG $bpc->timeStamp,
1178 "Unknown status request $type\n");
1181 $dump = Data::Dumper->new(\@values, \@names);
1183 $reply = $dump->Dump;
1184 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1186 $host = $bpc->uriUnesc($host);
1188 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1189 print(LOG $bpc->timeStamp, "$1\n");
1190 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1194 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1195 $reply = "error: bad command $cmd";
1198 # send a reply to the client, at a minimum "ok\n".
1200 $reply = "ok" if ( $reply eq "" );
1202 syswrite($Clients{$client}{fh}, $reply, length($reply));
1205 # Detect possible denial-of-service attack from sending a huge line
1206 # (ie: never terminated). 32K seems to be plenty big enough as
1209 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1210 print(LOG $bpc->timeStamp, "Line too long from client"
1211 . " '$Clients{$client}{clientName}':"
1212 . " shutting down client connection\n");
1216 # Shut down the client connection if we read EOF
1218 if ( $nbytes <= 0 ) {
1219 close($Clients{$client}{fh});
1220 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1221 delete($Clients{$client});
1225 # Accept any new connections on each of our listen sockets
1227 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1229 my $paddr = accept(CLIENT, SERVER_UNIX);
1231 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1232 $Clients{$ClientConnCnt}{mesg} = "";
1233 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1234 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1235 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1237 # Generate and send unique seed for MD5 digests to avoid
1238 # replay attacks. See BackupPC::Lib::ServerMesg().
1240 my $seed = time . ",$ClientConnCnt,$$,0\n";
1241 $Clients{$ClientConnCnt}{seed} = $seed;
1242 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1243 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1245 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1247 my $paddr = accept(CLIENT, SERVER_INET);
1248 my($port,$iaddr) = sockaddr_in($paddr);
1249 my $name = gethostbyaddr($iaddr, AF_INET);
1251 $Clients{$ClientConnCnt}{mesg} = "";
1252 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1253 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1254 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1255 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1257 # Generate and send unique seed for MD5 digests to avoid
1258 # replay attacks. See BackupPC::Lib::ServerMesg().
1260 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1261 $Clients{$ClientConnCnt}{seed} = $seed;
1262 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1263 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1267 ###########################################################################
1268 # Miscellaneous subroutines
1269 ###########################################################################
1272 # Write the current status to $TopDir/log/status.pl
1276 my($dump) = Data::Dumper->new(
1277 [ \%Info, \%Status],
1278 [qw(*Info *Status)]);
1280 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1281 print(STATUS $dump->Dump);
1287 # Queue all the hosts for backup. This means queuing all the fixed
1288 # ip hosts and all the dhcp address ranges. We also additionally
1289 # queue the dhcp hosts with a -e flag to check for expired dumps.
1293 foreach my $host ( sort(keys(%$Hosts)) ) {
1294 delete($Status{$host}{backoffTime})
1295 if ( defined($Status{$host}{backoffTime})
1296 && $Status{$host}{backoffTime} < time );
1297 next if ( defined($Jobs{$host})
1298 || $BgQueueOn{$host}
1299 || $UserQueueOn{$host}
1300 || $CmdQueueOn{$host} );
1301 if ( $Hosts->{$host}{dhcp} ) {
1302 $Status{$host}{dhcpCheckCnt}++;
1303 if ( $RunNightlyWhenIdle ) {
1305 # Once per night queue a check for DHCP hosts that just
1306 # checks for expired dumps. We need to do this to handle
1307 # the case when a DHCP host has not been on the network for
1308 # a long time, and some of the old dumps need to be expired.
1309 # Normally expiry checks are done by BackupPC_dump only
1310 # after the DHCP hosts has been detected on the network.
1313 {host => $host, user => "BackupPC", reqTime => time,
1314 dhcp => 0, dumpExpire => 1});
1315 $BgQueueOn{$host} = 1;
1319 # this is a fixed ip host: queue it
1322 {host => $host, user => "BackupPC", reqTime => time,
1323 dhcp => $Hosts->{$host}{dhcp}});
1324 $BgQueueOn{$host} = 1;
1327 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1328 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1329 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1330 next if ( defined($Jobs{$ipAddr})
1331 || $BgQueueOn{$ipAddr}
1332 || $UserQueueOn{$ipAddr}
1333 || $CmdQueueOn{$ipAddr} );
1335 # this is a potential dhcp ip address (we don't know the
1336 # host name yet): queue it
1339 {host => $ipAddr, user => "BackupPC", reqTime => time,
1341 $BgQueueOn{$ipAddr} = 1;
1347 # Queue a BackupPC_link for the given host
1353 return if ( $CmdQueueOn{$host} );
1354 $Status{$host}{state} = "Status_link_pending";
1355 $Status{$host}{needLink} = 0;
1356 unshift(@CmdQueue, {
1360 cmd => ["$BinDir/BackupPC_link", $host],
1362 $CmdQueueOn{$host} = 1;
1366 # Read the hosts file, and update Status if any hosts have been
1367 # added or deleted. We also track the mtime so the only need to
1368 # update the hosts file on changes.
1370 # This function is called at startup, SIGHUP, and on each wakeup.
1371 # It returns 1 on success and undef on failure.
1378 # Nothing to do if we already have the current hosts file
1380 return 1 if ( !$force && defined($Hosts)
1381 && $Info{HostsModTime} == $bpc->HostsMTime() );
1382 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1383 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1386 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1388 $Info{HostsModTime} = $bpc->HostsMTime();
1390 # Now update %Status in case any hosts have been added or deleted
1392 foreach my $host ( sort(keys(%$Hosts)) ) {
1393 next if ( defined($Status{$host}) );
1394 $Status{$host}{state} = "Status_idle";
1395 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1397 foreach my $host ( sort(keys(%Status)) ) {
1398 next if ( $host eq $bpc->trashJob
1399 || $host eq $bpc->adminJob
1400 || defined($Hosts->{$host})
1401 || defined($Jobs{$host})
1402 || $BgQueueOn{$host}
1403 || $UserQueueOn{$host}
1404 || $CmdQueueOn{$host} );
1405 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1406 delete($Status{$host});
1412 # Remember the signal name for later processing
1418 foreach my $host ( keys(%Jobs) ) {
1419 kill(2, $Jobs{$host}{pid});
1422 # In case we are inside the exit handler, reopen the log file
1426 print(LOG "Fatal error: unhandled signal $SigName\n");
1427 unlink("$TopDir/log/BackupPC.pid");
1428 confess("Got new signal $SigName... quitting\n");
1434 # Open the log file and point STDOUT and STDERR there too
1438 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1439 open(LOG, ">>$TopDir/log/LOG")
1440 || die("Can't create LOG file $TopDir/log/LOG");
1443 open(STDOUT, ">&LOG");
1444 open(STDERR, ">&LOG");
1445 select(LOG); $| = 1;
1446 select(STDERR); $| = 1;
1447 select(STDOUT); $| = 1;
1451 # Initialize the unix-domain and internet-domain sockets that
1452 # we listen to for client connections (from the CGI script and
1453 # some of the BackupPC sub-programs).
1455 sub ServerSocketInit
1457 if ( !defined(fileno(SERVER_UNIX)) ) {
1459 # one-time only: initialize unix-domain socket
1461 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1462 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1465 my $sockFile = "$TopDir/log/BackupPC.sock";
1467 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1468 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1471 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1472 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1475 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1477 return if ( $ServerInetPort == $Conf{ServerPort} );
1478 if ( $ServerInetPort > 0 ) {
1479 vec($FDread, fileno(SERVER_INET), 1) = 0;
1481 $ServerInetPort = -1;
1483 if ( $Conf{ServerPort} > 0 ) {
1485 # Setup a socket to listen on $Conf{ServerPort}
1487 my $proto = getprotobyname('tcp');
1488 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1489 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1492 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1493 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1496 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1497 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1500 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1501 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1504 vec($FDread, fileno(SERVER_INET), 1) = 1;
1505 $ServerInetPort = $Conf{ServerPort};