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