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