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