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