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