/[BackupPC]/upstream/2.1.0/bin/BackupPC
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /upstream/2.1.0/bin/BackupPC

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1 - (hide annotations)
Wed Jun 22 19:12:04 2005 UTC (18 years, 9 months ago) by dpavlin
File size: 68822 byte(s)
import of version 2.1.0

1 dpavlin 1 #!/bin/perl
2     #============================================================= -*-perl-*-
3     #
4     # BackupPC: Main program for PC backups.
5     #
6     # DESCRIPTION
7     #
8     # BackupPC reads the configuration and status information from
9     # $TopDir/conf. It then runs and manages all the backup activity.
10     #
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).
22     #
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.
27     #
28     # AUTHOR
29     # Craig Barratt <cbarratt@users.sourceforge.net>
30     #
31     # COPYRIGHT
32     # Copyright (C) 2001-2003 Craig Barratt
33     #
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.
38     #
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.
43     #
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
47     #
48     #========================================================================
49     #
50     # Version 2.1.0, released 20 Jun 2004.
51     #
52     # See http://backuppc.sourceforge.net.
53     #
54     #========================================================================
55    
56     use strict;
57     no utf8;
58     use vars qw(%Status %Info $Hosts);
59     use lib "__INSTALLDIR__/lib";
60     use BackupPC::Lib;
61     use BackupPC::FileZIO;
62    
63     use File::Path;
64     use Data::Dumper;
65     use Getopt::Std;
66     use Socket;
67     use Carp;
68     use Digest::MD5;
69    
70     ###########################################################################
71     # Handle command line options
72     ###########################################################################
73     my %opts;
74     if ( !getopts("d", \%opts) || @ARGV != 0 ) {
75     print("usage: $0 [-d]\n");
76     exit(1);
77     }
78    
79     ###########################################################################
80     # Initialize major data structures and variables
81     ###########################################################################
82    
83     #
84     # Get an instance of BackupPC::Lib and get some shortcuts.
85     #
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();
90    
91     #
92     # Verify we are running as the correct user
93     #
94     if ( $Conf{BackupPCUserVerify}
95     && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
96     die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
97     }
98    
99     #
100     # %Status maintain status information about each host.
101     # It is a hash of hashes, whose first index is the host.
102     #
103     %Status = ();
104    
105     #
106     # %Info is a hash giving general information about BackupPC status.
107     #
108     %Info = ();
109    
110     #
111     # Read old status
112     #
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";
117     }
118    
119     #
120     # %Jobs maintains information about currently running jobs.
121     # It is a hash of hashes, whose first index is the host.
122     #
123     my %Jobs = ();
124    
125     #
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.
133     #
134     my @UserQueue = ();
135     my @CmdQueue = ();
136     my @BgQueue = ();
137    
138     #
139     # To quickly lookup if a given host is on a given queue, we keep
140     # a hash of flags for each queue type.
141     #
142     my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
143    
144     #
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.
150     #
151     my %Clients = ();
152     my $ClientConnCnt;
153    
154     #
155     # Read file descriptor mask used by select(). Every file descriptor
156     # on which we expect to read (or accept) has the corresponding bit
157     # set.
158     #
159     my $FDread = '';
160    
161     #
162     # Unix seconds when we next wakeup. A value of zero forces the scheduler
163     # to compute the next wakeup time.
164     #
165     my $NextWakeup = 0;
166    
167     #
168     # Name of signal saved by catch_signal
169     #
170     my $SigName = "";
171    
172     #
173     # Misc variables
174     #
175     my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
176     my($BackupPCNightlyJobs, $BackupPCNightlyLock);
177    
178     #
179     # Complete the rest of the initialization
180     #
181     Main_Initialize();
182    
183     ###########################################################################
184     # Main loop
185     ###########################################################################
186     while ( 1 )
187     {
188     #
189     # Check if we can/should run BackupPC_nightly
190     #
191     Main_TryToRun_nightly();
192    
193     #
194     # Check if we can run a new command from @CmdQueue.
195     #
196     Main_TryToRun_CmdQueue();
197    
198     #
199     # Check if we can run a new command from @UserQueue or @BgQueue.
200     #
201     Main_TryToRun_Bg_or_User_Queue();
202    
203     #
204     # Do a select() to wait for the next interesting thing to happen
205     # (timeout, signal, someone sends a message, child dies etc).
206     #
207     my $fdRead = Main_Select();
208    
209     #
210     # Process a signal if we received one.
211     #
212     if ( $SigName ) {
213     Main_Process_Signal();
214     $fdRead = undef;
215     }
216    
217     #
218     # Check if a timeout has occurred.
219     #
220     Main_Check_Timeout();
221    
222     #
223     # Check for, and process, any messages (output) from our jobs
224     #
225     Main_Check_Job_Messages($fdRead);
226    
227     #
228     # Check for, and process, any output from our clients. Also checks
229     # for new connections to our SERVER_UNIX and SERVER_INET sockets.
230     #
231     Main_Check_Client_Messages($fdRead);
232     }
233    
234     ############################################################################
235     # Main_Initialize()
236     #
237     # Main initialization routine. Called once at statup.
238     ############################################################################
239     sub Main_Initialize
240     {
241     umask($Conf{UmaskMode});
242    
243     #
244     # Check for another running process, check that PASSWD is set and
245     # verify executables are configured correctly.
246     #
247     if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
248     print(STDERR $bpc->timeStamp,
249     "Another BackupPC is running (pid $Info{pid}); quitting...\n");
250     exit(1);
251     }
252     foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
253     SendmailPath SshPath) ) {
254     next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
255     print(STDERR $bpc->timeStamp,
256     "\$Conf{$progName} = '$Conf{$progName}' is not a"
257     . " valid executable program\n");
258     exit(1);
259     }
260    
261     if ( $opts{d} ) {
262     #
263     # daemonize by forking
264     #
265     defined(my $pid = fork) or die "Can't fork: $!";
266     exit if $pid; # parent exits
267     }
268    
269     #
270     # Open the LOG file and redirect STDOUT, STDERR etc
271     #
272     LogFileOpen();
273    
274     #
275     # Read the hosts file (force a read).
276     #
277     exit(1) if ( !HostsUpdate(1) );
278    
279     #
280     # Clean up %ENV for taint checking
281     #
282     delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
283     $ENV{PATH} = $Conf{MyPath};
284    
285     #
286     # Initialize server sockets
287     #
288     ServerSocketInit();
289    
290     #
291     # Catch various signals
292     #
293     foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
294     $SIG{$sig} = \&catch_signal;
295     }
296    
297     #
298     # Report that we started, and update %Info.
299     #
300     print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
301     $Info{ConfigModTime} = $bpc->ConfigMTime();
302     $Info{pid} = $$;
303     $Info{startTime} = time;
304     $Info{ConfigLTime} = time;
305     $Info{Version} = $bpc->{Version};
306    
307     #
308     # Update the status left over form the last time BackupPC ran.
309     # Requeue any pending links.
310     #
311     foreach my $host ( sort(keys(%$Hosts)) ) {
312     if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
313     #
314     # should we restart it? skip it for now.
315     #
316     $Status{$host}{state} = "Status_idle";
317     } elsif ( $Status{$host}{state} eq "Status_link_pending"
318     || $Status{$host}{state} eq "Status_link_running" ) {
319     QueueLink($host);
320     } else {
321     $Status{$host}{state} = "Status_idle";
322     }
323     $Status{$host}{activeJob} = 0;
324     }
325     foreach my $host ( sort(keys(%Status)) ) {
326     next if ( defined($Hosts->{$host}) );
327     delete($Status{$host});
328     }
329    
330     #
331     # Write out our initial status and save our PID
332     #
333     StatusWrite();
334     if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
335     print(PID $$);
336     close(PID);
337     }
338    
339     #
340     # For unknown reasons there is a very infrequent error about not
341     # being able to coerce GLOBs inside the XS Data::Dumper. I've
342     # only seen this on a particular platform and perl version.
343     # For now the workaround appears to be use the perl version of
344     # XS Data::Dumper.
345     #
346     $Data::Dumper::Useqq = 1;
347     }
348    
349     ############################################################################
350     # Main_TryToRun_nightly()
351     #
352     # Checks to see if we can/should run BackupPC_nightly or
353     # BackupPC_trashClean. If so we push the appropriate command onto
354     # @CmdQueue.
355     ############################################################################
356     sub Main_TryToRun_nightly
357     {
358     #
359     # Check if we should run BackupPC_nightly or BackupPC_trashClean.
360     # BackupPC_nightly is run when the current job queue is empty.
361     # BackupPC_trashClean is run in the background always.
362     #
363     my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
364     if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
365     #
366     # This should only happen once at startup, but just in case this
367     # code will re-start BackupPC_trashClean if it quits
368     #
369     unshift(@CmdQueue, {
370     host => $bpc->trashJob,
371     user => "BackupPC",
372     reqTime => time,
373     cmd => ["$BinDir/BackupPC_trashClean"],
374     });
375     $CmdQueueOn{$bpc->trashJob} = 1;
376     }
377     if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
378    
379     #
380     # Queue multiple nightly jobs based on the configuration
381     #
382     $Conf{MaxBackupPCNightlyJobs} = 1
383     if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
384     $Conf{BackupPCNightlyPeriod} = 1
385     if ( $Conf{BackupPCNightlyPeriod} <= 0 );
386     #
387     # Decide what subset of the 16 top-level directories 0..9a..f
388     # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
389     # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
390     # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
391     # 0..7 one night and 89a-f the next night. And so on.
392     #
393     # $Info{NightlyPhase} counts which night, from 0 to
394     # $Conf{BackupPCNightlyPeriod} - 1.
395     #
396     my $start = int($Info{NightlyPhase} * 16
397     / $Conf{BackupPCNightlyPeriod});
398     my $end = int(($Info{NightlyPhase} + 1) * 16
399     / $Conf{BackupPCNightlyPeriod});
400     $end = $start + 1 if ( $end <= $start );
401     $Info{NightlyPhase}++;
402     $Info{NightlyPhase} = 0 if ( $end >= 16 );
403    
404     #
405     # Zero out the data we expect to get from BackupPC_nightly.
406     # In the future if we want to split BackupPC_nightly over
407     # more than one night we will only zero out the portion
408     # that we are running right now.
409     #
410     for my $p ( qw(pool cpool) ) {
411     for ( my $i = $start ; $i < $end ; $i++ ) {
412     $Info{pool}{$p}[$i]{FileCnt} = 0;
413     $Info{pool}{$p}[$i]{DirCnt} = 0;
414     $Info{pool}{$p}[$i]{Kb} = 0;
415     $Info{pool}{$p}[$i]{Kb2} = 0;
416     $Info{pool}{$p}[$i]{KbRm} = 0;
417     $Info{pool}{$p}[$i]{FileCntRm} = 0;
418     $Info{pool}{$p}[$i]{FileCntRep} = 0;
419     $Info{pool}{$p}[$i]{FileRepMax} = 0;
420     $Info{pool}{$p}[$i]{FileCntRename} = 0;
421     $Info{pool}{$p}[$i]{FileLinkMax} = 0;
422     $Info{pool}{$p}[$i]{Time} = 0;
423     }
424     }
425     print(LOG $bpc->timeStamp,
426     sprintf("Running %d BackupPC_nightly jobs from %d..%d"
427     . " (out of 0..15)\n",
428     $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
429    
430     #
431     # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
432     # The granularity on start and end is now 0..256.
433     #
434     $start *= 16;
435     $end *= 16;
436     my $start0 = $start;
437     for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
438     #
439     # The first nightly job gets the -m option (does email, log aging).
440     # All jobs get the start and end options from 0..255 telling
441     # them which parts of the pool to traverse.
442     #
443     my $cmd = ["$BinDir/BackupPC_nightly"];
444     push(@$cmd, "-m") if ( $i == 0 );
445     push(@$cmd, $start);
446     $start = $start0 + int(($end - $start0)
447     * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
448     push(@$cmd, $start - 1);
449    
450     my $job = $bpc->adminJob($i);
451     unshift(@CmdQueue, {
452     host => $job,
453     user => "BackupPC",
454     reqTime => time,
455     cmd => $cmd,
456     });
457     $CmdQueueOn{$job} = 1;
458     }
459     $RunNightlyWhenIdle = 2;
460    
461     }
462     }
463    
464     ############################################################################
465     # Main_TryToRun_CmdQueue()
466     #
467     # Decide if we can run a new command from the @CmdQueue.
468     # We only run one of these at a time. The @CmdQueue is
469     # used to run BackupPC_link (for the corresponding host),
470     # BackupPC_trashClean, and BackupPC_nightly using a fake
471     # host name of $bpc->adminJob.
472     ############################################################################
473     sub Main_TryToRun_CmdQueue
474     {
475     my($req, $host);
476    
477     while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
478     || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
479     && $bpc->isAdminJob($CmdQueue[0]->{host})
480     ) {
481     local(*FH);
482     $req = pop(@CmdQueue);
483    
484     $host = $req->{host};
485     if ( defined($Jobs{$host}) ) {
486     print(LOG $bpc->timeStamp,
487     "Botch on admin job for $host: already in use!!\n");
488     #
489     # This could happen during normal opertion: a user could
490     # request a backup while a BackupPC_link is queued from
491     # a previous backup. But it is unlikely. Just put this
492     # request back on the end of the queue.
493     #
494     unshift(@CmdQueue, $req);
495     return;
496     }
497     $CmdQueueOn{$host} = 0;
498     my $cmd = $req->{cmd};
499     my $pid = open(FH, "-|");
500     if ( !defined($pid) ) {
501     print(LOG $bpc->timeStamp,
502     "can't fork for $host, request by $req->{user}\n");
503     close(FH);
504     next;
505     }
506     if ( !$pid ) {
507     setpgrp 0,0;
508     exec(@$cmd);
509     print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
510     exit(0);
511     }
512     $Jobs{$host}{pid} = $pid;
513     $Jobs{$host}{fh} = *FH;
514     $Jobs{$host}{fn} = fileno(FH);
515     vec($FDread, $Jobs{$host}{fn}, 1) = 1;
516     $Jobs{$host}{startTime} = time;
517     $Jobs{$host}{reqTime} = $req->{reqTime};
518     $cmd = $bpc->execCmd2ShellCmd(@$cmd);
519     $Jobs{$host}{cmd} = $cmd;
520     $Jobs{$host}{user} = $req->{user};
521     $Jobs{$host}{type} = $Status{$host}{type};
522     $Status{$host}{state} = "Status_link_running";
523     $Status{$host}{activeJob} = 1;
524     $Status{$host}{endTime} = time;
525     $CmdJob = $host if ( $host ne $bpc->trashJob );
526     $cmd =~ s/$BinDir\///g;
527     print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
528     if ( $cmd =~ /^BackupPC_nightly\s/ ) {
529     $BackupPCNightlyJobs++;
530     $BackupPCNightlyLock++;
531     }
532     }
533     }
534    
535     ############################################################################
536     # Main_TryToRun_Bg_or_User_Queue()
537     #
538     # Decide if we can run any new backup requests from @BgQueue
539     # or @UserQueue. Several of these can be run at the same time
540     # based on %Conf settings. Jobs from @UserQueue take priority,
541     # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
542     # simultaneous jobs can run from @UserQueue. After @UserQueue
543     # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
544     # run from @BgQueue.
545     ############################################################################
546     sub Main_TryToRun_Bg_or_User_Queue
547     {
548     my($req, $host);
549     while ( $RunNightlyWhenIdle == 0 ) {
550     local(*FH);
551     my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
552     my $nJobs = keys(%Jobs);
553     #
554     # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
555     #
556     $nJobs -= $BackupPCNightlyJobs if ( $CmdJob ne "" );
557     $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
558     if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
559     && @UserQueue > 0 ) {
560     $req = pop(@UserQueue);
561     if ( defined($Jobs{$req->{host}}) ) {
562     push(@deferUserQueue, $req);
563     next;
564     }
565     push(@args, $req->{doFull} ? "-f" : "-i")
566     if (( !$req->{restore} ) && ( !$req->{archive} ));
567     $UserQueueOn{$req->{host}} = 0;
568     } elsif ( $nJobs < $Conf{MaxBackups}
569     && (@CmdQueue + $nJobs)
570     <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
571     && @BgQueue > 0 ) {
572     my $du;
573     if ( time - $Info{DUlastValueTime} >= 60 ) {
574     #
575     # Update our notion of disk usage no more than
576     # once every minute
577     #
578     $du = $bpc->CheckFileSystemUsage($TopDir);
579     $Info{DUlastValue} = $du;
580     $Info{DUlastValueTime} = time;
581     } else {
582     #
583     # if we recently checked it then just use the old value
584     #
585     $du = $Info{DUlastValue};
586     }
587     if ( $Info{DUDailyMaxReset} ) {
588     $Info{DUDailyMaxStartTime} = time;
589     $Info{DUDailyMaxReset} = 0;
590     $Info{DUDailyMax} = 0;
591     }
592     if ( $du > $Info{DUDailyMax} ) {
593     $Info{DUDailyMax} = $du;
594     $Info{DUDailyMaxTime} = time;
595     }
596     if ( $du > $Conf{DfMaxUsagePct} ) {
597     my $nSkip = @BgQueue + @deferBgQueue;
598     print(LOG $bpc->timeStamp,
599     "Disk too full ($du%); skipping $nSkip hosts\n");
600     $Info{DUDailySkipHostCnt} += $nSkip;
601     @BgQueue = ();
602     @deferBgQueue = ();
603     %BgQueueOn = ();
604     next;
605     }
606     $req = pop(@BgQueue);
607     if ( defined($Jobs{$req->{host}}) ) {
608     push(@deferBgQueue, $req);
609     next;
610     }
611     $BgQueueOn{$req->{host}} = 0;
612     } else {
613     while ( @deferBgQueue ) {
614     push(@BgQueue, pop(@deferBgQueue));
615     }
616     while ( @deferUserQueue ) {
617     push(@UserQueue, pop(@deferUserQueue));
618     }
619     last;
620     }
621     $host = $req->{host};
622     my $user = $req->{user};
623     if ( $req->{restore} ) {
624     $progName = "BackupPC_restore";
625     $type = "restore";
626     push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
627     } elsif ( $req->{archive} ) {
628     $progName = "BackupPC_archive";
629     $type = "archive";
630     push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
631     } else {
632     $progName = "BackupPC_dump";
633     $type = "backup";
634     push(@args, "-d") if ( $req->{dhcp} );
635     push(@args, "-e") if ( $req->{dumpExpire} );
636     push(@args, $host);
637     }
638     my $pid = open(FH, "-|");
639     if ( !defined($pid) ) {
640     print(LOG $bpc->timeStamp,
641     "can't fork to run $progName for $host, request by $user\n");
642     close(FH);
643     next;
644     }
645     if ( !$pid ) {
646     setpgrp 0,0;
647     exec("$BinDir/$progName", @args);
648     print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
649     exit(0);
650     }
651     $Jobs{$host}{pid} = $pid;
652     $Jobs{$host}{fh} = *FH;
653     $Jobs{$host}{fn} = fileno(FH);
654     $Jobs{$host}{dhcp} = $req->{dhcp};
655     vec($FDread, $Jobs{$host}{fn}, 1) = 1;
656     $Jobs{$host}{startTime} = time;
657     $Jobs{$host}{reqTime} = $req->{reqTime};
658     $Jobs{$host}{userReq} = $req->{userReq};
659     $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
660     $Jobs{$host}{user} = $user;
661     $Jobs{$host}{type} = $type;
662     $Status{$host}{userReq} = $req->{userReq}
663     if ( defined($Hosts->{$host}) );
664     if ( !$req->{dhcp} ) {
665     $Status{$host}{state} = "Status_".$type."_starting";
666     $Status{$host}{activeJob} = 1;
667     $Status{$host}{startTime} = time;
668     $Status{$host}{endTime} = "";
669     }
670     }
671     }
672    
673     ############################################################################
674     # Main_Select()
675     #
676     # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
677     # and then do a select() to wait for the next thing to happen
678     # (timeout, signal, someone sends a message, child dies etc).
679     ############################################################################
680     sub Main_Select
681     {
682     if ( $NextWakeup <= 0 ) {
683     #
684     # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
685     #
686     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
687     = localtime(time);
688     my($currHours) = $hour + $min / 60 + $sec / 3600;
689     if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
690     ServerReload("Re-read config file because mtime changed");
691     }
692     my $delta = -1;
693     foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
694     next if ( $t < 0 || $t > 24 );
695     my $tomorrow = $t + 24;
696     if ( $delta < 0
697     || ($tomorrow - $currHours > 0
698     && $delta > $tomorrow - $currHours) ) {
699     $delta = $tomorrow - $currHours;
700     $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
701     }
702     if ( $delta < 0
703     || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
704     $delta = $t - $currHours;
705     $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
706     }
707     }
708     $NextWakeup = time + $delta * 3600;
709     $Info{nextWakeup} = $NextWakeup;
710     print(LOG $bpc->timeStamp, "Next wakeup is ",
711     $bpc->timeStamp($NextWakeup, 1), "\n");
712     }
713     #
714     # Call select(), waiting until either a signal, a timeout,
715     # any output from our jobs, or any messages from clients
716     # connected via tcp.
717     # select() is where we (hopefully) spend most of our time blocked...
718     #
719     my $timeout = $NextWakeup - time;
720     $timeout = 1 if ( $timeout <= 0 );
721     my $ein = $FDread;
722     select(my $rout = $FDread, undef, $ein, $timeout);
723    
724     return $rout;
725     }
726    
727     ############################################################################
728     # Main_Process_Signal()
729     #
730     # Signal handler.
731     ############################################################################
732     sub Main_Process_Signal
733     {
734     #
735     # Process signals
736     #
737     if ( $SigName eq "HUP" ) {
738     ServerReload("Re-read config file because of a SIG_HUP");
739     } elsif ( $SigName ) {
740     ServerShutdown("Got signal $SigName... cleaning up");
741     }
742     $SigName = "";
743     }
744    
745     ############################################################################
746     # Main_Check_Timeout()
747     #
748     # Check if a timeout has occured, and if so, queue all the PCs for backups.
749     # Also does log file aging on the first timeout after midnight.
750     ############################################################################
751     sub Main_Check_Timeout
752     {
753     #
754     # Process timeouts
755     #
756     return if ( time < $NextWakeup || $NextWakeup <= 0 );
757     $NextWakeup = 0;
758     if ( $FirstWakeup ) {
759     #
760     # This is the first wakeup after midnight. Do log file aging
761     # and various house keeping.
762     #
763     $FirstWakeup = 0;
764     printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
765     . " %d skipped hosts\n",
766     $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
767     $Info{DUDailySkipHostCnt});
768     $Info{DUDailyMaxReset} = 1;
769     $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
770     $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
771     $Info{DUDailySkipHostCnt} = 0;
772     my $lastLog = $Conf{MaxOldLogFiles} - 1;
773     if ( -f "$TopDir/log/LOG.$lastLog" ) {
774     print(LOG $bpc->timeStamp,
775     "Removing $TopDir/log/LOG.$lastLog\n");
776     unlink("$TopDir/log/LOG.$lastLog");
777     }
778     if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
779     print(LOG $bpc->timeStamp,
780     "Removing $TopDir/log/LOG.$lastLog.z\n");
781     unlink("$TopDir/log/LOG.$lastLog.z");
782     }
783     print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
784     . "LOG.1 -> ... -> LOG.$lastLog\n");
785     close(STDERR); # dup of LOG
786     close(STDOUT); # dup of LOG
787     close(LOG);
788     for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
789     my $j = $i + 1;
790     rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
791     if ( -f "$TopDir/log/LOG.$i" );
792     rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
793     if ( -f "$TopDir/log/LOG.$i.z" );
794     }
795     #
796     # Compress the log file LOG -> LOG.0.z (if enabled).
797     # Otherwise, just rename LOG -> LOG.0.
798     #
799     BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
800     "$TopDir/log/LOG.0.z",
801     "$TopDir/log/LOG.0",
802     $Conf{CompressLevel}, 1);
803     LogFileOpen();
804     #
805     # Remember to run nightly script after current jobs are done
806     #
807     $RunNightlyWhenIdle = 1;
808     }
809     #
810     # Write out the current status and then queue all the PCs
811     #
812     HostsUpdate(0);
813     StatusWrite();
814     %BgQueueOn = () if ( @BgQueue == 0 );
815     %UserQueueOn = () if ( @UserQueue == 0 );
816     %CmdQueueOn = () if ( @CmdQueue == 0 );
817     QueueAllPCs();
818     }
819    
820     ############################################################################
821     # Main_Check_Job_Messages($fdRead)
822     #
823     # Check if select() says we have bytes waiting from any of our jobs.
824     # Handle each of the messages when complete (newline terminated).
825     ############################################################################
826     sub Main_Check_Job_Messages
827     {
828     my($fdRead) = @_;
829     foreach my $host ( keys(%Jobs) ) {
830     next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
831     my $mesg;
832     #
833     # do a last check to make sure there is something to read so
834     # we are absolutely sure we won't block.
835     #
836     vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
837     if ( !select($readMask, undef, undef, 0.0) ) {
838     print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
839     . " nothing to read from $host. Debug dump:\n");
840     my($dump) = Data::Dumper->new(
841     [ \%Clients, \%Jobs, \$FDread, \$fdRead],
842     [qw(*Clients, *Jobs *FDread, *fdRead)]);
843     $dump->Indent(1);
844     print(LOG $dump->Dump);
845     next;
846     }
847     my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
848     $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
849     #
850     # Process any complete lines of output from this jobs.
851     # Any output to STDOUT or STDERR from the children is processed here.
852     #
853     while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
854     $mesg = $1;
855     $Jobs{$host}{mesg} = $2;
856     if ( $Jobs{$host}{dhcp} ) {
857     if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
858     my $newHost = $bpc->uriUnesc($2);
859     if ( defined($Jobs{$newHost}) ) {
860     print(LOG $bpc->timeStamp,
861     "Backup on $newHost is already running\n");
862     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
863     $nbytes = 0;
864     last;
865     }
866     $Jobs{$host}{dhcpHostIP} = $host;
867     $Status{$newHost}{dhcpHostIP} = $host;
868     $Jobs{$newHost} = $Jobs{$host};
869     delete($Jobs{$host});
870     $host = $newHost;
871     $Status{$host}{state} = "Status_backup_starting";
872     $Status{$host}{activeJob} = 1;
873     $Status{$host}{startTime} = $Jobs{$host}{startTime};
874     $Status{$host}{endTime} = "";
875     $Jobs{$host}{dhcp} = 0;
876     } else {
877     print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
878     }
879     } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
880     $Jobs{$host}{type} = $1;
881     $Jobs{$host}{shareName} = $2;
882     print(LOG $bpc->timeStamp,
883     "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
884     $Jobs{$host}{dhcpHostIP}
885     ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
886     ", share=$Jobs{$host}{shareName})\n");
887     $Status{$host}{state} = "Status_backup_in_progress";
888     $Status{$host}{reason} = "";
889     $Status{$host}{type} = $1;
890     $Status{$host}{startTime} = time;
891     $Status{$host}{deadCnt} = 0;
892     $Status{$host}{aliveCnt}++;
893     $Status{$host}{dhcpCheckCnt}--
894     if ( $Status{$host}{dhcpCheckCnt} > 0 );
895     } elsif ( $mesg =~ /^xferPids (.*)/ ) {
896     $Jobs{$host}{xferPid} = $1;
897     } elsif ( $mesg =~ /^started_restore/ ) {
898     $Jobs{$host}{type} = "restore";
899     print(LOG $bpc->timeStamp,
900     "Started restore on $host"
901     . " (pid=$Jobs{$host}{pid})\n");
902     $Status{$host}{state} = "Status_restore_in_progress";
903     $Status{$host}{reason} = "";
904     $Status{$host}{type} = "restore";
905     $Status{$host}{startTime} = time;
906     $Status{$host}{deadCnt} = 0;
907     $Status{$host}{aliveCnt}++;
908     } elsif ( $mesg =~ /^started_archive/ ) {
909     $Jobs{$host}{type} = "archive";
910     print(LOG $bpc->timeStamp,
911     "Started archive on $host"
912     . " (pid=$Jobs{$host}{pid})\n");
913     $Status{$host}{state} = "Status_archive_in_progress";
914     $Status{$host}{reason} = "";
915     $Status{$host}{type} = "archive";
916     $Status{$host}{startTime} = time;
917     $Status{$host}{deadCnt} = 0;
918     $Status{$host}{aliveCnt}++;
919     } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
920     print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
921     $Status{$host}{reason} = "Reason_backup_done";
922     delete($Status{$host}{error});
923     delete($Status{$host}{errorTime});
924     $Status{$host}{endTime} = time;
925     } elsif ( $mesg =~ /^backups disabled/ ) {
926     print(LOG $bpc->timeStamp,
927     "Ignoring old backup error on $host\n");
928     $Status{$host}{reason} = "Reason_backup_done";
929     delete($Status{$host}{error});
930     delete($Status{$host}{errorTime});
931     $Status{$host}{endTime} = time;
932     } elsif ( $mesg =~ /^restore complete/ ) {
933     print(LOG $bpc->timeStamp, "Finished restore on $host\n");
934     $Status{$host}{reason} = "Reason_restore_done";
935     delete($Status{$host}{error});
936     delete($Status{$host}{errorTime});
937     $Status{$host}{endTime} = time;
938     } elsif ( $mesg =~ /^archive complete/ ) {
939     print(LOG $bpc->timeStamp, "Finished archive on $host\n");
940     $Status{$host}{reason} = "Reason_archive_done";
941     delete($Status{$host}{error});
942     delete($Status{$host}{errorTime});
943     $Status{$host}{endTime} = time;
944     } elsif ( $mesg =~ /^nothing to do/ ) {
945     if ( $Status{$host}{reason} ne "Reason_backup_failed"
946     && $Status{$host}{reason} ne "Reason_restore_failed" ) {
947     $Status{$host}{state} = "Status_idle";
948     $Status{$host}{reason} = "Reason_nothing_to_do";
949     $Status{$host}{startTime} = time;
950     }
951     $Status{$host}{dhcpCheckCnt}--
952     if ( $Status{$host}{dhcpCheckCnt} > 0 );
953     } elsif ( $mesg =~ /^no ping response/
954     || $mesg =~ /^ping too slow/
955     || $mesg =~ /^host not found/ ) {
956     $Status{$host}{state} = "Status_idle";
957     if ( $Status{$host}{userReq}
958     || $Status{$host}{reason} ne "Reason_backup_failed"
959     || $Status{$host}{error} =~ /^aborted by user/ ) {
960     $Status{$host}{reason} = "Reason_no_ping";
961     $Status{$host}{error} = $mesg;
962     $Status{$host}{startTime} = time;
963     }
964     $Status{$host}{deadCnt}++;
965     if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
966     $Status{$host}{aliveCnt} = 0;
967     }
968     } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
969     $Status{$host}{state} = "Status_idle";
970     $Status{$host}{error} = $1;
971     $Status{$host}{errorTime} = time;
972     $Status{$host}{endTime} = time;
973     if ( $Status{$host}{reason}
974     eq "Reason_backup_canceled_by_user" ) {
975     print(LOG $bpc->timeStamp,
976     "Backup canceled on $host ($1)\n");
977     } else {
978     $Status{$host}{reason} = "Reason_backup_failed";
979     print(LOG $bpc->timeStamp,
980     "Backup failed on $host ($1)\n");
981     }
982     } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
983     $Status{$host}{state} = "Status_idle";
984     $Status{$host}{error} = $1;
985     $Status{$host}{errorTime} = time;
986     $Status{$host}{endTime} = time;
987     if ( $Status{$host}{reason}
988     eq "Reason_restore_canceled_by_user" ) {
989     print(LOG $bpc->timeStamp,
990     "Restore canceled on $host ($1)\n");
991     } else {
992     $Status{$host}{reason} = "Reason_restore_failed";
993     print(LOG $bpc->timeStamp,
994     "Restore failed on $host ($1)\n");
995     }
996     } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
997     $Status{$host}{state} = "Status_idle";
998     $Status{$host}{error} = $1;
999     $Status{$host}{errorTime} = time;
1000     $Status{$host}{endTime} = time;
1001     if ( $Status{$host}{reason}
1002     eq "Reason_archive_canceled_by_user" ) {
1003     print(LOG $bpc->timeStamp,
1004     "Archive canceled on $host ($1)\n");
1005     } else {
1006     $Status{$host}{reason} = "Reason_archive_failed";
1007     print(LOG $bpc->timeStamp,
1008     "Archive failed on $host ($1)\n");
1009     }
1010     } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1011     print(LOG $bpc->timeStamp, "$1\n");
1012     } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1013     my $chunk = int($1 / 16);
1014     my @f = split(/,/, $2);
1015     $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1016     $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1017     $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1018     $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1019     $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1020     $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1021     $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1022     $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1023     if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1024     $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1025     $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1026     if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1027     $Info{pool}{$f[0]}[$chunk]{Time} = time;
1028     } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1029     $BackupPCNightlyLock--;
1030     if ( $BackupPCNightlyLock == 0 ) {
1031     #
1032     # This means the last BackupPC_nightly is done with
1033     # the pool clean, so it's to start running regular
1034     # backups again.
1035     #
1036     $RunNightlyWhenIdle = 0;
1037     }
1038     } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1039     $Jobs{$host}{processState} = $1;
1040     } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1041     my($h) = $1;
1042     $Status{$h}{needLink} = 1;
1043     } else {
1044     print(LOG $bpc->timeStamp, "$host: $mesg\n");
1045     }
1046     }
1047     #
1048     # shut down the client connection if we read EOF
1049     #
1050     if ( $nbytes <= 0 ) {
1051     close($Jobs{$host}{fh});
1052     vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1053     if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1054     my $cmd = $Jobs{$host}{cmd};
1055     $cmd =~ s/$BinDir\///g;
1056     print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1057     $Status{$host}{state} = "Status_idle";
1058     $Status{$host}{endTime} = time;
1059     if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1060     $BackupPCNightlyJobs--;
1061     #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1062     # . " have $BackupPCNightlyJobs running\n");
1063     if ( $BackupPCNightlyJobs <= 0 ) {
1064     $BackupPCNightlyJobs = 0;
1065     $RunNightlyWhenIdle = 0;
1066     $CmdJob = "";
1067     #
1068     # Combine the 16 per-directory results
1069     #
1070     for my $p ( qw(pool cpool) ) {
1071     $Info{"${p}FileCnt"} = 0;
1072     $Info{"${p}DirCnt"} = 0;
1073     $Info{"${p}Kb"} = 0;
1074     $Info{"${p}Kb2"} = 0;
1075     $Info{"${p}KbRm"} = 0;
1076     $Info{"${p}FileCntRm"} = 0;
1077     $Info{"${p}FileCntRep"} = 0;
1078     $Info{"${p}FileRepMax"} = 0;
1079     $Info{"${p}FileCntRename"} = 0;
1080     $Info{"${p}FileLinkMax"} = 0;
1081     $Info{"${p}Time"} = 0;
1082     for ( my $i = 0 ; $i < 16 ; $i++ ) {
1083     $Info{"${p}FileCnt"}
1084     += $Info{pool}{$p}[$i]{FileCnt};
1085     $Info{"${p}DirCnt"}
1086     += $Info{pool}{$p}[$i]{DirCnt};
1087     $Info{"${p}Kb"}
1088     += $Info{pool}{$p}[$i]{Kb};
1089     $Info{"${p}Kb2"}
1090     += $Info{pool}{$p}[$i]{Kb2};
1091     $Info{"${p}KbRm"}
1092     += $Info{pool}{$p}[$i]{KbRm};
1093     $Info{"${p}FileCntRm"}
1094     += $Info{pool}{$p}[$i]{FileCntRm};
1095     $Info{"${p}FileCntRep"}
1096     += $Info{pool}{$p}[$i]{FileCntRep};
1097     $Info{"${p}FileRepMax"}
1098     = $Info{pool}{$p}[$i]{FileRepMax}
1099     if ( $Info{"${p}FileRepMax"} <
1100     $Info{pool}{$p}[$i]{FileRepMax} );
1101     $Info{"${p}FileCntRename"}
1102     += $Info{pool}{$p}[$i]{FileCntRename};
1103     $Info{"${p}FileLinkMax"}
1104     = $Info{pool}{$p}[$i]{FileLinkMax}
1105     if ( $Info{"${p}FileLinkMax"} <
1106     $Info{pool}{$p}[$i]{FileLinkMax} );
1107     $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1108     if ( $Info{"${p}Time"} <
1109     $Info{pool}{$p}[$i]{Time} );
1110     }
1111     printf(LOG "%s%s nightly clean removed %d files of"
1112     . " size %.2fGB\n",
1113     $bpc->timeStamp, ucfirst($p),
1114     $Info{"${p}FileCntRm"},
1115     $Info{"${p}KbRm"} / (1000 * 1024));
1116     printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1117     . "%d max chain, %d max links), %d directories\n",
1118     $bpc->timeStamp, ucfirst($p),
1119     $Info{"${p}Kb"} / (1000 * 1024),
1120     $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1121     $Info{"${p}FileRepMax"},
1122     $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1123     }
1124     }
1125     } else {
1126     $CmdJob = "";
1127     }
1128     } else {
1129     #
1130     # Queue BackupPC_link to complete the backup
1131     # processing for this host.
1132     #
1133     if ( defined($Status{$host})
1134     && ($Status{$host}{reason} eq "Reason_backup_done"
1135     || $Status{$host}{needLink}) ) {
1136     QueueLink($host);
1137     } elsif ( defined($Status{$host}) ) {
1138     $Status{$host}{state} = "Status_idle";
1139     }
1140     }
1141     delete($Jobs{$host});
1142     $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1143     }
1144     }
1145     #
1146     # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1147     # do a pass over %Status updating the deadCnt and aliveCnt for
1148     # DHCP hosts. The reason we need to do this later is we can't
1149     # be sure whether a DHCP host is alive or dead until we have passed
1150     # over all the DHCP pool.
1151     #
1152     return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1153     foreach my $host ( keys(%Status) ) {
1154     next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1155     $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1156     $Status{$host}{dhcpCheckCnt} = 0;
1157     if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1158     $Status{$host}{aliveCnt} = 0;
1159     }
1160     }
1161     }
1162    
1163     ############################################################################
1164     # Main_Check_Client_Messages($fdRead)
1165     #
1166     # Check for, and process, any output from our clients. Also checks
1167     # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1168     ############################################################################
1169     sub Main_Check_Client_Messages
1170     {
1171     my($fdRead) = @_;
1172     foreach my $client ( keys(%Clients) ) {
1173     next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1174     my($mesg, $host);
1175     #
1176     # do a last check to make sure there is something to read so
1177     # we are absolutely sure we won't block.
1178     #
1179     vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1180     if ( !select($readMask, undef, undef, 0.0) ) {
1181     print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1182     . " nothing to read from $client. Debug dump:\n");
1183     my($dump) = Data::Dumper->new(
1184     [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1185     [qw(*Clients, *Jobs *FDread, *fdRead)]);
1186     $dump->Indent(1);
1187     print(LOG $dump->Dump);
1188     next;
1189     }
1190     my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1191     $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1192     #
1193     # Process any complete lines received from this client.
1194     #
1195     while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1196     my($reply);
1197     my $cmd = $1;
1198     $Clients{$client}{mesg} = $2;
1199     #
1200     # Authenticate the message by checking the MD5 digest
1201     #
1202     my $md5 = Digest::MD5->new;
1203     if ( $cmd !~ /^(.{22}) (.*)/
1204     || ($md5->add($Clients{$client}{seed}
1205     . $Clients{$client}{mesgCnt}
1206     . $Conf{ServerMesgSecret} . $2),
1207     $md5->b64digest ne $1) ) {
1208     print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1209     . " client '$Clients{$client}{clientName}':"
1210     . " shutting down client connection\n");
1211     $nbytes = 0;
1212     last;
1213     }
1214     $Clients{$client}{mesgCnt}++;
1215     $cmd = $2;
1216     if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1217     $host = $1;
1218     my $user = $2;
1219     my $backoff = $3;
1220     $host = $bpc->uriUnesc($host);
1221     if ( $CmdJob ne $host && defined($Status{$host})
1222     && defined($Jobs{$host}) ) {
1223     print(LOG $bpc->timeStamp,
1224     "Stopping current $Jobs{$host}{type} of $host,"
1225     . " request by $user (backoff=$backoff)\n");
1226     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1227     #
1228     # Don't close the pipe now; wait until the child
1229     # really exits later. Otherwise close() will
1230     # block until the child has exited.
1231     # old code:
1232     ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1233     ##close($Jobs{$host}{fh});
1234     ##delete($Jobs{$host});
1235    
1236     $Status{$host}{state} = "Status_idle";
1237     if ( $Jobs{$host}{type} eq "restore" ) {
1238     $Status{$host}{reason}
1239     = "Reason_restore_canceled_by_user";
1240     } elsif ( $Jobs{$host}{type} eq "archive" ) {
1241     $Status{$host}{reason}
1242     = "Reason_archive_canceled_by_user";
1243     } else {
1244     $Status{$host}{reason}
1245     = "Reason_backup_canceled_by_user";
1246     }
1247     $Status{$host}{activeJob} = 0;
1248     $Status{$host}{startTime} = time;
1249     $reply = "ok: $Jobs{$host}{type} of $host canceled";
1250     } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1251     print(LOG $bpc->timeStamp,
1252     "Stopping pending backup of $host,"
1253     . " request by $user (backoff=$backoff)\n");
1254     @BgQueue = grep($_->{host} ne $host, @BgQueue);
1255     @UserQueue = grep($_->{host} ne $host, @UserQueue);
1256     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1257     $reply = "ok: pending backup of $host canceled";
1258     } else {
1259     print(LOG $bpc->timeStamp,
1260     "Nothing to do for stop backup of $host,"
1261     . " request by $user (backoff=$backoff)\n");
1262     $reply = "ok: no backup was pending or running";
1263     }
1264     if ( defined($Status{$host}) && $backoff ne "" ) {
1265     if ( $backoff > 0 ) {
1266     $Status{$host}{backoffTime} = time + $backoff * 3600;
1267     } else {
1268     delete($Status{$host}{backoffTime});
1269     }
1270     }
1271     } elsif ( $cmd =~ /^backup all$/ ) {
1272     QueueAllPCs();
1273     } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1274     $RunNightlyWhenIdle = 1;
1275     } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1276     my $hostIP = $1;
1277     $host = $2;
1278     my $user = $3;
1279     my $doFull = $4;
1280     $host = $bpc->uriUnesc($host);
1281     $hostIP = $bpc->uriUnesc($hostIP);
1282     if ( !defined($Status{$host}) ) {
1283     print(LOG $bpc->timeStamp,
1284     "User $user requested backup of unknown host"
1285     . " $host\n");
1286     $reply = "error: unknown host $host";
1287     } elsif ( defined($Jobs{$host})
1288     && $Jobs{$host}{type} ne "restore" ) {
1289     print(LOG $bpc->timeStamp,
1290     "User $user requested backup of $host,"
1291     . " but one is currently running\n");
1292     $reply = "error: backup of $host is already running";
1293     } else {
1294     print(LOG $bpc->timeStamp,
1295     "User $user requested backup of $host"
1296     . " ($hostIP)\n");
1297     if ( $BgQueueOn{$hostIP} ) {
1298     @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1299     $BgQueueOn{$hostIP} = 0;
1300     }
1301     if ( $UserQueueOn{$hostIP} ) {
1302     @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1303     $UserQueueOn{$hostIP} = 0;
1304     }
1305     unshift(@UserQueue, {
1306     host => $hostIP,
1307     user => $user,
1308     reqTime => time,
1309     doFull => $doFull,
1310     userReq => 1,
1311     dhcp => $hostIP eq $host ? 0 : 1,
1312     });
1313     $UserQueueOn{$hostIP} = 1;
1314     $reply = "ok: requested backup of $host";
1315     }
1316     } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1317     my $user = $1;
1318     my $archivehost = $2;
1319     my $reqFileName = $3;
1320     $host = $bpc->uriUnesc($archivehost);
1321     if ( !defined($Status{$host}) ) {
1322     print(LOG $bpc->timeStamp,
1323     "User $user requested archive of unknown archive host"
1324     . " $host");
1325     $reply = "archive error: unknown archive host $host";
1326     } else {
1327     print(LOG $bpc->timeStamp,
1328     "User $user requested archive on $host"
1329     . " ($host)\n");
1330     if ( defined($Jobs{$host}) ) {
1331     $reply = "Archive currently running on $host, please try later";
1332     } else {
1333     unshift(@UserQueue, {
1334     host => $host,
1335     hostIP => $user,
1336     reqFileName => $reqFileName,
1337     reqTime => time,
1338     dhcp => 0,
1339     archive => 1,
1340     userReq => 1,
1341     });
1342     $UserQueueOn{$host} = 1;
1343     $reply = "ok: requested archive on $host";
1344     }
1345     }
1346     } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1347     my $hostIP = $1;
1348     $host = $2;
1349     my $user = $3;
1350     my $reqFileName = $4;
1351     $host = $bpc->uriUnesc($host);
1352     $hostIP = $bpc->uriUnesc($hostIP);
1353     if ( !defined($Status{$host}) ) {
1354     print(LOG $bpc->timeStamp,
1355     "User $user requested restore to unknown host"
1356     . " $host");
1357     $reply = "restore error: unknown host $host";
1358     } else {
1359     print(LOG $bpc->timeStamp,
1360     "User $user requested restore to $host"
1361     . " ($hostIP)\n");
1362     unshift(@UserQueue, {
1363     host => $host,
1364     hostIP => $hostIP,
1365     reqFileName => $reqFileName,
1366     reqTime => time,
1367     dhcp => 0,
1368     restore => 1,
1369     userReq => 1,
1370     });
1371     $UserQueueOn{$host} = 1;
1372     if ( defined($Jobs{$host}) ) {
1373     $reply = "ok: requested restore of $host, but a"
1374     . " job is currently running,"
1375     . " so this request will start later";
1376     } else {
1377     $reply = "ok: requested restore of $host";
1378     }
1379     }
1380     } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1381     my($args) = $1;
1382     my($dump, @values, @names);
1383     foreach my $type ( split(/\s+/, $args) ) {
1384     if ( $type =~ /^queues/ ) {
1385     push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1386     push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1387     } elsif ( $type =~ /^jobs/ ) {
1388     push(@values, \%Jobs);
1389     push(@names, qw(*Jobs));
1390     } elsif ( $type =~ /^queueLen/ ) {
1391     push(@values, {
1392     BgQueue => scalar(@BgQueue),
1393     UserQueue => scalar(@UserQueue),
1394     CmdQueue => scalar(@CmdQueue),
1395     });
1396     push(@names, qw(*QueueLen));
1397     } elsif ( $type =~ /^info/ ) {
1398     push(@values, \%Info);
1399     push(@names, qw(*Info));
1400     } elsif ( $type =~ /^hosts/ ) {
1401     push(@values, \%Status);
1402     push(@names, qw(*Status));
1403     } elsif ( $type =~ /^host\((.*)\)/ ) {
1404     my $h = $bpc->uriUnesc($1);
1405     if ( defined($Status{$h}) ) {
1406     push(@values, {
1407     %{$Status{$h}},
1408     BgQueueOn => $BgQueueOn{$h},
1409     UserQueueOn => $UserQueueOn{$h},
1410     CmdQueueOn => $CmdQueueOn{$h},
1411     });
1412     push(@names, qw(*StatusHost));
1413     } else {
1414     print(LOG $bpc->timeStamp,
1415     "Unknown host $h for status request\n");
1416     }
1417     } else {
1418     print(LOG $bpc->timeStamp,
1419     "Unknown status request $type\n");
1420     }
1421     }
1422     $dump = Data::Dumper->new(\@values, \@names);
1423     $dump->Indent(0);
1424     $reply = $dump->Dump;
1425     } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1426     my($host) = $1;
1427     $host = $bpc->uriUnesc($host);
1428     QueueLink($host);
1429     } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1430     print(LOG $bpc->timeStamp, "$1\n");
1431     } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1432     my($type) = $1;
1433     if ( $type eq 'reload' ) {
1434     ServerReload("Reloading config/host files via CGI request");
1435     } elsif ( $type eq 'shutdown' ) {
1436     $reply = "Shutting down...\n";
1437     syswrite($Clients{$client}{fh}, $reply, length($reply));
1438     ServerShutdown("Server shutting down...");
1439     }
1440     } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1441     $nbytes = 0;
1442     last;
1443     } else {
1444     print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1445     $reply = "error: bad command $cmd";
1446     }
1447     #
1448     # send a reply to the client, at a minimum "ok\n".
1449     #
1450     $reply = "ok" if ( $reply eq "" );
1451     $reply .= "\n";
1452     syswrite($Clients{$client}{fh}, $reply, length($reply));
1453     }
1454     #
1455     # Detect possible denial-of-service attack from sending a huge line
1456     # (ie: never terminated). 32K seems to be plenty big enough as
1457     # a limit.
1458     #
1459     if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1460     print(LOG $bpc->timeStamp, "Line too long from client"
1461     . " '$Clients{$client}{clientName}':"
1462     . " shutting down client connection\n");
1463     $nbytes = 0;
1464     }
1465     #
1466     # Shut down the client connection if we read EOF
1467     #
1468     if ( $nbytes <= 0 ) {
1469     close($Clients{$client}{fh});
1470     vec($FDread, $Clients{$client}{fn}, 1) = 0;
1471     delete($Clients{$client});
1472     }
1473     }
1474     #
1475     # Accept any new connections on each of our listen sockets
1476     #
1477     if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1478     local(*CLIENT);
1479     my $paddr = accept(CLIENT, SERVER_UNIX);
1480     $ClientConnCnt++;
1481     $Clients{$ClientConnCnt}{clientName} = "unix socket";
1482     $Clients{$ClientConnCnt}{mesg} = "";
1483     $Clients{$ClientConnCnt}{fh} = *CLIENT;
1484     $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1485     vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1486     #
1487     # Generate and send unique seed for MD5 digests to avoid
1488     # replay attacks. See BackupPC::Lib::ServerMesg().
1489     #
1490     my $seed = time . ",$ClientConnCnt,$$,0\n";
1491     $Clients{$ClientConnCnt}{seed} = $seed;
1492     $Clients{$ClientConnCnt}{mesgCnt} = 0;
1493     syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1494     }
1495     if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1496     local(*CLIENT);
1497     my $paddr = accept(CLIENT, SERVER_INET);
1498     my($port,$iaddr) = sockaddr_in($paddr);
1499     my $name = gethostbyaddr($iaddr, AF_INET);
1500     $ClientConnCnt++;
1501     $Clients{$ClientConnCnt}{mesg} = "";
1502     $Clients{$ClientConnCnt}{fh} = *CLIENT;
1503     $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1504     $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1505     vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1506     #
1507     # Generate and send unique seed for MD5 digests to avoid
1508     # replay attacks. See BackupPC::Lib::ServerMesg().
1509     #
1510     my $seed = time . ",$ClientConnCnt,$$,$port\n";
1511     $Clients{$ClientConnCnt}{seed} = $seed;
1512     $Clients{$ClientConnCnt}{mesgCnt} = 0;
1513     syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1514     }
1515     }
1516    
1517     ###########################################################################
1518     # Miscellaneous subroutines
1519     ###########################################################################
1520    
1521     #
1522     # Write the current status to $TopDir/log/status.pl
1523     #
1524     sub StatusWrite
1525     {
1526     my($dump) = Data::Dumper->new(
1527     [ \%Info, \%Status],
1528     [qw(*Info *Status)]);
1529     $dump->Indent(1);
1530     if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1531     print(STATUS $dump->Dump);
1532     close(STATUS);
1533     }
1534     }
1535    
1536     #
1537     # Compare function for host sort. Hosts with errors go first,
1538     # sorted with the oldest errors first. The remaining hosts
1539     # are sorted so that those with the oldest backups go first.
1540     #
1541     sub HostSortCompare
1542     {
1543     return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1544     return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1545     return $Status{$a}{endTime} <=> $Status{$b}{endTime};
1546     }
1547    
1548     #
1549     # Queue all the hosts for backup. This means queuing all the fixed
1550     # ip hosts and all the dhcp address ranges. We also additionally
1551     # queue the dhcp hosts with a -e flag to check for expired dumps.
1552     #
1553     sub QueueAllPCs
1554     {
1555     foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1556     delete($Status{$host}{backoffTime})
1557     if ( defined($Status{$host}{backoffTime})
1558     && $Status{$host}{backoffTime} < time );
1559     next if ( defined($Jobs{$host})
1560     || $BgQueueOn{$host}
1561     || $UserQueueOn{$host}
1562     || $CmdQueueOn{$host} );
1563     if ( $Hosts->{$host}{dhcp} ) {
1564     $Status{$host}{dhcpCheckCnt}++;
1565     if ( $RunNightlyWhenIdle ) {
1566     #
1567     # Once per night queue a check for DHCP hosts that just
1568     # checks for expired dumps. We need to do this to handle
1569     # the case when a DHCP host has not been on the network for
1570     # a long time, and some of the old dumps need to be expired.
1571     # Normally expiry checks are done by BackupPC_dump only
1572     # after the DHCP hosts has been detected on the network.
1573     #
1574     unshift(@BgQueue,
1575     {host => $host, user => "BackupPC", reqTime => time,
1576     dhcp => 0, dumpExpire => 1});
1577     $BgQueueOn{$host} = 1;
1578     }
1579     } else {
1580     #
1581     # this is a fixed ip host: queue it
1582     #
1583     unshift(@BgQueue,
1584     {host => $host, user => "BackupPC", reqTime => time,
1585     dhcp => $Hosts->{$host}{dhcp}});
1586     $BgQueueOn{$host} = 1;
1587     }
1588     }
1589     foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1590     for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1591     my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1592     next if ( defined($Jobs{$ipAddr})
1593     || $BgQueueOn{$ipAddr}
1594     || $UserQueueOn{$ipAddr}
1595     || $CmdQueueOn{$ipAddr} );
1596     #
1597     # this is a potential dhcp ip address (we don't know the
1598     # host name yet): queue it
1599     #
1600     unshift(@BgQueue,
1601     {host => $ipAddr, user => "BackupPC", reqTime => time,
1602     dhcp => 1});
1603     $BgQueueOn{$ipAddr} = 1;
1604     }
1605     }
1606     }
1607    
1608     #
1609     # Queue a BackupPC_link for the given host
1610     #
1611     sub QueueLink
1612     {
1613     my($host) = @_;
1614    
1615     return if ( $CmdQueueOn{$host} );
1616     $Status{$host}{state} = "Status_link_pending";
1617     $Status{$host}{needLink} = 0;
1618     unshift(@CmdQueue, {
1619     host => $host,
1620     user => "BackupPC",
1621     reqTime => time,
1622     cmd => ["$BinDir/BackupPC_link", $host],
1623     });
1624     $CmdQueueOn{$host} = 1;
1625     }
1626    
1627     #
1628     # Read the hosts file, and update Status if any hosts have been
1629     # added or deleted. We also track the mtime so the only need to
1630     # update the hosts file on changes.
1631     #
1632     # This function is called at startup, SIGHUP, and on each wakeup.
1633     # It returns 1 on success and undef on failure.
1634     #
1635     sub HostsUpdate
1636     {
1637     my($force) = @_;
1638     my $newHosts;
1639     #
1640     # Nothing to do if we already have the current hosts file
1641     #
1642     return 1 if ( !$force && defined($Hosts)
1643     && $Info{HostsModTime} == $bpc->HostsMTime() );
1644     if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1645     print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1646     return;
1647     }
1648     print(LOG $bpc->timeStamp, "Reading hosts file\n");
1649     $Hosts = $newHosts;
1650     $Info{HostsModTime} = $bpc->HostsMTime();
1651     #
1652     # Now update %Status in case any hosts have been added or deleted
1653     #
1654     foreach my $host ( sort(keys(%$Hosts)) ) {
1655     next if ( defined($Status{$host}) );
1656     $Status{$host}{state} = "Status_idle";
1657     print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1658     }
1659     foreach my $host ( sort(keys(%Status)) ) {
1660     next if ( $host eq $bpc->trashJob
1661     || $bpc->isAdminJob($host)
1662     || defined($Hosts->{$host})
1663     || defined($Jobs{$host})
1664     || $BgQueueOn{$host}
1665     || $UserQueueOn{$host}
1666     || $CmdQueueOn{$host} );
1667     print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1668     delete($Status{$host});
1669     }
1670     return 1;
1671     }
1672    
1673     #
1674     # Remember the signal name for later processing
1675     #
1676     sub catch_signal
1677     {
1678     if ( $SigName ) {
1679     $SigName = shift;
1680     foreach my $host ( keys(%Jobs) ) {
1681     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1682     }
1683     #
1684     # In case we are inside the exit handler, reopen the log file
1685     #
1686     close(LOG);
1687     LogFileOpen();
1688     print(LOG "Fatal error: unhandled signal $SigName\n");
1689     unlink("$TopDir/log/BackupPC.pid");
1690     confess("Got new signal $SigName... quitting\n");
1691     } else {
1692     $SigName = shift;
1693     }
1694     }
1695    
1696     #
1697     # Open the log file and point STDOUT and STDERR there too
1698     #
1699     sub LogFileOpen
1700     {
1701     mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1702     open(LOG, ">>$TopDir/log/LOG")
1703     || die("Can't create LOG file $TopDir/log/LOG");
1704     close(STDOUT);
1705     close(STDERR);
1706     open(STDOUT, ">&LOG");
1707     open(STDERR, ">&LOG");
1708     select(LOG); $| = 1;
1709     select(STDERR); $| = 1;
1710     select(STDOUT); $| = 1;
1711     }
1712    
1713     #
1714     # Initialize the unix-domain and internet-domain sockets that
1715     # we listen to for client connections (from the CGI script and
1716     # some of the BackupPC sub-programs).
1717     #
1718     sub ServerSocketInit
1719     {
1720     if ( !defined(fileno(SERVER_UNIX)) ) {
1721     #
1722     # one-time only: initialize unix-domain socket
1723     #
1724     if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1725     print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1726     exit(1);
1727     }
1728     my $sockFile = "$TopDir/log/BackupPC.sock";
1729     unlink($sockFile);
1730     if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1731     print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1732     exit(1);
1733     }
1734     if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1735     print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1736     exit(1);
1737     }
1738     vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1739     }
1740     return if ( $ServerInetPort == $Conf{ServerPort} );
1741     if ( $ServerInetPort > 0 ) {
1742     vec($FDread, fileno(SERVER_INET), 1) = 0;
1743     close(SERVER_INET);
1744     $ServerInetPort = -1;
1745     }
1746     if ( $Conf{ServerPort} > 0 ) {
1747     #
1748     # Setup a socket to listen on $Conf{ServerPort}
1749     #
1750     my $proto = getprotobyname('tcp');
1751     if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1752     print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1753     exit(1);
1754     }
1755     if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1756     print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1757     exit(1);
1758     }
1759     if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1760     print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1761     exit(1);
1762     }
1763     if ( !listen(SERVER_INET, SOMAXCONN) ) {
1764     print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1765     exit(1);
1766     }
1767     vec($FDread, fileno(SERVER_INET), 1) = 1;
1768     $ServerInetPort = $Conf{ServerPort};
1769     }
1770     }
1771    
1772     #
1773     # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1774     # or when the command "server reload" is received.
1775     #
1776     sub ServerReload
1777     {
1778     my($mesg) = @_;
1779     $mesg = $bpc->ConfigRead() || $mesg;
1780     print(LOG $bpc->timeStamp, "$mesg\n");
1781     $Info{ConfigModTime} = $bpc->ConfigMTime();
1782     %Conf = $bpc->Conf();
1783     umask($Conf{UmaskMode});
1784     ServerSocketInit();
1785     HostsUpdate(0);
1786     $NextWakeup = 0;
1787     $Info{ConfigLTime} = time;
1788     }
1789    
1790     #
1791     # Gracefully shutdown the server. Used by Main_Process_Signal when
1792     # $SigName ne "" && $SigName ne "HUP" or when the command
1793     # "server shutdown" is received.
1794     #
1795     sub ServerShutdown
1796     {
1797     my($mesg) = @_;
1798     print(LOG $bpc->timeStamp, "$mesg\n");
1799     if ( keys(%Jobs) ) {
1800     foreach my $host ( keys(%Jobs) ) {
1801     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1802     }
1803     sleep(1);
1804     foreach my $host ( keys(%Jobs) ) {
1805     kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1806     }
1807     %Jobs = ();
1808     }
1809     StatusWrite();
1810     unlink("$TopDir/log/BackupPC.pid");
1811     exit(1);
1812     }
1813    

Properties

Name Value
svn:executable

  ViewVC Help
Powered by ViewVC 1.1.26