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