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