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