dab51db8b2a4f5ec01d8ccf55a4ad47b59562329
[BackupPC.git] / bin / BackupPC
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 "/usr/local/BackupPC/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     my(@deferUserQueue, @deferBgQueue);
550     my $du;
551
552     if ( time - $Info{DUlastValueTime} >= 600 ) {
553         #
554         # Update our notion of disk usage no more than
555         # once every 10 minutes
556         #
557         $du = $bpc->CheckFileSystemUsage($TopDir);
558         $Info{DUlastValue}     = $du;
559         $Info{DUlastValueTime} = time;
560     } else {
561         #
562         # if we recently checked it then just use the old value
563         #
564         $du = $Info{DUlastValue};
565     }
566     if ( $Info{DUDailyMaxReset} ) {
567         $Info{DUDailyMaxStartTime} = time;
568         $Info{DUDailyMaxReset}     = 0;
569         $Info{DUDailyMax}          = 0;
570     }
571     if ( $du > $Info{DUDailyMax} ) {
572         $Info{DUDailyMax}     = $du;
573         $Info{DUDailyMaxTime} = time;
574     }
575     if ( $du > $Conf{DfMaxUsagePct} ) {
576         my @bgQueue = @BgQueue;
577         my $nSkip = 0;
578
579         #
580         # When the disk is too full, only run backups that will
581         # do expires, not regular backups
582         #
583         @BgQueue = ();
584         foreach $req ( @bgQueue ) {
585             if ( $req->{dumpExpire} ) {
586                 unshift(@BgQueue, $req);
587             } else {
588                 $BgQueueOn{$req->{host}} = 0;
589                 $nSkip++;
590             }
591         }
592         if ( $nSkip ) {
593             print(LOG $bpc->timeStamp,
594                        "Disk too full ($du%); skipped $nSkip hosts\n");
595             $Info{DUDailySkipHostCnt} += $nSkip;
596         }
597     }
598
599     while ( $RunNightlyWhenIdle == 0 ) {
600         local(*FH);
601         my(@args, $progName, $type);
602         my $nJobs = keys(%Jobs);
603         #
604         # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
605         #
606         if ( $CmdJob ne "" ) {
607             if ( $BackupPCNightlyJobs ) {
608                 $nJobs -= $BackupPCNightlyJobs;
609             } else {
610                 $nJobs--;
611             }
612         }
613         $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
614         if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
615                         && @UserQueue > 0 ) {
616             $req = pop(@UserQueue);
617             if ( defined($Jobs{$req->{host}}) ) {
618                 push(@deferUserQueue, $req);
619                 next;
620             }
621             push(@args, $req->{doFull} ? "-f" : "-i")
622                             if (( !$req->{restore} ) && ( !$req->{archive} ));
623             $UserQueueOn{$req->{host}} = 0;
624         } elsif ( $nJobs < $Conf{MaxBackups}
625                         && (@CmdQueue + $nJobs)
626                                 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
627                         && @BgQueue > 0 ) {
628             $req = pop(@BgQueue);
629             if ( defined($Jobs{$req->{host}}) ) {
630                 #
631                 # Job is currently running for this host; save it for later
632                 #
633                 unshift(@deferBgQueue, $req);
634                 next;
635             }
636             $BgQueueOn{$req->{host}} = 0;
637         } else {
638             #
639             # Restore the deferred jobs
640             #
641             @BgQueue   = (@BgQueue,   @deferBgQueue);
642             @UserQueue = (@UserQueue, @deferUserQueue);
643             last;
644         }
645         $host = $req->{host};
646         my $user = $req->{user};
647         if ( $req->{restore} ) {
648             $progName = "BackupPC_restore";
649             $type     = "restore";
650             push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
651         } elsif ( $req->{archive} ) {
652             $progName = "BackupPC_archive";
653             $type     = "archive";
654             push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
655         } else {
656             $progName = "BackupPC_dump";
657             $type     = "backup";
658             push(@args, "-d") if ( $req->{dhcp} );
659             push(@args, "-e") if ( $req->{dumpExpire} );
660             push(@args, $host);
661         }
662         my $pid = open(FH, "-|");
663         if ( !defined($pid) ) {
664             print(LOG $bpc->timeStamp,
665                    "can't fork to run $progName for $host, request by $user\n");
666             close(FH);
667             next;
668         }
669         if ( !$pid ) {
670             setpgrp 0,0;
671             exec("$BinDir/$progName", @args);
672             print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
673             exit(0);
674         }
675         $Jobs{$host}{pid}        = $pid;
676         $Jobs{$host}{fh}         = *FH;
677         $Jobs{$host}{fn}         = fileno(FH);
678         $Jobs{$host}{dhcp}       = $req->{dhcp};
679         vec($FDread, $Jobs{$host}{fn}, 1) = 1;
680         $Jobs{$host}{startTime}  = time;
681         $Jobs{$host}{reqTime}    = $req->{reqTime};
682         $Jobs{$host}{userReq}    = $req->{userReq};
683         $Jobs{$host}{cmd}        = $bpc->execCmd2ShellCmd($progName, @args);
684         $Jobs{$host}{user}       = $user;
685         $Jobs{$host}{type}       = $type;
686         $Status{$host}{userReq}  = $req->{userReq}
687                                         if ( defined($Hosts->{$host}) );
688         if ( !$req->{dhcp} ) {
689             $Status{$host}{state}     = "Status_".$type."_starting";
690             $Status{$host}{activeJob} = 1;
691             $Status{$host}{startTime} = time;
692             $Status{$host}{endTime}   = "";
693         }
694     }
695 }
696
697 ############################################################################
698 # Main_Select()
699 #
700 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
701 # and then do a select() to wait for the next thing to happen
702 # (timeout, signal, someone sends a message, child dies etc).
703 ############################################################################
704 sub Main_Select
705 {
706     if ( $NextWakeup <= 0 ) {
707         #
708         # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
709         #
710         my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
711                                                 = localtime(time);
712         my($currHours) = $hour + $min / 60 + $sec / 3600;
713         if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
714             ServerReload("Re-read config file because mtime changed");
715         }
716         my $delta = -1;
717         foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
718             next if ( $t < 0 || $t > 24 );
719             my $tomorrow = $t + 24;
720             if ( $delta < 0
721                 || ($tomorrow - $currHours > 0
722                                 && $delta > $tomorrow - $currHours) ) {
723                 $delta = $tomorrow - $currHours;
724                 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
725             }
726             if ( $delta < 0
727                     || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
728                 $delta = $t - $currHours;
729                 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
730             }
731         }
732         $NextWakeup = time + $delta * 3600;
733         $Info{nextWakeup} = $NextWakeup;
734         print(LOG $bpc->timeStamp, "Next wakeup is ",
735                   $bpc->timeStamp($NextWakeup, 1), "\n");
736     }
737     #
738     # Call select(), waiting until either a signal, a timeout,
739     # any output from our jobs, or any messages from clients
740     # connected via tcp.
741     # select() is where we (hopefully) spend most of our time blocked...
742     #
743     my $timeout = $NextWakeup - time;
744     $timeout = 1 if ( $timeout <= 0 );
745     my $ein = $FDread;
746     select(my $rout = $FDread, undef, $ein, $timeout);
747
748     return $rout;
749 }
750
751 ############################################################################
752 # Main_Process_Signal()
753 #
754 # Signal handler.
755 ############################################################################
756 sub Main_Process_Signal
757 {
758     #
759     # Process signals
760     #
761     if ( $SigName eq "HUP" ) {
762         ServerReload("Re-read config file because of a SIG_HUP");
763     } elsif ( $SigName ) {
764         ServerShutdown("Got signal $SigName... cleaning up");
765     }
766     $SigName = "";
767 }
768
769 ############################################################################
770 # Main_Check_Timeout()
771 #
772 # Check if a timeout has occured, and if so, queue all the PCs for backups.
773 # Also does log file aging on the first timeout after midnight.
774 ############################################################################
775 sub Main_Check_Timeout
776 {
777     #
778     # Process timeouts
779     #
780     return if ( time < $NextWakeup || $NextWakeup <= 0 );
781     $NextWakeup = 0;
782     if ( $FirstWakeup ) {
783         #
784         # This is the first wakeup after midnight.  Do log file aging
785         # and various house keeping.
786         #
787         $FirstWakeup = 0;
788         printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
789                    . " %d skipped hosts\n",
790                    $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
791                    $Info{DUDailySkipHostCnt});
792         $Info{DUDailyMaxReset}        = 1;
793         $Info{DUDailyMaxPrev}         = $Info{DUDailyMax};
794         $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
795         $Info{DUDailySkipHostCnt}     = 0;
796         my $lastLog = $Conf{MaxOldLogFiles} - 1;
797         if ( -f "$TopDir/log/LOG.$lastLog" ) {
798             print(LOG $bpc->timeStamp,
799                        "Removing $TopDir/log/LOG.$lastLog\n");
800             unlink("$TopDir/log/LOG.$lastLog");
801         }
802         if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
803             print(LOG $bpc->timeStamp,
804                        "Removing $TopDir/log/LOG.$lastLog.z\n");
805             unlink("$TopDir/log/LOG.$lastLog.z");
806         }
807         print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
808                    . "LOG.1 -> ... -> LOG.$lastLog\n");
809         close(STDERR);          # dup of LOG
810         close(STDOUT);          # dup of LOG
811         close(LOG);
812         for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
813             my $j = $i + 1;
814             rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
815                             if ( -f "$TopDir/log/LOG.$i" );
816             rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
817                             if ( -f "$TopDir/log/LOG.$i.z" );
818         }
819         #
820         # Compress the log file LOG -> LOG.0.z (if enabled).
821         # Otherwise, just rename LOG -> LOG.0.
822         #
823         BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
824                                         "$TopDir/log/LOG.0.z",
825                                         "$TopDir/log/LOG.0",
826                                         $Conf{CompressLevel}, 1);
827         LogFileOpen();
828         #
829         # Remember to run nightly script after current jobs are done
830         #
831         $RunNightlyWhenIdle = 1;
832     }
833     #
834     # Write out the current status and then queue all the PCs
835     #
836     HostsUpdate(0);
837     StatusWrite();
838     %BgQueueOn = ()   if ( @BgQueue == 0 );
839     %UserQueueOn = () if ( @UserQueue == 0 );
840     %CmdQueueOn = ()  if ( @CmdQueue == 0 );
841     QueueAllPCs();
842 }
843
844 ############################################################################
845 # Main_Check_Job_Messages($fdRead)
846 #
847 # Check if select() says we have bytes waiting from any of our jobs.
848 # Handle each of the messages when complete (newline terminated).
849 ############################################################################
850 sub Main_Check_Job_Messages
851 {
852     my($fdRead) = @_;
853     foreach my $host ( keys(%Jobs) ) {
854         next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
855         my $mesg;
856         #
857         # do a last check to make sure there is something to read so
858         # we are absolutely sure we won't block.
859         #
860         vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
861         if ( !select($readMask, undef, undef, 0.0) ) {
862             print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
863                         . " nothing to read from $host.  Debug dump:\n");
864             my($dump) = Data::Dumper->new(
865                          [  \%Clients, \%Jobs, \$FDread, \$fdRead],
866                          [qw(*Clients,  *Jobs   *FDread,  *fdRead)]);
867             $dump->Indent(1);
868             print(LOG $dump->Dump);
869             next;
870         }
871         my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
872         $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
873         #
874         # Process any complete lines of output from this jobs.
875         # Any output to STDOUT or STDERR from the children is processed here.
876         #
877         while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
878             $mesg = $1;
879             $Jobs{$host}{mesg} = $2;
880             if ( $Jobs{$host}{dhcp} ) {
881                 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
882                     my $newHost = $bpc->uriUnesc($2);
883                     if ( defined($Jobs{$newHost}) ) {
884                         print(LOG $bpc->timeStamp,
885                                 "Backup on $newHost is already running\n");
886                         kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
887                         $nbytes = 0;
888                         last;
889                     }
890                     $Jobs{$host}{dhcpHostIP} = $host;
891                     $Status{$newHost}{dhcpHostIP} = $host;
892                     $Jobs{$newHost} = $Jobs{$host};
893                     delete($Jobs{$host});
894                     $host = $newHost;
895                     $Status{$host}{state}      = "Status_backup_starting";
896                     $Status{$host}{activeJob}  = 1;
897                     $Status{$host}{startTime}  = $Jobs{$host}{startTime};
898                     $Status{$host}{endTime}    = "";
899                     $Jobs{$host}{dhcp}         = 0;
900                 } else {
901                     print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
902                 }
903             } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
904                 $Jobs{$host}{type}      = $1;
905                 $Jobs{$host}{shareName} = $2;
906                 print(LOG $bpc->timeStamp,
907                           "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
908                           $Jobs{$host}{dhcpHostIP}
909                                 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
910                           ", share=$Jobs{$host}{shareName})\n");
911                 $Status{$host}{state}     = "Status_backup_in_progress";
912                 $Status{$host}{reason}    = "";
913                 $Status{$host}{type}      = $1;
914                 $Status{$host}{startTime} = time;
915                 $Status{$host}{deadCnt}   = 0;
916                 $Status{$host}{aliveCnt}++;
917                 $Status{$host}{dhcpCheckCnt}--
918                                 if ( $Status{$host}{dhcpCheckCnt} > 0 );
919             } elsif ( $mesg =~ /^xferPids (.*)/ ) {
920                 $Jobs{$host}{xferPid} = $1;
921             } elsif ( $mesg =~ /^started_restore/ ) {
922                 $Jobs{$host}{type}    = "restore";
923                 print(LOG $bpc->timeStamp,
924                           "Started restore on $host"
925                           . " (pid=$Jobs{$host}{pid})\n");
926                 $Status{$host}{state}     = "Status_restore_in_progress";
927                 $Status{$host}{reason}    = "";
928                 $Status{$host}{type}      = "restore";
929                 $Status{$host}{startTime} = time;
930                 $Status{$host}{deadCnt}   = 0;
931                 $Status{$host}{aliveCnt}++;
932             } elsif ( $mesg =~ /^started_archive/ ) {
933                 $Jobs{$host}{type}    = "archive";
934                 print(LOG $bpc->timeStamp,
935                           "Started archive on $host"
936                           . " (pid=$Jobs{$host}{pid})\n");
937                 $Status{$host}{state}     = "Status_archive_in_progress";
938                 $Status{$host}{reason}    = "";
939                 $Status{$host}{type}      = "archive";
940                 $Status{$host}{startTime} = time;
941                 $Status{$host}{deadCnt}   = 0;
942                 $Status{$host}{aliveCnt}++;
943             } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
944                 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
945                 $Status{$host}{reason}    = "Reason_backup_done";
946                 delete($Status{$host}{error});
947                 delete($Status{$host}{errorTime});
948                 $Status{$host}{endTime}   = time;
949                 $Status{$host}{lastGoodBackupTime} = time;
950             } elsif ( $mesg =~ /^backups disabled/ ) {
951                 print(LOG $bpc->timeStamp,
952                             "Ignoring old backup error on $host\n");
953                 $Status{$host}{reason}    = "Reason_backup_done";
954                 delete($Status{$host}{error});
955                 delete($Status{$host}{errorTime});
956                 $Status{$host}{endTime}   = time;
957             } elsif ( $mesg =~ /^restore complete/ ) {
958                 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
959                 $Status{$host}{reason}    = "Reason_restore_done";
960                 delete($Status{$host}{error});
961                 delete($Status{$host}{errorTime});
962                 $Status{$host}{endTime}   = time;
963             } elsif ( $mesg =~ /^archive complete/ ) {
964                 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
965                 $Status{$host}{reason}    = "Reason_archive_done";
966                 delete($Status{$host}{error});
967                 delete($Status{$host}{errorTime});
968                 $Status{$host}{endTime}   = time;
969             } elsif ( $mesg =~ /^nothing to do/ ) {
970                 if ( $Status{$host}{reason} ne "Reason_backup_failed"
971                         && $Status{$host}{reason} ne "Reason_restore_failed" ) {
972                     $Status{$host}{state}     = "Status_idle";
973                     $Status{$host}{reason}    = "Reason_nothing_to_do";
974                     $Status{$host}{startTime} = time;
975                 }
976                 $Status{$host}{dhcpCheckCnt}--
977                                 if ( $Status{$host}{dhcpCheckCnt} > 0 );
978             } elsif ( $mesg =~ /^no ping response/
979                             || $mesg =~ /^ping too slow/
980                             || $mesg =~ /^host not found/ ) {
981                 $Status{$host}{state}     = "Status_idle";
982                 if ( $Status{$host}{userReq}
983                         || $Status{$host}{reason} ne "Reason_backup_failed"
984                         || $Status{$host}{error} =~ /^aborted by user/ ) {
985                     $Status{$host}{reason}    = "Reason_no_ping";
986                     $Status{$host}{error}     = $mesg;
987                     $Status{$host}{startTime} = time;
988                 }
989                 $Status{$host}{deadCnt}++;
990                 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
991                     $Status{$host}{aliveCnt} = 0;
992                 }
993             } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
994                 $Status{$host}{state}     = "Status_idle";
995                 $Status{$host}{error}     = $1;
996                 $Status{$host}{errorTime} = time;
997                 $Status{$host}{endTime}   = time;
998                 if ( $Status{$host}{reason}
999                         eq "Reason_backup_canceled_by_user" ) {
1000                     print(LOG $bpc->timeStamp,
1001                             "Backup canceled on $host ($1)\n");
1002                 } else {
1003                     $Status{$host}{reason} = "Reason_backup_failed";
1004                     print(LOG $bpc->timeStamp,
1005                             "Backup failed on $host ($1)\n");
1006                 }
1007             } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1008                 $Status{$host}{state}     = "Status_idle";
1009                 $Status{$host}{error}     = $1;
1010                 $Status{$host}{errorTime} = time;
1011                 $Status{$host}{endTime}   = time;
1012                 if ( $Status{$host}{reason}
1013                          eq "Reason_restore_canceled_by_user" ) {
1014                     print(LOG $bpc->timeStamp,
1015                             "Restore canceled on $host ($1)\n");
1016                 } else {
1017                     $Status{$host}{reason} = "Reason_restore_failed";
1018                     print(LOG $bpc->timeStamp,
1019                             "Restore failed on $host ($1)\n");
1020                 }
1021             } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1022                 $Status{$host}{state}     = "Status_idle";
1023                 $Status{$host}{error}     = $1;
1024                 $Status{$host}{errorTime} = time;
1025                 $Status{$host}{endTime}   = time;
1026                 if ( $Status{$host}{reason}
1027                          eq "Reason_archive_canceled_by_user" ) {
1028                     print(LOG $bpc->timeStamp,
1029                             "Archive canceled on $host ($1)\n");
1030                 } else {
1031                     $Status{$host}{reason} = "Reason_archive_failed";
1032                     print(LOG $bpc->timeStamp,
1033                             "Archive failed on $host ($1)\n");
1034                 }
1035             } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1036                 print(LOG $bpc->timeStamp, "$1\n");
1037             } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1038                 my $chunk = int($1 / 16);
1039                 my @f = split(/,/, $2);
1040                 $Info{pool}{$f[0]}[$chunk]{FileCnt}       += $f[1];
1041                 $Info{pool}{$f[0]}[$chunk]{DirCnt}        += $f[2];
1042                 $Info{pool}{$f[0]}[$chunk]{Kb}            += $f[3];
1043                 $Info{pool}{$f[0]}[$chunk]{Kb2}           += $f[4];
1044                 $Info{pool}{$f[0]}[$chunk]{KbRm}          += $f[5];
1045                 $Info{pool}{$f[0]}[$chunk]{FileCntRm}     += $f[6];
1046                 $Info{pool}{$f[0]}[$chunk]{FileCntRep}    += $f[7];
1047                 $Info{pool}{$f[0]}[$chunk]{FileRepMax}     = $f[8]
1048                         if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1049                 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1050                 $Info{pool}{$f[0]}[$chunk]{FileLinkMax}    = $f[10]
1051                         if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1052                 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1053                 $Info{pool}{$f[0]}[$chunk]{Time}           = time;
1054             } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1055                 $BackupPCNightlyLock--;
1056                 if ( $BackupPCNightlyLock == 0 ) {
1057                     #
1058                     # This means the last BackupPC_nightly is done with
1059                     # the pool clean, so it's ok to start running regular
1060                     # backups again.
1061                     #
1062                     $RunNightlyWhenIdle = 0;
1063                 }
1064             } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1065                 $Jobs{$host}{processState} = $1;
1066             } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1067                 my($h) = $1;
1068                 $Status{$h}{needLink} = 1;
1069             } else {
1070                 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1071             }
1072         }
1073         #
1074         # shut down the client connection if we read EOF
1075         #
1076         if ( $nbytes <= 0 ) {
1077             close($Jobs{$host}{fh});
1078             vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1079             if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1080                 my $cmd = $Jobs{$host}{cmd};
1081                 $cmd =~ s/$BinDir\///g;
1082                 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1083                 $Status{$host}{state}    = "Status_idle";
1084                 $Status{$host}{endTime}  = time;
1085                 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1086                     $BackupPCNightlyJobs--;
1087                     #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1088                     #         . " have $BackupPCNightlyJobs running\n");
1089                     if ( $BackupPCNightlyJobs <= 0 ) {
1090                         $BackupPCNightlyJobs = 0;
1091                         $RunNightlyWhenIdle = 0;
1092                         $CmdJob = "";
1093                         #
1094                         # Combine the 16 per-directory results
1095                         #
1096                         for my $p ( qw(pool cpool) ) {
1097                             $Info{"${p}FileCnt"}       = 0;
1098                             $Info{"${p}DirCnt"}        = 0;
1099                             $Info{"${p}Kb"}            = 0;
1100                             $Info{"${p}Kb2"}           = 0;
1101                             $Info{"${p}KbRm"}          = 0;
1102                             $Info{"${p}FileCntRm"}     = 0;
1103                             $Info{"${p}FileCntRep"}    = 0;
1104                             $Info{"${p}FileRepMax"}    = 0;
1105                             $Info{"${p}FileCntRename"} = 0;
1106                             $Info{"${p}FileLinkMax"}   = 0;
1107                             $Info{"${p}Time"}          = 0;
1108                             for ( my $i = 0 ; $i < 16 ; $i++ ) {
1109                                 $Info{"${p}FileCnt"}
1110                                        += $Info{pool}{$p}[$i]{FileCnt};
1111                                 $Info{"${p}DirCnt"}
1112                                        += $Info{pool}{$p}[$i]{DirCnt};
1113                                 $Info{"${p}Kb"}
1114                                        += $Info{pool}{$p}[$i]{Kb};
1115                                 $Info{"${p}Kb2"}
1116                                        += $Info{pool}{$p}[$i]{Kb2};
1117                                 $Info{"${p}KbRm"}
1118                                        += $Info{pool}{$p}[$i]{KbRm};
1119                                 $Info{"${p}FileCntRm"}
1120                                        += $Info{pool}{$p}[$i]{FileCntRm};
1121                                 $Info{"${p}FileCntRep"}
1122                                        += $Info{pool}{$p}[$i]{FileCntRep};
1123                                 $Info{"${p}FileRepMax"}
1124                                         = $Info{pool}{$p}[$i]{FileRepMax}
1125                                           if ( $Info{"${p}FileRepMax"} <
1126                                               $Info{pool}{$p}[$i]{FileRepMax} );
1127                                 $Info{"${p}FileCntRename"}
1128                                        += $Info{pool}{$p}[$i]{FileCntRename};
1129                                 $Info{"${p}FileLinkMax"}
1130                                         = $Info{pool}{$p}[$i]{FileLinkMax}
1131                                           if ( $Info{"${p}FileLinkMax"} <
1132                                              $Info{pool}{$p}[$i]{FileLinkMax} );
1133                                 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1134                                           if ( $Info{"${p}Time"} <
1135                                                  $Info{pool}{$p}[$i]{Time} );
1136                             }
1137                             printf(LOG "%s%s nightly clean removed %d files of"
1138                                    . " size %.2fGB\n",
1139                                      $bpc->timeStamp, ucfirst($p),
1140                                      $Info{"${p}FileCntRm"},
1141                                      $Info{"${p}KbRm"} / (1000 * 1024));
1142                             printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1143                                    . "%d max chain, %d max links), %d directories\n",
1144                                      $bpc->timeStamp, ucfirst($p),
1145                                      $Info{"${p}Kb"} / (1000 * 1024),
1146                                      $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1147                                      $Info{"${p}FileRepMax"},
1148                                      $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1149                         }
1150                     }
1151                 } else {
1152                     $CmdJob = "";
1153                 }
1154             } else {
1155                 #
1156                 # Queue BackupPC_link to complete the backup
1157                 # processing for this host.
1158                 #
1159                 if ( defined($Status{$host})
1160                             && ($Status{$host}{reason} eq "Reason_backup_done"
1161                                 || $Status{$host}{needLink}) ) {
1162                     QueueLink($host);
1163                 } elsif ( defined($Status{$host}) ) {
1164                     $Status{$host}{state} = "Status_idle";
1165                 }
1166             }
1167             delete($Jobs{$host});
1168             $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1169         }
1170     }
1171     #
1172     # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1173     # do a pass over %Status updating the deadCnt and aliveCnt for
1174     # DHCP hosts.  The reason we need to do this later is we can't
1175     # be sure whether a DHCP host is alive or dead until we have passed
1176     # over all the DHCP pool.
1177     #
1178     return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1179     foreach my $host ( keys(%Status) ) {
1180         next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1181         $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1182         $Status{$host}{dhcpCheckCnt} = 0;
1183         if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1184             $Status{$host}{aliveCnt} = 0;
1185         }
1186     }
1187 }
1188
1189 ############################################################################
1190 # Main_Check_Client_Messages($fdRead)
1191 #
1192 # Check for, and process, any output from our clients.  Also checks
1193 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1194 ############################################################################
1195 sub Main_Check_Client_Messages
1196 {
1197     my($fdRead) = @_;
1198     foreach my $client ( keys(%Clients) ) {
1199         next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1200         my($mesg, $host);
1201         #
1202         # do a last check to make sure there is something to read so
1203         # we are absolutely sure we won't block.
1204         #
1205         vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1206         if ( !select($readMask, undef, undef, 0.0) ) {
1207             print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1208                         . " nothing to read from $client.  Debug dump:\n");
1209             my($dump) = Data::Dumper->new(
1210                          [  \%Clients, \%Jobs, \$FDread, \$fdRead],
1211                          [qw(*Clients,  *Jobs   *FDread,  *fdRead)]);
1212             $dump->Indent(1);
1213             print(LOG $dump->Dump);
1214             next;
1215         }
1216         my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1217         $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1218         #
1219         # Process any complete lines received from this client.
1220         #
1221         while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1222             my($reply);
1223             my $cmd = $1;
1224             $Clients{$client}{mesg} = $2;
1225             #
1226             # Authenticate the message by checking the MD5 digest
1227             #
1228             my $md5 = Digest::MD5->new;
1229             if ( $cmd !~ /^(.{22}) (.*)/
1230                 || ($md5->add($Clients{$client}{seed}
1231                             . $Clients{$client}{mesgCnt}
1232                             . $Conf{ServerMesgSecret} . $2),
1233                      $md5->b64digest ne $1) ) {
1234                 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1235                             . " client '$Clients{$client}{clientName}':"
1236                             . " shutting down client connection\n");
1237                 $nbytes = 0;
1238                 last;
1239             }
1240             $Clients{$client}{mesgCnt}++;
1241             $cmd = $2;
1242             if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1243                 $host = $1;
1244                 my $user = $2;
1245                 my $backoff = $3;
1246                 $host = $bpc->uriUnesc($host);
1247                 if ( $CmdJob ne $host && defined($Status{$host})
1248                                       && defined($Jobs{$host}) ) {
1249                     print(LOG $bpc->timeStamp,
1250                                "Stopping current $Jobs{$host}{type} of $host,"
1251                              . " request by $user (backoff=$backoff)\n");
1252                     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1253                     #
1254                     # Don't close the pipe now; wait until the child
1255                     # really exits later.  Otherwise close() will
1256                     # block until the child has exited.
1257                     #  old code:
1258                     ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1259                     ##close($Jobs{$host}{fh});
1260                     ##delete($Jobs{$host});
1261
1262                     $Status{$host}{state}    = "Status_idle";
1263                     if ( $Jobs{$host}{type} eq "restore" ) {
1264                         $Status{$host}{reason}
1265                                     = "Reason_restore_canceled_by_user";
1266                     } elsif ( $Jobs{$host}{type} eq "archive" ) {
1267                         $Status{$host}{reason}
1268                                     = "Reason_archive_canceled_by_user";
1269                     } else {
1270                         $Status{$host}{reason}
1271                                     = "Reason_backup_canceled_by_user";
1272                     }
1273                     $Status{$host}{activeJob} = 0;
1274                     $Status{$host}{startTime} = time;
1275                     $reply = "ok: $Jobs{$host}{type} of $host canceled";
1276                 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1277                     print(LOG $bpc->timeStamp,
1278                                "Stopping pending backup of $host,"
1279                              . " request by $user (backoff=$backoff)\n");
1280                     @BgQueue = grep($_->{host} ne $host, @BgQueue);
1281                     @UserQueue = grep($_->{host} ne $host, @UserQueue);
1282                     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1283                     $reply = "ok: pending backup of $host canceled";
1284                 } else {
1285                     print(LOG $bpc->timeStamp,
1286                                "Nothing to do for stop backup of $host,"
1287                              . " request by $user (backoff=$backoff)\n");
1288                     $reply = "ok: no backup was pending or running";
1289                 }
1290                 if ( defined($Status{$host}) && $backoff ne "" ) {
1291                     if ( $backoff > 0 ) {
1292                         $Status{$host}{backoffTime} = time + $backoff * 3600;
1293                     } else {
1294                         delete($Status{$host}{backoffTime});
1295                     }
1296                 }
1297             } elsif ( $cmd =~ /^backup all$/ ) {
1298                 QueueAllPCs();
1299             } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1300                 $RunNightlyWhenIdle = 1;
1301             } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1302                 my $hostIP = $1;
1303                 $host      = $2;
1304                 my $user   = $3;
1305                 my $doFull = $4;
1306                 $host      = $bpc->uriUnesc($host);
1307                 $hostIP    = $bpc->uriUnesc($hostIP);
1308                 if ( !defined($Status{$host}) ) {
1309                     print(LOG $bpc->timeStamp,
1310                                "User $user requested backup of unknown host"
1311                              . " $host\n");
1312                     $reply = "error: unknown host $host";
1313                 } else {
1314                     print(LOG $bpc->timeStamp,
1315                                "User $user requested backup of $host"
1316                              . " ($hostIP)\n");
1317                     if ( $BgQueueOn{$hostIP} ) {
1318                         @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1319                         $BgQueueOn{$hostIP} = 0;
1320                     }
1321                     if ( $UserQueueOn{$hostIP} ) {
1322                         @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1323                         $UserQueueOn{$hostIP} = 0;
1324                     }
1325                     unshift(@UserQueue, {
1326                                 host    => $hostIP,
1327                                 user    => $user,
1328                                 reqTime => time,
1329                                 doFull  => $doFull,
1330                                 userReq => 1,
1331                                 dhcp    => $hostIP eq $host ? 0 : 1,
1332                         });
1333                     $UserQueueOn{$hostIP} = 1;
1334                     $reply = "ok: requested backup of $host";
1335                 }
1336             } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1337                 my $user         = $1;
1338                 my $archivehost  = $2;
1339                 my $reqFileName  = $3;
1340                 $host      = $bpc->uriUnesc($archivehost);
1341                 if ( !defined($Status{$host}) ) {
1342                     print(LOG $bpc->timeStamp,
1343                                "User $user requested archive of unknown archive host"
1344                              . " $host");
1345                     $reply = "archive error: unknown archive host $host";
1346                 } else {
1347                     print(LOG $bpc->timeStamp,
1348                                "User $user requested archive on $host"
1349                              . " ($host)\n");
1350                     if ( defined($Jobs{$host}) ) {
1351                         $reply = "Archive currently running on $host, please try later";
1352                     } else {
1353                         unshift(@UserQueue, {
1354                                 host    => $host,
1355                                 hostIP  => $user,
1356                                 reqFileName => $reqFileName,
1357                                 reqTime => time,
1358                                 dhcp    => 0,
1359                                 archive => 1,
1360                                 userReq => 1,
1361                         });
1362                         $UserQueueOn{$host} = 1;
1363                         $reply = "ok: requested archive on $host";
1364                     }
1365                 }
1366             } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1367                 my $hostIP = $1;
1368                 $host      = $2;
1369                 my $user   = $3;
1370                 my $reqFileName = $4;
1371                 $host      = $bpc->uriUnesc($host);
1372                 $hostIP    = $bpc->uriUnesc($hostIP);
1373                 if ( !defined($Status{$host}) ) {
1374                     print(LOG $bpc->timeStamp,
1375                                "User $user requested restore to unknown host"
1376                              . " $host");
1377                     $reply = "restore error: unknown host $host";
1378                 } else {
1379                     print(LOG $bpc->timeStamp,
1380                                "User $user requested restore to $host"
1381                              . " ($hostIP)\n");
1382                     unshift(@UserQueue, {
1383                                 host    => $host,
1384                                 hostIP  => $hostIP,
1385                                 reqFileName => $reqFileName,
1386                                 reqTime => time,
1387                                 dhcp    => 0,
1388                                 restore => 1,
1389                                 userReq => 1,
1390                         });
1391                     $UserQueueOn{$host} = 1;
1392                     if ( defined($Jobs{$host}) ) {
1393                         $reply = "ok: requested restore of $host, but a"
1394                                . " job is currently running,"
1395                                . " so this request will start later";
1396                     } else {
1397                         $reply = "ok: requested restore of $host";
1398                     }
1399                 }
1400             } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1401                 my($args) = $1;
1402                 my($dump, @values, @names);
1403                 foreach my $type ( split(/\s+/, $args) ) {
1404                     if ( $type =~ /^queues/ ) {
1405                         push(@values,  \@BgQueue, \@UserQueue, \@CmdQueue);
1406                         push(@names, qw(*BgQueue   *UserQueue   *CmdQueue));
1407                     } elsif ( $type =~ /^jobs/ ) {
1408                         push(@values,  \%Jobs);
1409                         push(@names, qw(*Jobs));
1410                     } elsif ( $type =~ /^queueLen/ ) {
1411                         push(@values,  {
1412                                 BgQueue   => scalar(@BgQueue),
1413                                 UserQueue => scalar(@UserQueue),
1414                                 CmdQueue  => scalar(@CmdQueue),
1415                             });
1416                         push(@names, qw(*QueueLen));
1417                     } elsif ( $type =~ /^info/ ) {
1418                         push(@values,  \%Info);
1419                         push(@names, qw(*Info));
1420                     } elsif ( $type =~ /^hosts/ ) {
1421                         push(@values,  \%Status);
1422                         push(@names, qw(*Status));
1423                     } elsif ( $type =~ /^host\((.*)\)/ ) {
1424                         my $h = $bpc->uriUnesc($1);
1425                         if ( defined($Status{$h}) ) {
1426                             push(@values,  {
1427                                     %{$Status{$h}},
1428                                     BgQueueOn => $BgQueueOn{$h},
1429                                     UserQueueOn => $UserQueueOn{$h},
1430                                     CmdQueueOn => $CmdQueueOn{$h},
1431                                 });
1432                             push(@names, qw(*StatusHost));
1433                         } else {
1434                             print(LOG $bpc->timeStamp,
1435                                       "Unknown host $h for status request\n");
1436                         }
1437                     } else {
1438                         print(LOG $bpc->timeStamp,
1439                                   "Unknown status request $type\n");
1440                     }
1441                 }
1442                 $dump = Data::Dumper->new(\@values, \@names);
1443                 $dump->Indent(0);
1444                 $reply = $dump->Dump;
1445             } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1446                 my($host) = $1;
1447                 $host = $bpc->uriUnesc($host);
1448                 QueueLink($host);
1449             } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1450                 print(LOG $bpc->timeStamp, "$1\n");
1451             } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1452                 my($type) = $1;
1453                 if ( $type eq 'reload' ) {
1454                     ServerReload("Reloading config/host files via CGI request");
1455                 } elsif ( $type eq 'shutdown' ) {
1456                     $reply = "Shutting down...\n";
1457                     syswrite($Clients{$client}{fh}, $reply, length($reply));
1458                     ServerShutdown("Server shutting down...");
1459                 }
1460             } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1461                 $nbytes = 0;
1462                 last;
1463             } else {
1464                 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1465                 $reply = "error: bad command $cmd";
1466             }
1467             #
1468             # send a reply to the client, at a minimum "ok\n".
1469             #
1470             $reply = "ok" if ( $reply eq "" );
1471             $reply .= "\n";
1472             syswrite($Clients{$client}{fh}, $reply, length($reply));
1473         }
1474         #
1475         # Detect possible denial-of-service attack from sending a huge line
1476         # (ie: never terminated).  32K seems to be plenty big enough as
1477         # a limit.
1478         #
1479         if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1480             print(LOG $bpc->timeStamp, "Line too long from client"
1481                         . " '$Clients{$client}{clientName}':"
1482                         . " shutting down client connection\n");
1483             $nbytes = 0;
1484         }
1485         #
1486         # Shut down the client connection if we read EOF
1487         #
1488         if ( $nbytes <= 0 ) {
1489             close($Clients{$client}{fh});
1490             vec($FDread, $Clients{$client}{fn}, 1) = 0;
1491             delete($Clients{$client});
1492         }
1493     }
1494     #
1495     # Accept any new connections on each of our listen sockets
1496     #
1497     if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1498         local(*CLIENT);
1499         my $paddr = accept(CLIENT, SERVER_UNIX);
1500         $ClientConnCnt++;
1501         $Clients{$ClientConnCnt}{clientName} = "unix socket";
1502         $Clients{$ClientConnCnt}{mesg} = "";
1503         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1504         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
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,$$,0\n";
1511         $Clients{$ClientConnCnt}{seed}    = $seed;
1512         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1513         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1514     }
1515     if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1516         local(*CLIENT);
1517         my $paddr = accept(CLIENT, SERVER_INET);
1518         my($port,$iaddr) = sockaddr_in($paddr); 
1519         my $name = gethostbyaddr($iaddr, AF_INET);
1520         $ClientConnCnt++;
1521         $Clients{$ClientConnCnt}{mesg} = "";
1522         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1523         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
1524         $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1525         vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1526         #
1527         # Generate and send unique seed for MD5 digests to avoid
1528         # replay attacks.  See BackupPC::Lib::ServerMesg().
1529         #
1530         my $seed = time . ",$ClientConnCnt,$$,$port\n";
1531         $Clients{$ClientConnCnt}{seed}    = $seed;
1532         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1533         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1534     }
1535 }
1536
1537 ###########################################################################
1538 # Miscellaneous subroutines
1539 ###########################################################################
1540
1541 #
1542 # Write the current status to $TopDir/log/status.pl
1543 #
1544 sub StatusWrite
1545 {
1546     my($dump) = Data::Dumper->new(
1547              [  \%Info, \%Status],
1548              [qw(*Info   *Status)]);
1549     $dump->Indent(1);
1550     if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1551         print(STATUS $dump->Dump);
1552         close(STATUS);
1553     }
1554 }
1555
1556 #
1557 # Compare function for host sort.  Hosts with errors go first,
1558 # sorted with the oldest errors first.  The remaining hosts
1559 # are sorted so that those with the oldest backups go first.
1560 #
1561 sub HostSortCompare
1562 {
1563     #
1564     # Hosts with errors go before hosts without errors
1565     #
1566     return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1567
1568     #
1569     # Hosts with no errors go after hosts with errors
1570     #
1571
1572     return  1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1573
1574     #
1575     # hosts with the older last good backups sort earlier
1576     #
1577     my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1578     return $r if ( $r );
1579
1580     #
1581     # Finally, just sort based on host name
1582     #
1583     return $a cmp $b;
1584 }
1585
1586 #
1587 # Queue all the hosts for backup.  This means queuing all the fixed
1588 # ip hosts and all the dhcp address ranges.  We also additionally
1589 # queue the dhcp hosts with a -e flag to check for expired dumps.
1590 #
1591 sub QueueAllPCs
1592 {
1593     my $nSkip = 0;
1594     foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1595         delete($Status{$host}{backoffTime})
1596                 if ( defined($Status{$host}{backoffTime})
1597                   && $Status{$host}{backoffTime} < time );
1598         next if ( defined($Jobs{$host})
1599                 || $BgQueueOn{$host}
1600                 || $UserQueueOn{$host}
1601                 || $CmdQueueOn{$host} ); 
1602         if ( $Hosts->{$host}{dhcp} ) {
1603             $Status{$host}{dhcpCheckCnt}++;
1604             if ( $RunNightlyWhenIdle ) {
1605                 #
1606                 # Once per night queue a check for DHCP hosts that just
1607                 # checks for expired dumps.  We need to do this to handle
1608                 # the case when a DHCP host has not been on the network for
1609                 # a long time, and some of the old dumps need to be expired.
1610                 # Normally expiry checks are done by BackupPC_dump only
1611                 # after the DHCP hosts has been detected on the network.
1612                 #
1613                 unshift(@BgQueue,
1614                     {host => $host, user => "BackupPC", reqTime => time,
1615                      dhcp => 0, dumpExpire => 1});
1616                 $BgQueueOn{$host} = 1;
1617             }
1618         } else {
1619             #
1620             # this is a fixed ip host: queue it
1621             #
1622             if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1623                 #
1624                 # Since we are out of disk space, instead of queuing
1625                 # a regular job, queue an expire check instead.  That
1626                 # way if the admin reduces the number of backups to
1627                 # keep then we will actually delete them.  Otherwise
1628                 # BackupPC_dump will never run since we have exceeded
1629                 # the limit.
1630                 #
1631                 $nSkip++;
1632                 unshift(@BgQueue,
1633                     {host => $host, user => "BackupPC", reqTime => time,
1634                      dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1635             } else {
1636                 #
1637                 # Queue regular background backup
1638                 #
1639                 unshift(@BgQueue,
1640                     {host => $host, user => "BackupPC", reqTime => time,
1641                      dhcp => $Hosts->{$host}{dhcp}});
1642             }
1643             $BgQueueOn{$host} = 1;
1644         }
1645     }
1646     if ( $nSkip ) {
1647         print(LOG $bpc->timeStamp,
1648                "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1649         $Info{DUDailySkipHostCnt} += $nSkip;
1650     }
1651     foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1652         for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1653             my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1654             next if ( defined($Jobs{$ipAddr})
1655                     || $BgQueueOn{$ipAddr}
1656                     || $UserQueueOn{$ipAddr}
1657                     || $CmdQueueOn{$ipAddr} ); 
1658             #
1659             # this is a potential dhcp ip address (we don't know the
1660             # host name yet): queue it
1661             #
1662             unshift(@BgQueue,
1663                 {host => $ipAddr, user => "BackupPC", reqTime => time,
1664                  dhcp => 1});
1665             $BgQueueOn{$ipAddr} = 1;
1666         }
1667     }
1668 }
1669
1670 #
1671 # Queue a BackupPC_link for the given host
1672 #
1673 sub QueueLink
1674 {
1675     my($host) = @_;
1676
1677     return if ( $CmdQueueOn{$host} );
1678     $Status{$host}{state}    = "Status_link_pending";
1679     $Status{$host}{needLink} = 0;
1680     unshift(@CmdQueue, {
1681             host    => $host,
1682             user    => "BackupPC",
1683             reqTime => time,
1684             cmd     => ["$BinDir/BackupPC_link",  $host],
1685         });
1686     $CmdQueueOn{$host} = 1;
1687 }
1688
1689 #
1690 # Read the hosts file, and update Status if any hosts have been
1691 # added or deleted.  We also track the mtime so the only need to
1692 # update the hosts file on changes.
1693 #
1694 # This function is called at startup, SIGHUP, and on each wakeup.
1695 # It returns 1 on success and undef on failure.
1696 #
1697 sub HostsUpdate
1698 {
1699     my($force) = @_;
1700     my $newHosts;
1701     #
1702     # Nothing to do if we already have the current hosts file
1703     #
1704     return 1 if ( !$force && defined($Hosts)
1705                           && $Info{HostsModTime} == $bpc->HostsMTime() );
1706     if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1707         print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1708         return;
1709     }
1710     print(LOG $bpc->timeStamp, "Reading hosts file\n");
1711     $Hosts = $newHosts;
1712     $Info{HostsModTime} = $bpc->HostsMTime();
1713     #
1714     # Now update %Status in case any hosts have been added or deleted
1715     #
1716     foreach my $host ( sort(keys(%$Hosts)) ) {
1717         next if ( defined($Status{$host}) );
1718         $Status{$host}{state} = "Status_idle";
1719         print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1720     }
1721     foreach my $host ( sort(keys(%Status)) ) {
1722         next if ( $host eq $bpc->trashJob
1723                      || $bpc->isAdminJob($host)
1724                      || defined($Hosts->{$host})
1725                      || defined($Jobs{$host})
1726                      || $BgQueueOn{$host}
1727                      || $UserQueueOn{$host}
1728                      || $CmdQueueOn{$host} );
1729         print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1730         delete($Status{$host});
1731     }
1732     return 1;
1733 }
1734
1735 #
1736 # Remember the signal name for later processing
1737 #
1738 sub catch_signal
1739 {
1740     if ( $SigName ) {
1741         $SigName = shift;
1742         foreach my $host ( keys(%Jobs) ) {
1743             kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1744         }
1745         #
1746         # In case we are inside the exit handler, reopen the log file
1747         #
1748         close(LOG);
1749         LogFileOpen();
1750         print(LOG "Fatal error: unhandled signal $SigName\n");
1751         unlink("$TopDir/log/BackupPC.pid");
1752         confess("Got new signal $SigName... quitting\n");
1753     } else {
1754         $SigName = shift;
1755     }
1756 }
1757
1758 #
1759 # Open the log file and point STDOUT and STDERR there too
1760 #
1761 sub LogFileOpen
1762 {
1763     mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1764     open(LOG, ">>$TopDir/log/LOG")
1765             || die("Can't create LOG file $TopDir/log/LOG");
1766     close(STDOUT);
1767     close(STDERR);
1768     open(STDOUT, ">&LOG");
1769     open(STDERR, ">&LOG");
1770     select(LOG);    $| = 1;
1771     select(STDERR); $| = 1;
1772     select(STDOUT); $| = 1;
1773 }
1774
1775 #
1776 # Initialize the unix-domain and internet-domain sockets that
1777 # we listen to for client connections (from the CGI script and
1778 # some of the BackupPC sub-programs).
1779 #
1780 sub ServerSocketInit
1781 {
1782     if ( !defined(fileno(SERVER_UNIX)) ) {
1783         #
1784         # one-time only: initialize unix-domain socket
1785         #
1786         if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1787             print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1788             exit(1);
1789         }
1790         my $sockFile = "$TopDir/log/BackupPC.sock";
1791         unlink($sockFile);
1792         if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1793             print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1794             exit(1);
1795         }
1796         if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1797             print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1798             exit(1);
1799         }
1800         vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1801     }
1802     return if ( $ServerInetPort == $Conf{ServerPort} );
1803     if ( $ServerInetPort > 0 ) {
1804         vec($FDread, fileno(SERVER_INET), 1) = 0;
1805         close(SERVER_INET);
1806         $ServerInetPort = -1;
1807     }
1808     if ( $Conf{ServerPort} > 0 ) {
1809         #
1810         # Setup a socket to listen on $Conf{ServerPort}
1811         #
1812         my $proto = getprotobyname('tcp');
1813         if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1814             print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1815             exit(1);
1816         }
1817         if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1818             print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1819             exit(1);
1820         }
1821         if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1822             print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1823             exit(1);
1824         }
1825         if ( !listen(SERVER_INET, SOMAXCONN) ) {
1826             print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1827             exit(1);
1828         }
1829         vec($FDread, fileno(SERVER_INET), 1) = 1;
1830         $ServerInetPort = $Conf{ServerPort};
1831     }
1832 }
1833
1834 #
1835 # Reload the server.  Used by Main_Process_Signal when $SigName eq "HUP"
1836 # or when the command "server reload" is received.
1837 #
1838 sub ServerReload
1839 {
1840     my($mesg) = @_;
1841     $mesg = $bpc->ConfigRead() || $mesg;
1842     print(LOG $bpc->timeStamp, "$mesg\n");
1843     $Info{ConfigModTime} = $bpc->ConfigMTime();
1844     %Conf = $bpc->Conf();
1845     umask($Conf{UmaskMode});
1846     ServerSocketInit();
1847     HostsUpdate(0);
1848     $NextWakeup = 0;
1849     $Info{ConfigLTime} = time;
1850 }
1851
1852 #
1853 # Gracefully shutdown the server.  Used by Main_Process_Signal when
1854 # $SigName ne "" && $SigName ne "HUP" or when the command
1855 # "server shutdown" is received.
1856 #
1857 sub ServerShutdown
1858 {
1859     my($mesg) = @_;
1860     print(LOG $bpc->timeStamp, "$mesg\n");
1861     if ( keys(%Jobs) ) {
1862         foreach my $host ( keys(%Jobs) ) {
1863             kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1864         }
1865         sleep(1);
1866         foreach my $host ( keys(%Jobs) ) {
1867             kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1868         }
1869         %Jobs = ();
1870     }
1871     delete($Info{pid});
1872     StatusWrite();
1873     unlink("$TopDir/log/BackupPC.pid");
1874     exit(1);
1875 }
1876