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