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 1.6.0_CVS, released 10 Dec 2002.
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 ###########################################################################
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
253 next if ( !defined($Conf{$progName}) || -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;
325 # Write out our initial status and save our PID
328 if ( open(PID, ">$TopDir/log/BackupPC.pid") ) {
334 # For unknown reasons there is a very infrequent error about not
335 # being able to coerce GLOBs inside the XS Data::Dumper. I've
336 # only seen this on a particular platform and perl version.
337 # For now the workaround appears to be use the perl version of
340 $Data::Dumper::Useqq = 1;
343 ############################################################################
344 # Main_TryToRun_nightly()
346 # Checks to see if we can/should run BackupPC_nightly or
347 # BackupPC_trashClean. If so we push the appropriate command onto
349 ############################################################################
350 sub Main_TryToRun_nightly
353 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
354 # BackupPC_nightly is run when the current job queue is empty.
355 # BackupPC_trashClean is run in the background always.
357 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
358 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
360 # This should only happen once at startup, but just in case this
361 # code will re-start BackupPC_trashClean if it quits
364 host => $bpc->trashJob,
367 cmd => "$BinDir/BackupPC_trashClean"
369 $CmdQueueOn{$bpc->trashJob} = 1;
371 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
373 host => $bpc->adminJob,
376 cmd => "$BinDir/BackupPC_nightly"
378 $CmdQueueOn{$bpc->adminJob} = 1;
379 $RunNightlyWhenIdle = 2;
383 ############################################################################
384 # Main_TryToRun_CmdQueue()
386 # Decide if we can run a new command from the @CmdQueue.
387 # We only run one of these at a time. The @CmdQueue is
388 # used to run BackupPC_link (for the corresponding host),
389 # BackupPC_trashClean, and BackupPC_nightly using a fake
390 # host name of $bpc->adminJob.
391 ############################################################################
392 sub Main_TryToRun_CmdQueue
395 if ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1 ) {
397 $req = pop(@CmdQueue);
399 $host = $req->{host};
400 if ( defined($Jobs{$host}) ) {
401 print(LOG $bpc->timeStamp,
402 "Botch on admin job for $host: already in use!!\n");
404 # This could happen during normal opertion: a user could
405 # request a backup while a BackupPC_link is queued from
406 # a previous backup. But it is unlikely. Just put this
407 # request back on the end of the queue.
409 unshift(@CmdQueue, $req);
412 $CmdQueueOn{$host} = 0;
413 my $cmd = $req->{cmd};
414 my $pid = open(FH, "-|");
415 if ( !defined($pid) ) {
416 print(LOG $bpc->timeStamp,
417 "can't fork for $host, request by $req->{user}\n");
424 print(LOG $bpc->timeStamp, "can't exec $cmd for $host\n");
427 $Jobs{$host}{pid} = $pid;
428 $Jobs{$host}{fh} = *FH;
429 $Jobs{$host}{fn} = fileno(FH);
430 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
431 $Jobs{$host}{startTime} = time;
432 $Jobs{$host}{reqTime} = $req->{reqTime};
433 $Jobs{$host}{cmd} = $cmd;
434 $Jobs{$host}{type} = $Status{$host}{type};
435 $Status{$host}{state} = "Status_link_running";
436 $Status{$host}{activeJob} = 1;
437 $Status{$host}{endTime} = time;
438 $CmdJob = $host if ( $host ne $bpc->trashJob );
439 $cmd =~ s/$BinDir\///g;
440 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
444 ############################################################################
445 # Main_TryToRun_Bg_or_User_Queue()
447 # Decide if we can run any new backup requests from @BgQueue
448 # or @UserQueue. Several of these can be run at the same time
449 # based on %Conf settings. Jobs from @UserQueue take priority,
450 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
451 # simultaneous jobs can run from @UserQueue. After @UserQueue
452 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
454 ############################################################################
455 sub Main_TryToRun_Bg_or_User_Queue
458 while ( $RunNightlyWhenIdle == 0 ) {
460 my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
461 my $nJobs = keys(%Jobs);
463 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
465 $nJobs-- if ( $CmdJob ne "" );
466 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
467 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
468 && @UserQueue > 0 ) {
469 $req = pop(@UserQueue);
470 if ( defined($Jobs{$req->{host}}) ) {
471 push(@deferUserQueue, $req);
474 push(@args, $req->{doFull} ? "-f" : "-i")
475 if ( !$req->{restore} );
476 $UserQueueOn{$req->{host}} = 0;
477 } elsif ( $nJobs < $Conf{MaxBackups}
478 && (@CmdQueue + $nJobs)
479 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
482 if ( time - $Info{DUlastValueTime} >= 60 ) {
484 # Update our notion of disk usage no more than
487 $du = $bpc->CheckFileSystemUsage($TopDir);
488 $Info{DUlastValue} = $du;
489 $Info{DUlastValueTime} = time;
492 # if we recently checked it then just use the old value
494 $du = $Info{DUlastValue};
496 if ( $Info{DUDailyMaxReset} ) {
497 $Info{DUDailyMaxStartTime} = time;
498 $Info{DUDailyMaxReset} = 0;
499 $Info{DUDailyMax} = 0;
501 if ( $du > $Info{DUDailyMax} ) {
502 $Info{DUDailyMax} = $du;
503 $Info{DUDailyMaxTime} = time;
505 if ( $du > $Conf{DfMaxUsagePct} ) {
506 my $nSkip = @BgQueue + @deferBgQueue;
507 print(LOG $bpc->timeStamp,
508 "Disk too full ($du%%); skipping $nSkip hosts\n");
509 $Info{DUDailySkipHostCnt} += $nSkip;
515 $req = pop(@BgQueue);
516 if ( defined($Jobs{$req->{host}}) ) {
517 push(@deferBgQueue, $req);
520 $BgQueueOn{$req->{host}} = 0;
522 while ( @deferBgQueue ) {
523 push(@BgQueue, pop(@deferBgQueue));
525 while ( @deferUserQueue ) {
526 push(@UserQueue, pop(@deferUserQueue));
530 $host = $req->{host};
531 my $user = $req->{user};
532 if ( $req->{restore} ) {
533 $progName = "BackupPC_restore";
535 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
537 $progName = "BackupPC_dump";
539 push(@args, "-d") if ( $req->{dhcp} );
540 push(@args, "-e") if ( $req->{dumpExpire} );
543 my $pid = open(FH, "-|");
544 if ( !defined($pid) ) {
545 print(LOG $bpc->timeStamp,
546 "can't fork to run $progName for $host, request by $user\n");
552 exec("$BinDir/$progName", @args);
553 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
556 $Jobs{$host}{pid} = $pid;
557 $Jobs{$host}{fh} = *FH;
558 $Jobs{$host}{fn} = fileno(FH);
559 $Jobs{$host}{dhcp} = $req->{dhcp};
560 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
561 $Jobs{$host}{startTime} = time;
562 $Jobs{$host}{reqTime} = $req->{reqTime};
563 $Jobs{$host}{cmd} = "$progName " . join(" ", @args);
564 $Jobs{$host}{user} = $user;
565 $Jobs{$host}{type} = $type;
566 if ( !$req->{dhcp} ) {
567 $Status{$host}{state} = "Status_".$type."_starting";
568 $Status{$host}{activeJob} = 1;
569 $Status{$host}{startTime} = time;
570 $Status{$host}{endTime} = "";
575 ############################################################################
578 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
579 # and then do a select() to wait for the next thing to happen
580 # (timeout, signal, someone sends a message, child dies etc).
581 ############################################################################
584 if ( $NextWakeup <= 0 ) {
586 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
588 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
590 my($currHours) = $hour + $min / 60 + $sec / 3600;
591 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
592 my($mesg) = $bpc->ConfigRead()
593 || "Re-read config file because mtime changed";
594 print(LOG $bpc->timeStamp, "$mesg\n");
595 %Conf = $bpc->Conf();
596 $Info{ConfigModTime} = $bpc->ConfigMTime();
597 umask($Conf{UmaskMode});
601 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
602 next if ( $t < 0 || $t > 24 );
603 my $tomorrow = $t + 24;
605 || ($tomorrow - $currHours > 0
606 && $delta > $tomorrow - $currHours) ) {
607 $delta = $tomorrow - $currHours;
608 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
611 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
612 $delta = $t - $currHours;
613 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
616 $NextWakeup = time + $delta * 3600;
617 $Info{nextWakeup} = $NextWakeup;
618 print(LOG $bpc->timeStamp, "Next wakeup is ",
619 $bpc->timeStamp($NextWakeup, 1), "\n");
622 # Call select(), waiting until either a signal, a timeout,
623 # any output from our jobs, or any messages from clients
625 # select() is where we (hopefully) spend most of our time blocked...
627 my $timeout = $NextWakeup - time;
628 $timeout = 1 if ( $timeout <= 0 );
630 select(my $rout = $FDread, undef, $ein, $timeout);
635 ############################################################################
636 # Main_Process_Signal()
639 ############################################################################
640 sub Main_Process_Signal
645 if ( $SigName eq "HUP" ) {
646 my($mesg) = $bpc->ConfigRead()
647 || "Re-read config file because of a SIG_HUP";
648 print(LOG $bpc->timeStamp, "$mesg\n");
649 $Info{ConfigModTime} = $bpc->ConfigMTime();
650 %Conf = $bpc->Conf();
651 umask($Conf{UmaskMode});
655 } elsif ( $SigName ) {
656 print(LOG $bpc->timeStamp, "Got signal $SigName... cleaning up\n");
657 foreach my $host ( keys(%Jobs) ) {
658 kill(2, $Jobs{$host}{pid});
661 unlink("$TopDir/log/BackupPC.pid");
667 ############################################################################
668 # Main_Check_Timeout()
670 # Check if a timeout has occured, and if so, queue all the PCs for backups.
671 # Also does log file aging on the first timeout after midnight.
672 ############################################################################
673 sub Main_Check_Timeout
678 return if ( time < $NextWakeup || $NextWakeup <= 0 );
680 if ( $FirstWakeup ) {
682 # This is the first wakeup after midnight. Do log file aging
683 # and various house keeping.
686 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
687 . " %d skipped hosts\n",
688 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
689 $Info{DUDailySkipHostCnt});
690 $Info{DUDailyMaxReset} = 1;
691 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
692 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
693 $Info{DUDailySkipHostCnt} = 0;
694 my $lastLog = $Conf{MaxOldLogFiles} - 1;
695 if ( -f "$TopDir/log/LOG.$lastLog" ) {
696 print(LOG $bpc->timeStamp,
697 "Removing $TopDir/log/LOG.$lastLog\n");
698 unlink("$TopDir/log/LOG.$lastLog");
700 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
701 print(LOG $bpc->timeStamp,
702 "Removing $TopDir/log/LOG.$lastLog.z\n");
703 unlink("$TopDir/log/LOG.$lastLog.z");
705 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
706 . "LOG.1 -> ... -> LOG.$lastLog\n");
708 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
710 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
711 if ( -f "$TopDir/log/LOG.$i" );
712 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
713 if ( -f "$TopDir/log/LOG.$i.z" );
716 # Compress the log file LOG -> LOG.0.z (if enabled).
717 # Otherwise, just rename LOG -> LOG.0.
719 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
720 "$TopDir/log/LOG.0.z",
722 $Conf{CompressLevel}, 1);
725 # Remember to run nightly script after current jobs are done
727 $RunNightlyWhenIdle = 1;
730 # Write out the current status and then queue all the PCs
734 %BgQueueOn = () if ( @BgQueue == 0 );
735 %UserQueueOn = () if ( @UserQueue == 0 );
736 %CmdQueueOn = () if ( @CmdQueue == 0 );
740 ############################################################################
741 # Main_Check_Job_Messages($fdRead)
743 # Check if select() says we have bytes waiting from any of our jobs.
744 # Handle each of the messages when complete (newline terminated).
745 ############################################################################
746 sub Main_Check_Job_Messages
749 foreach my $host ( keys(%Jobs) ) {
750 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
753 # do a last check to make sure there is something to read so
754 # we are absolutely sure we won't block.
756 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
757 if ( !select($readMask, undef, undef, 0.0) ) {
758 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
759 . " nothing to read from $host. Debug dump:\n");
760 my($dump) = Data::Dumper->new(
761 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
762 [qw(*Clients, *Jobs *FDread, *fdRead)]);
764 print(LOG $dump->Dump);
767 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
768 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
770 # Process any complete lines of output from this jobs.
771 # Any output to STDOUT or STDERR from the children is processed here.
773 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
775 $Jobs{$host}{mesg} = $2;
776 if ( $Jobs{$host}{dhcp} ) {
777 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
779 if ( defined($Jobs{$newHost}) ) {
780 print(LOG $bpc->timeStamp,
781 "Backup on $newHost is already running\n");
782 kill(2, $Jobs{$host}{pid});
786 $Jobs{$host}{dhcpHostIP} = $host;
787 $Status{$newHost}{dhcpHostIP} = $host;
788 $Jobs{$newHost} = $Jobs{$host};
789 delete($Jobs{$host});
791 $Status{$host}{state} = "Status_backup_starting";
792 $Status{$host}{activeJob} = 1;
793 $Status{$host}{startTime} = $Jobs{$host}{startTime};
794 $Status{$host}{endTime} = "";
795 $Jobs{$host}{dhcp} = 0;
797 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
799 } elsif ( $mesg =~ /^started (.*) dump, pid=(-?\d+), tarPid=(-?\d+), share=(.*)/ ) {
800 $Jobs{$host}{type} = $1;
801 $Jobs{$host}{xferPid} = $2;
802 $Jobs{$host}{tarPid} = $3;
803 $Jobs{$host}{shareName} = $4;
804 print(LOG $bpc->timeStamp,
805 "Started $1 backup on $host"
806 . " (pid=$Jobs{$host}{pid}, xferPid=$2",
807 $Jobs{$host}{tarPid} > 0
808 ? ", tarPid=$Jobs{$host}{tarPid}" : "",
809 $Jobs{$host}{dhcpHostIP}
810 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
811 ", share=$Jobs{$host}{shareName})\n");
812 $Status{$host}{state} = "Status_backup_in_progress";
813 $Status{$host}{reason} = "";
814 $Status{$host}{type} = $1;
815 $Status{$host}{startTime} = time;
816 $Status{$host}{deadCnt} = 0;
817 $Status{$host}{aliveCnt}++;
818 $Status{$host}{dhcpCheckCnt}--
819 if ( $Status{$host}{dhcpCheckCnt} > 0 );
820 } elsif ( $mesg =~ /^started_restore (\S+) (\S+)/ ) {
821 $Jobs{$host}{type} = "restore";
822 $Jobs{$host}{xferPid} = $1;
823 $Jobs{$host}{tarPid} = $2;
824 print(LOG $bpc->timeStamp,
825 "Started restore on $host"
826 . " (pid=$Jobs{$host}{pid}, xferPid=$2",
827 $Jobs{$host}{tarPid} > 0
828 ? ", tarPid=$Jobs{$host}{tarPid}" : "",
830 $Status{$host}{state} = "Status_restore_in_progress";
831 $Status{$host}{reason} = "";
832 $Status{$host}{type} = "restore";
833 $Status{$host}{startTime} = time;
834 $Status{$host}{deadCnt} = 0;
835 $Status{$host}{aliveCnt}++;
836 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
837 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
838 $Status{$host}{reason} = "Reason_backup_done";
839 delete($Status{$host}{error});
840 delete($Status{$host}{errorTime});
841 $Status{$host}{endTime} = time;
842 } elsif ( $mesg =~ /^restore complete/ ) {
843 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
844 $Status{$host}{reason} = "Reason_restore_done";
845 delete($Status{$host}{error});
846 delete($Status{$host}{errorTime});
847 $Status{$host}{endTime} = time;
848 } elsif ( $mesg =~ /^nothing to do/ ) {
849 $Status{$host}{state} = "Status_idle";
850 $Status{$host}{reason} = "Reason_nothing_to_do";
851 $Status{$host}{startTime} = time;
852 $Status{$host}{dhcpCheckCnt}--
853 if ( $Status{$host}{dhcpCheckCnt} > 0 );
854 } elsif ( $mesg =~ /^no ping response/
855 || $mesg =~ /^ping too slow/ ) {
856 $Status{$host}{state} = "Status_idle";
857 if ( $Status{$host}{reason} ne "Reason_backup_failed" ) {
858 $Status{$host}{reason} = "Reason_no_ping";
859 $Status{$host}{startTime} = time;
861 $Status{$host}{deadCnt}++;
862 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
863 $Status{$host}{aliveCnt} = 0;
865 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
866 $Status{$host}{state} = "Status_idle";
867 $Status{$host}{reason} = "Reason_backup_failed";
868 $Status{$host}{error} = $1;
869 $Status{$host}{errorTime} = time;
870 $Status{$host}{endTime} = time;
871 print(LOG $bpc->timeStamp, "backup failed on $host ($1)\n");
872 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
873 print(LOG $bpc->timeStamp, "$1\n");
874 } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
875 my @f = split(/,/, $1);
876 $Info{"$f[0]FileCnt"} = $f[1];
877 $Info{"$f[0]DirCnt"} = $f[2];
878 $Info{"$f[0]Kb"} = $f[3];
879 $Info{"$f[0]Kb2"} = $f[4];
880 $Info{"$f[0]KbRm"} = $f[5];
881 $Info{"$f[0]FileCntRm"} = $f[6];
882 $Info{"$f[0]FileCntRep"} = $f[7];
883 $Info{"$f[0]FileRepMax"} = $f[8];
884 $Info{"$f[0]FileCntRename"} = $f[9];
885 $Info{"$f[0]Time"} = time;
886 printf(LOG "%s%s nightly clean removed %d files of"
888 $bpc->timeStamp, ucfirst($f[0]),
889 $Info{"$f[0]FileCntRm"},
890 $Info{"$f[0]KbRm"} / (1000 * 1024));
891 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
892 . "%d max chain), %d directories\n",
893 $bpc->timeStamp, ucfirst($f[0]),
894 $Info{"$f[0]Kb"} / (1000 * 1024),
895 $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
896 $Info{"$f[0]FileRepMax"}, $Info{"$f[0]DirCnt"});
897 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
898 $RunNightlyWhenIdle = 0;
899 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
900 $Jobs{$host}{processState} = $1;
901 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
903 $Status{$h}{needLink} = 1;
905 print(LOG $bpc->timeStamp, "$host: $mesg\n");
909 # shut down the client connection if we read EOF
911 if ( $nbytes <= 0 ) {
912 close($Jobs{$host}{fh});
913 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
914 if ( $CmdJob eq $host ) {
915 my $cmd = $Jobs{$host}{cmd};
916 $cmd =~ s/$BinDir\///g;
917 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
918 $Status{$host}{state} = "Status_idle";
919 $Status{$host}{endTime} = time;
921 $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
922 && $RunNightlyWhenIdle );
925 # Queue BackupPC_link to complete the backup
926 # processing for this host.
928 if ( defined($Status{$host})
929 && ($Status{$host}{reason} eq "Reason_backup_done"
930 || $Status{$host}{needLink}) ) {
932 } elsif ( defined($Status{$host}) ) {
933 $Status{$host}{state} = "Status_idle";
936 delete($Jobs{$host});
937 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
941 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
942 # do a pass over %Status updating the deadCnt and aliveCnt for
943 # DHCP hosts. The reason we need to do this later is we can't
944 # be sure whether a DHCP host is alive or dead until we have passed
945 # over all the DHCP pool.
947 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
948 foreach my $host ( keys(%Status) ) {
949 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
950 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
951 $Status{$host}{dhcpCheckCnt} = 0;
952 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
953 $Status{$host}{aliveCnt} = 0;
958 ############################################################################
959 # Main_Check_Client_Messages($fdRead)
961 # Check for, and process, any output from our clients. Also checks
962 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
963 ############################################################################
964 sub Main_Check_Client_Messages
967 foreach my $client ( keys(%Clients) ) {
968 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
971 # do a last check to make sure there is something to read so
972 # we are absolutely sure we won't block.
974 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
975 if ( !select($readMask, undef, undef, 0.0) ) {
976 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
977 . " nothing to read from $client. Debug dump:\n");
978 my($dump) = Data::Dumper->new(
979 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
980 [qw(*Clients, *Jobs *FDread, *fdRead)]);
982 print(LOG $dump->Dump);
985 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
986 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
988 # Process any complete lines received from this client.
990 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
993 $Clients{$client}{mesg} = $2;
995 # Authenticate the message by checking the MD5 digest
997 my $md5 = Digest::MD5->new;
998 if ( $cmd !~ /^(.{22}) (.*)/
999 || ($md5->add($Clients{$client}{seed}
1000 . $Clients{$client}{mesgCnt}
1001 . $Conf{ServerMesgSecret} . $2),
1002 $md5->b64digest ne $1) ) {
1003 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1004 . " client '$Clients{$client}{clientName}':"
1005 . " shutting down client connection\n");
1009 $Clients{$client}{mesgCnt}++;
1011 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1015 if ( $CmdJob ne $host && defined($Status{$host})
1016 && defined($Jobs{$host}) ) {
1017 print(LOG $bpc->timeStamp,
1018 "Stopping current backup of $host,"
1019 . " request by $user (backoff=$backoff)\n");
1020 kill(2, $Jobs{$host}{pid});
1021 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1022 close($Jobs{$host}{fh});
1023 delete($Jobs{$host});
1024 $Status{$host}{state} = "Status_idle";
1025 $Status{$host}{reason} = "Reason_backup_canceled_by_user"; #FIXME: user should be $user (we need to substitute the variable in the l10n stuff)
1026 $Status{$host}{activeJob} = 0;
1027 $Status{$host}{startTime} = time;
1028 $reply = "ok: backup of $host cancelled";
1029 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1030 print(LOG $bpc->timeStamp,
1031 "Stopping pending backup of $host,"
1032 . " request by $user (backoff=$backoff)\n");
1033 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1034 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1035 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1036 $reply = "ok: pending backup of $host cancelled";
1038 print(LOG $bpc->timeStamp,
1039 "Nothing to do for stop backup of $host,"
1040 . " request by $user (backoff=$backoff)\n");
1041 $reply = "ok: no backup was pending or running";
1043 if ( defined($Status{$host}) && $backoff ne "" ) {
1044 if ( $backoff > 0 ) {
1045 $Status{$host}{backoffTime} = time + $backoff * 3600;
1047 delete($Status{$host}{backoffTime});
1050 } elsif ( $cmd =~ /^backup all$/ ) {
1052 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1057 if ( !defined($Status{$host}) ) {
1058 print(LOG $bpc->timeStamp,
1059 "User $user requested backup of unknown host"
1061 $reply = "error: unknown host $host";
1062 } elsif ( defined($Jobs{$host})
1063 && $Jobs{$host}{type} ne "restore" ) {
1064 print(LOG $bpc->timeStamp,
1065 "User $user requested backup of $host,"
1066 . " but one is currently running\n");
1067 $reply = "error: backup of $host is already running";
1069 print(LOG $bpc->timeStamp,
1070 "User $user requested backup of $host"
1072 if ( $BgQueueOn{$hostIP} ) {
1073 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1074 $BgQueueOn{$hostIP} = 0;
1076 if ( $UserQueueOn{$hostIP} ) {
1077 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1078 $UserQueueOn{$hostIP} = 0;
1080 unshift(@UserQueue, {
1085 dhcp => $hostIP eq $host ? 0 : 1,
1087 $UserQueueOn{$hostIP} = 1;
1088 $reply = "ok: requested backup of $host";
1090 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1094 my $reqFileName = $4;
1095 if ( !defined($Status{$host}) ) {
1096 print(LOG $bpc->timeStamp,
1097 "User $user requested restore to unknown host"
1099 $reply = "restore error: unknown host $host";
1101 print(LOG $bpc->timeStamp,
1102 "User $user requested restore to $host"
1104 unshift(@UserQueue, {
1107 reqFileName => $reqFileName,
1112 $UserQueueOn{$host} = 1;
1113 if ( defined($Jobs{$host}) ) {
1114 $reply = "ok: requested restore of $host, but a"
1115 . " job is currently running,"
1116 . " so this request will start later";
1118 $reply = "ok: requested restore of $host";
1121 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1123 my($dump, @values, @names);
1124 foreach my $type ( split(/\s+/, $args) ) {
1125 if ( $type =~ /^queues/ ) {
1126 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1127 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1128 } elsif ( $type =~ /^jobs/ ) {
1129 push(@values, \%Jobs);
1130 push(@names, qw(*Jobs));
1131 } elsif ( $type =~ /^queueLen/ ) {
1133 BgQueue => scalar(@BgQueue),
1134 UserQueue => scalar(@UserQueue),
1135 CmdQueue => scalar(@CmdQueue),
1137 push(@names, qw(*QueueLen));
1138 } elsif ( $type =~ /^info/ ) {
1139 push(@values, \%Info);
1140 push(@names, qw(*Info));
1141 } elsif ( $type =~ /^hosts/ ) {
1142 push(@values, \%Status);
1143 push(@names, qw(*Status));
1144 } elsif ( $type =~ /^host\((.*)\)/
1145 && defined($Status{$1}) ) {
1148 BgQueueOn => $BgQueueOn{$1},
1149 UserQueueOn => $UserQueueOn{$1},
1150 CmdQueueOn => $CmdQueueOn{$1},
1152 push(@names, qw(*StatusHost));
1154 print(LOG $bpc->timeStamp,
1155 "Unknown status request $type\n");
1158 $dump = Data::Dumper->new(\@values, \@names);
1160 $reply = $dump->Dump;
1161 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1164 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1165 print(LOG $bpc->timeStamp, "$1\n");
1166 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1170 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1171 $reply = "error: bad command $cmd";
1174 # send a reply to the client, at a minimum "ok\n".
1176 $reply = "ok" if ( $reply eq "" );
1178 syswrite($Clients{$client}{fh}, $reply, length($reply));
1181 # Detect possible denial-of-service attack from sending a huge line
1182 # (ie: never terminated). 32K seems to be plenty big enough as
1185 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1186 print(LOG $bpc->timeStamp, "Line too long from client"
1187 . " '$Clients{$client}{clientName}':"
1188 . " shutting down client connection\n");
1192 # Shut down the client connection if we read EOF
1194 if ( $nbytes <= 0 ) {
1195 close($Clients{$client}{fh});
1196 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1197 delete($Clients{$client});
1201 # Accept any new connections on each of our listen sockets
1203 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1205 my $paddr = accept(CLIENT, SERVER_UNIX);
1207 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1208 $Clients{$ClientConnCnt}{mesg} = "";
1209 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1210 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1211 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1213 # Generate and send unique seed for MD5 digests to avoid
1214 # replay attacks. See BackupPC::Lib::ServerMesg().
1216 my $seed = time . ",$ClientConnCnt,$$,0\n";
1217 $Clients{$ClientConnCnt}{seed} = $seed;
1218 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1219 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1221 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1223 my $paddr = accept(CLIENT, SERVER_INET);
1224 my($port,$iaddr) = sockaddr_in($paddr);
1225 my $name = gethostbyaddr($iaddr, AF_INET);
1227 $Clients{$ClientConnCnt}{mesg} = "";
1228 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1229 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1230 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1231 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1233 # Generate and send unique seed for MD5 digests to avoid
1234 # replay attacks. See BackupPC::Lib::ServerMesg().
1236 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1237 $Clients{$ClientConnCnt}{seed} = $seed;
1238 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1239 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1243 ###########################################################################
1244 # Miscellaneous subroutines
1245 ###########################################################################
1248 # Write the current status to $TopDir/log/status.pl
1252 my($dump) = Data::Dumper->new(
1253 [ \%Info, \%Status],
1254 [qw(*Info *Status)]);
1256 if ( open(STATUS, ">$TopDir/log/status.pl") ) {
1257 print(STATUS $dump->Dump);
1263 # Queue all the hosts for backup. This means queuing all the fixed
1264 # ip hosts and all the dhcp address ranges. We also additionally
1265 # queue the dhcp hosts with a -e flag to check for expired dumps.
1269 foreach my $host ( sort(keys(%$Hosts)) ) {
1270 delete($Status{$host}{backoffTime})
1271 if ( defined($Status{$host}{backoffTime})
1272 && $Status{$host}{backoffTime} < time );
1273 next if ( defined($Jobs{$host})
1274 || $BgQueueOn{$host}
1275 || $UserQueueOn{$host}
1276 || $CmdQueueOn{$host} );
1277 if ( $Hosts->{$host}{dhcp} ) {
1278 $Status{$host}{dhcpCheckCnt}++;
1279 if ( $RunNightlyWhenIdle ) {
1281 # Once per night queue a check for DHCP hosts that just
1282 # checks for expired dumps. We need to do this to handle
1283 # the case when a DHCP host has not been on the network for
1284 # a long time, and some of the old dumps need to be expired.
1285 # Normally expiry checks are done by BackupPC_dump only
1286 # after the DHCP hosts has been detected on the network.
1289 {host => $host, user => "BackupPC", reqTime => time,
1290 dhcp => 0, dumpExpire => 1});
1291 $BgQueueOn{$host} = 1;
1295 # this is a fixed ip host: queue it
1298 {host => $host, user => "BackupPC", reqTime => time,
1299 dhcp => $Hosts->{$host}{dhcp}});
1300 $BgQueueOn{$host} = 1;
1303 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1304 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1305 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1306 next if ( defined($Jobs{$ipAddr})
1307 || $BgQueueOn{$ipAddr}
1308 || $UserQueueOn{$ipAddr}
1309 || $CmdQueueOn{$ipAddr} );
1311 # this is a potential dhcp ip address (we don't know the
1312 # host name yet): queue it
1315 {host => $ipAddr, user => "BackupPC", reqTime => time,
1317 $BgQueueOn{$ipAddr} = 1;
1323 # Queue a BackupPC_link for the given host
1329 return if ( $CmdQueueOn{$host} );
1330 $Status{$host}{state} = "Status_link_pending";
1331 $Status{$host}{needLink} = 0;
1332 unshift(@CmdQueue, {
1336 cmd => "$BinDir/BackupPC_link $host"
1338 $CmdQueueOn{$host} = 1;
1342 # Read the hosts file, and update Status if any hosts have been
1343 # added or deleted. We also track the mtime so the only need to
1344 # update the hosts file on changes.
1346 # This function is called at startup, SIGHUP, and on each wakeup.
1347 # It returns 1 on success and undef on failure.
1354 # Nothing to do if we already have the current hosts file
1356 return 1 if ( !$force && defined($Hosts)
1357 && $Info{HostsModTime} == $bpc->HostsMTime() );
1358 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1359 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1362 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1364 $Info{HostsModTime} = $bpc->HostsMTime();
1366 # Now update %Status in case any hosts have been added or deleted
1368 foreach my $host ( sort(keys(%$Hosts)) ) {
1369 next if ( defined($Status{$host}) );
1370 $Status{$host}{state} = "Status_idle";
1371 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1373 foreach my $host ( sort(keys(%Status)) ) {
1374 next if ( $host eq $bpc->trashJob
1375 || $host eq $bpc->adminJob
1376 || defined($Hosts->{$host})
1377 || defined($Jobs{$host})
1378 || $BgQueueOn{$host}
1379 || $UserQueueOn{$host}
1380 || $CmdQueueOn{$host} );
1381 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1382 delete($Status{$host});
1388 # Remember the signal name for later processing
1394 foreach my $host ( keys(%Jobs) ) {
1395 kill(2, $Jobs{$host}{pid});
1398 # In case we are inside the exit handler, reopen the log file
1402 print(LOG "Fatal error: unhandled signal $SigName\n");
1403 unlink("$TopDir/log/BackupPC.pid");
1404 confess("Got new signal $SigName... quitting\n");
1410 # Open the log file and point STDOUT and STDERR there too
1414 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1415 open(LOG, ">>$TopDir/log/LOG")
1416 || die("Can't create LOG file $TopDir/log/LOG");
1419 open(STDOUT, ">&LOG");
1420 open(STDERR, ">&LOG");
1421 select(LOG); $| = 1;
1422 select(STDERR); $| = 1;
1423 select(STDOUT); $| = 1;
1427 # Initialize the unix-domain and internet-domain sockets that
1428 # we listen to for client connections (from the CGI script and
1429 # some of the BackupPC sub-programs).
1431 sub ServerSocketInit
1433 if ( !defined(fileno(SERVER_UNIX)) ) {
1435 # one-time only: initialize unix-domain socket
1437 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1438 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1441 my $sockFile = "$TopDir/log/BackupPC.sock";
1443 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1444 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1447 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1448 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1451 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1453 return if ( $ServerInetPort == $Conf{ServerPort} );
1454 if ( $ServerInetPort > 0 ) {
1455 vec($FDread, fileno(SERVER_INET), 1) = 0;
1457 $ServerInetPort = -1;
1459 if ( $Conf{ServerPort} > 0 ) {
1461 # Setup a socket to listen on $Conf{ServerPort}
1463 my $proto = getprotobyname('tcp');
1464 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1465 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1468 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1469 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1472 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1473 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1476 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1477 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1480 vec($FDread, fileno(SERVER_INET), 1) = 1;
1481 $ServerInetPort = $Conf{ServerPort};