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