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