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