e13b60df5bf8e7c6a2dda9ae11ded4234c6bfab4
[BackupPC.git] / bin / BackupPC
1 #!/bin/perl -T
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  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.0.0_CVS, released 18 Jan 2003.
51 #
52 # See http://backuppc.sourceforge.net.
53 #
54 #========================================================================
55
56 use strict;
57 use vars qw(%Status %Info $Hosts);
58 use lib "/usr/local/BackupPC/lib";
59 use BackupPC::Lib;
60 use BackupPC::FileZIO;
61
62 use File::Path;
63 use Data::Dumper;
64 use Getopt::Std;
65 use Socket;
66 use Carp;
67 use Digest::MD5;
68
69 ###########################################################################
70 # Handle command line options
71 ###########################################################################
72 my %opts;
73 getopts("d", \%opts);
74 if ( @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
177 #
178 # Complete the rest of the initialization
179 #
180 Main_Initialize();
181
182 ###########################################################################
183 # Main loop
184 ###########################################################################
185 while ( 1 )
186 {
187     #
188     # Check if we can/should run BackupPC_nightly
189     #
190     Main_TryToRun_nightly();
191
192     #
193     # Check if we can run a new command from @CmdQueue.
194     #
195     Main_TryToRun_CmdQueue();
196
197     #
198     # Check if we can run a new command from @UserQueue or @BgQueue.
199     #
200     Main_TryToRun_Bg_or_User_Queue();
201
202     #
203     # Do a select() to wait for the next interesting thing to happen
204     # (timeout, signal, someone sends a message, child dies etc).
205     #
206     my $fdRead = Main_Select();
207
208     #
209     # Process a signal if we received one.
210     #
211     if ( $SigName ) {
212         Main_Process_Signal();
213         $fdRead = undef;
214     }
215
216     #
217     # Check if a timeout has occurred.
218     #
219     Main_Check_Timeout();
220
221     #
222     # Check for, and process, any messages (output) from our jobs
223     #
224     Main_Check_Job_Messages($fdRead);
225
226     #
227     # Check for, and process, any output from our clients.  Also checks
228     # for new connections to our SERVER_UNIX and SERVER_INET sockets.
229     #
230     Main_Check_Client_Messages($fdRead);
231 }
232
233 ############################################################################
234 # Main_Initialize()
235 #
236 # Main initialization routine.  Called once at statup.
237 ############################################################################
238 sub Main_Initialize
239 {
240     umask($Conf{UmaskMode});
241
242     #
243     # Check for another running process, check that PASSWD is set and
244     # verify executables are configured correctly.
245     #
246     if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
247         print(STDERR $bpc->timeStamp,
248                  "Another BackupPC is running (pid $Info{pid}); quitting...\n");
249         exit(1);
250     }
251     foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
252                               SendmailPath) ) {
253         next if ( !defined($Conf{$progName}) || -x $Conf{$progName} );
254         print(STDERR $bpc->timeStamp,
255                      "\$Conf{$progName} = '$Conf{$progName}' is not a"
256                    . " valid executable program\n");
257         exit(1);
258     }
259
260     if ( $opts{d} ) {
261         #
262         # daemonize by forking
263         #
264         defined(my $pid = fork) or die "Can't fork: $!";
265         exit if $pid;   # parent exits
266     }
267
268     #
269     # Open the LOG file and redirect STDOUT, STDERR etc
270     #
271     LogFileOpen();
272
273     #
274     # Read the hosts file (force a read).
275     #
276     exit(1) if ( !HostsUpdate(1) );
277
278     #
279     # Clean up %ENV for taint checking
280     #
281     delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
282     $ENV{PATH} = $Conf{MyPath};
283
284     #
285     # Initialize server sockets
286     #
287     ServerSocketInit();
288
289     #
290     # Catch various signals
291     #
292     foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
293         $SIG{$sig} = \&catch_signal;
294     }
295
296     #
297     # Report that we started, and update %Info.
298     #
299     print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
300     $Info{ConfigModTime} = $bpc->ConfigMTime();
301     $Info{pid} = $$;
302     $Info{startTime} = time;
303     $Info{Version} = $bpc->{Version};
304
305     #
306     # Update the status left over form the last time BackupPC ran.
307     # Requeue any pending links.
308     #
309     foreach my $host ( sort(keys(%$Hosts)) ) {
310         if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
311             #
312             # should we restart it?  skip it for now.
313             #
314             $Status{$host}{state} = "Status_idle";
315         } elsif ( $Status{$host}{state} eq "Status_link_pending"
316                 || $Status{$host}{state} eq "Status_link_running" ) {
317             QueueLink($host);
318         } else {
319             $Status{$host}{state} = "Status_idle";
320         }
321         $Status{$host}{activeJob} = 0;
322     }
323
324     #
325     # Write out our initial status and save our PID
326     #
327     StatusWrite();
328     if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
329         print(PID $$);
330         close(PID);
331     }
332
333     #
334     # For unknown reasons there is a very infrequent error about not
335     # being able to coerce GLOBs inside the XS Data::Dumper.  I've
336     # only seen this on a particular platform and perl version.
337     # For now the workaround appears to be use the perl version of
338     # XS Data::Dumper.
339     #
340     $Data::Dumper::Useqq = 1;
341 }
342
343 ############################################################################
344 # Main_TryToRun_nightly()
345 #
346 # Checks to see if we can/should run BackupPC_nightly or
347 # BackupPC_trashClean.  If so we push the appropriate command onto
348 # @CmdQueue.
349 ############################################################################
350 sub Main_TryToRun_nightly
351 {
352     #
353     # Check if we should run BackupPC_nightly or BackupPC_trashClean.
354     # BackupPC_nightly is run when the current job queue is empty.
355     # BackupPC_trashClean is run in the background always.
356     #
357     my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
358     if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
359         #
360         # This should only happen once at startup, but just in case this
361         # code will re-start BackupPC_trashClean if it quits
362         #
363         unshift(@CmdQueue, {
364                 host    => $bpc->trashJob,
365                 user    => "BackupPC",
366                 reqTime => time,
367                 cmd     => ["$BinDir/BackupPC_trashClean"],
368             });
369         $CmdQueueOn{$bpc->trashJob} = 1;
370     }
371     if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
372         push(@CmdQueue, {
373                 host    => $bpc->adminJob,
374                 user    => "BackupPC",
375                 reqTime => time,
376                 cmd     => ["$BinDir/BackupPC_nightly"],
377             });
378         $CmdQueueOn{$bpc->adminJob} = 1;
379         $RunNightlyWhenIdle = 2;
380     }
381 }
382
383 ############################################################################
384 # Main_TryToRun_CmdQueue()
385 #
386 # Decide if we can run a new command from the @CmdQueue.
387 # We only run one of these at a time.  The @CmdQueue is
388 # used to run BackupPC_link (for the corresponding host),
389 # BackupPC_trashClean, and BackupPC_nightly using a fake
390 # host name of $bpc->adminJob.
391 ############################################################################
392 sub Main_TryToRun_CmdQueue
393 {
394     my($req, $host);
395     if ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1 ) {
396         local(*FH);
397         $req = pop(@CmdQueue);
398
399         $host = $req->{host};
400         if ( defined($Jobs{$host}) ) {
401             print(LOG $bpc->timeStamp,
402                        "Botch on admin job for $host: already in use!!\n");
403             #
404             # This could happen during normal opertion: a user could
405             # request a backup while a BackupPC_link is queued from
406             # a previous backup.  But it is unlikely.  Just put this
407             # request back on the end of the queue.
408             #
409             unshift(@CmdQueue, $req);
410             return;
411         }
412         $CmdQueueOn{$host} = 0;
413         my $cmd  = $req->{cmd};
414         my $pid = open(FH, "-|");
415         if ( !defined($pid) ) {
416             print(LOG $bpc->timeStamp,
417                        "can't fork for $host, request by $req->{user}\n");
418             close(FH);
419             next;
420         }
421         if ( !$pid ) {
422             setpgrp 0,0;
423             exec(@$cmd);
424             print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
425             exit(0);
426         }
427         $Jobs{$host}{pid}       = $pid;
428         $Jobs{$host}{fh}        = *FH;
429         $Jobs{$host}{fn}        = fileno(FH);
430         vec($FDread, $Jobs{$host}{fn}, 1) = 1;
431         $Jobs{$host}{startTime} = time;
432         $Jobs{$host}{reqTime}   = $req->{reqTime};
433         $cmd                    = join(" ", @$cmd);
434         $Jobs{$host}{cmd}       = $cmd;
435         $Jobs{$host}{type}      = $Status{$host}{type};
436         $Status{$host}{state}   = "Status_link_running";
437         $Status{$host}{activeJob} = 1;
438         $Status{$host}{endTime} = time;
439         $CmdJob = $host if ( $host ne $bpc->trashJob );
440         $cmd =~ s/$BinDir\///g;
441         print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
442     }
443 }
444
445 ############################################################################
446 # Main_TryToRun_Bg_or_User_Queue()
447 #
448 # Decide if we can run any new backup requests from @BgQueue
449 # or @UserQueue.  Several of these can be run at the same time
450 # based on %Conf settings.  Jobs from @UserQueue take priority,
451 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
452 # simultaneous jobs can run from @UserQueue.  After @UserQueue
453 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
454 # run from @BgQueue.
455 ############################################################################
456 sub Main_TryToRun_Bg_or_User_Queue
457 {
458     my($req, $host);
459     while ( $RunNightlyWhenIdle == 0 ) {
460         local(*FH);
461         my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
462         my $nJobs = keys(%Jobs);
463         #
464         # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
465         #
466         $nJobs-- if ( $CmdJob ne "" );
467         $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
468         if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
469                         && @UserQueue > 0 ) {
470             $req = pop(@UserQueue);
471             if ( defined($Jobs{$req->{host}}) ) {
472                 push(@deferUserQueue, $req);
473                 next;
474             }
475             push(@args, $req->{doFull} ? "-f" : "-i")
476                             if ( !$req->{restore} );
477             $UserQueueOn{$req->{host}} = 0;
478         } elsif ( $nJobs < $Conf{MaxBackups}
479                         && (@CmdQueue + $nJobs)
480                                 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
481                         && @BgQueue > 0 ) {
482             my $du;
483             if ( time - $Info{DUlastValueTime} >= 60 ) {
484                 #
485                 # Update our notion of disk usage no more than
486                 # once every minute
487                 #
488                 $du = $bpc->CheckFileSystemUsage($TopDir);
489                 $Info{DUlastValue}     = $du;
490                 $Info{DUlastValueTime} = time;
491             } else {
492                 #
493                 # if we recently checked it then just use the old value
494                 #
495                 $du = $Info{DUlastValue};
496             }
497             if ( $Info{DUDailyMaxReset} ) {
498                 $Info{DUDailyMaxStartTime} = time;
499                 $Info{DUDailyMaxReset}     = 0;
500                 $Info{DUDailyMax}          = 0;
501             }
502             if ( $du > $Info{DUDailyMax} ) {
503                 $Info{DUDailyMax}     = $du;
504                 $Info{DUDailyMaxTime} = time;
505             }
506             if ( $du > $Conf{DfMaxUsagePct} ) {
507                 my $nSkip = @BgQueue + @deferBgQueue;
508                 print(LOG $bpc->timeStamp,
509                            "Disk too full ($du%%); skipping $nSkip hosts\n");
510                 $Info{DUDailySkipHostCnt} += $nSkip;
511                 @BgQueue = ();
512                 @deferBgQueue = ();
513                 %BgQueueOn = ();
514                 next;
515             }
516             $req = pop(@BgQueue);
517             if ( defined($Jobs{$req->{host}}) ) {
518                 push(@deferBgQueue, $req);
519                 next;
520             }
521             $BgQueueOn{$req->{host}} = 0;
522         } else {
523             while ( @deferBgQueue ) {
524                 push(@BgQueue, pop(@deferBgQueue));
525             }
526             while ( @deferUserQueue ) {
527                 push(@UserQueue, pop(@deferUserQueue));
528             }
529             last;
530         }
531         $host = $req->{host};
532         my $user = $req->{user};
533         if ( $req->{restore} ) {
534             $progName = "BackupPC_restore";
535             $type     = "restore";
536             push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
537         } else {
538             $progName = "BackupPC_dump";
539             $type     = "backup";
540             push(@args, "-d") if ( $req->{dhcp} );
541             push(@args, "-e") if ( $req->{dumpExpire} );
542             push(@args, $host);
543         }
544         my $pid = open(FH, "-|");
545         if ( !defined($pid) ) {
546             print(LOG $bpc->timeStamp,
547                    "can't fork to run $progName for $host, request by $user\n");
548             close(FH);
549             next;
550         }
551         if ( !$pid ) {
552             setpgrp 0,0;
553             exec("$BinDir/$progName", @args);
554             print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
555             exit(0);
556         }
557         $Jobs{$host}{pid}        = $pid;
558         $Jobs{$host}{fh}         = *FH;
559         $Jobs{$host}{fn}         = fileno(FH);
560         $Jobs{$host}{dhcp}       = $req->{dhcp};
561         vec($FDread, $Jobs{$host}{fn}, 1) = 1;
562         $Jobs{$host}{startTime}  = time;
563         $Jobs{$host}{reqTime}    = $req->{reqTime};
564         $Jobs{$host}{cmd}        = join(" ", $progName, @args);
565         $Jobs{$host}{user}       = $user;
566         $Jobs{$host}{type}       = $type;
567         if ( !$req->{dhcp} ) {
568             $Status{$host}{state}     = "Status_".$type."_starting";
569             $Status{$host}{activeJob} = 1;
570             $Status{$host}{startTime} = time;
571             $Status{$host}{endTime}   = "";
572         }
573     }
574 }
575
576 ############################################################################
577 # Main_Select()
578 #
579 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
580 # and then do a select() to wait for the next thing to happen
581 # (timeout, signal, someone sends a message, child dies etc).
582 ############################################################################
583 sub Main_Select
584 {
585     if ( $NextWakeup <= 0 ) {
586         #
587         # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
588         #
589         my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
590                                                 = localtime(time);
591         my($currHours) = $hour + $min / 60 + $sec / 3600;
592         if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
593             my($mesg) = $bpc->ConfigRead()
594                         || "Re-read config file because mtime changed";
595             print(LOG $bpc->timeStamp, "$mesg\n");
596             %Conf = $bpc->Conf();
597             $Info{ConfigModTime} = $bpc->ConfigMTime();
598             umask($Conf{UmaskMode});
599             ServerSocketInit();
600         }
601         my $delta = -1;
602         foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
603             next if ( $t < 0 || $t > 24 );
604             my $tomorrow = $t + 24;
605             if ( $delta < 0
606                 || ($tomorrow - $currHours > 0
607                                 && $delta > $tomorrow - $currHours) ) {
608                 $delta = $tomorrow - $currHours;
609                 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
610             }
611             if ( $delta < 0
612                     || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
613                 $delta = $t - $currHours;
614                 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
615             }
616         }
617         $NextWakeup = time + $delta * 3600;
618         $Info{nextWakeup} = $NextWakeup;
619         print(LOG $bpc->timeStamp, "Next wakeup is ",
620                   $bpc->timeStamp($NextWakeup, 1), "\n");
621     }
622     #
623     # Call select(), waiting until either a signal, a timeout,
624     # any output from our jobs, or any messages from clients
625     # connected via tcp.
626     # select() is where we (hopefully) spend most of our time blocked...
627     #
628     my $timeout = $NextWakeup - time;
629     $timeout = 1 if ( $timeout <= 0 );
630     my $ein = $FDread;
631     select(my $rout = $FDread, undef, $ein, $timeout);
632
633     return $rout;
634 }
635
636 ############################################################################
637 # Main_Process_Signal()
638 #
639 # Signal handler.
640 ############################################################################
641 sub Main_Process_Signal
642 {
643     #
644     # Process signals
645     #
646     if ( $SigName eq "HUP" ) {
647         my($mesg) = $bpc->ConfigRead()
648                     || "Re-read config file because of a SIG_HUP";
649         print(LOG $bpc->timeStamp, "$mesg\n");
650         $Info{ConfigModTime} = $bpc->ConfigMTime();
651         %Conf = $bpc->Conf();
652         umask($Conf{UmaskMode});
653         ServerSocketInit();
654         HostsUpdate(0);
655         $NextWakeup = 0;
656     } elsif ( $SigName ) {
657         print(LOG $bpc->timeStamp, "Got signal $SigName... cleaning up\n");
658         foreach my $host ( keys(%Jobs) ) {
659             kill(2, $Jobs{$host}{pid});
660         }
661         StatusWrite();
662         unlink("$TopDir/log/BackupPC.pid");
663         exit(1);
664     }
665     $SigName = "";
666 }
667
668 ############################################################################
669 # Main_Check_Timeout()
670 #
671 # Check if a timeout has occured, and if so, queue all the PCs for backups.
672 # Also does log file aging on the first timeout after midnight.
673 ############################################################################
674 sub Main_Check_Timeout
675 {
676     #
677     # Process timeouts
678     #
679     return if ( time < $NextWakeup || $NextWakeup <= 0 );
680     $NextWakeup = 0;
681     if ( $FirstWakeup ) {
682         #
683         # This is the first wakeup after midnight.  Do log file aging
684         # and various house keeping.
685         #
686         $FirstWakeup = 0;
687         printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
688                    . " %d skipped hosts\n",
689                    $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
690                    $Info{DUDailySkipHostCnt});
691         $Info{DUDailyMaxReset}        = 1;
692         $Info{DUDailyMaxPrev}         = $Info{DUDailyMax};
693         $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
694         $Info{DUDailySkipHostCnt}     = 0;
695         my $lastLog = $Conf{MaxOldLogFiles} - 1;
696         if ( -f "$TopDir/log/LOG.$lastLog" ) {
697             print(LOG $bpc->timeStamp,
698                        "Removing $TopDir/log/LOG.$lastLog\n");
699             unlink("$TopDir/log/LOG.$lastLog");
700         }
701         if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
702             print(LOG $bpc->timeStamp,
703                        "Removing $TopDir/log/LOG.$lastLog.z\n");
704             unlink("$TopDir/log/LOG.$lastLog.z");
705         }
706         print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
707                    . "LOG.1 -> ... -> LOG.$lastLog\n");
708         close(LOG);
709         for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
710             my $j = $i + 1;
711             rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
712                             if ( -f "$TopDir/log/LOG.$i" );
713             rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
714                             if ( -f "$TopDir/log/LOG.$i.z" );
715         }
716         #
717         # Compress the log file LOG -> LOG.0.z (if enabled).
718         # Otherwise, just rename LOG -> LOG.0.
719         #
720         BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
721                                         "$TopDir/log/LOG.0.z",
722                                         "$TopDir/log/LOG.0",
723                                         $Conf{CompressLevel}, 1);
724         LogFileOpen();
725         #
726         # Remember to run nightly script after current jobs are done
727         #
728         $RunNightlyWhenIdle = 1;
729     }
730     #
731     # Write out the current status and then queue all the PCs
732     #
733     HostsUpdate(0);
734     StatusWrite();
735     %BgQueueOn = ()   if ( @BgQueue == 0 );
736     %UserQueueOn = () if ( @UserQueue == 0 );
737     %CmdQueueOn = ()  if ( @CmdQueue == 0 );
738     QueueAllPCs();
739 }
740
741 ############################################################################
742 # Main_Check_Job_Messages($fdRead)
743 #
744 # Check if select() says we have bytes waiting from any of our jobs.
745 # Handle each of the messages when complete (newline terminated).
746 ############################################################################
747 sub Main_Check_Job_Messages
748 {
749     my($fdRead) = @_;
750     foreach my $host ( keys(%Jobs) ) {
751         next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
752         my $mesg;
753         #
754         # do a last check to make sure there is something to read so
755         # we are absolutely sure we won't block.
756         #
757         vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
758         if ( !select($readMask, undef, undef, 0.0) ) {
759             print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
760                         . " nothing to read from $host.  Debug dump:\n");
761             my($dump) = Data::Dumper->new(
762                          [  \%Clients, \%Jobs, \$FDread, \$fdRead],
763                          [qw(*Clients,  *Jobs   *FDread,  *fdRead)]);
764             $dump->Indent(1);
765             print(LOG $dump->Dump);
766             next;
767         }
768         my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
769         $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
770         #
771         # Process any complete lines of output from this jobs.
772         # Any output to STDOUT or STDERR from the children is processed here.
773         #
774         while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
775             $mesg = $1;
776             $Jobs{$host}{mesg} = $2;
777             if ( $Jobs{$host}{dhcp} ) {
778                 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
779                     my $newHost = $bpc->uriUnesc($2);
780                     if ( defined($Jobs{$newHost}) ) {
781                         print(LOG $bpc->timeStamp,
782                                 "Backup on $newHost is already running\n");
783                         kill(2, $Jobs{$host}{pid});
784                         $nbytes = 0;
785                         last;
786                     }
787                     $Jobs{$host}{dhcpHostIP} = $host;
788                     $Status{$newHost}{dhcpHostIP} = $host;
789                     $Jobs{$newHost} = $Jobs{$host};
790                     delete($Jobs{$host});
791                     $host = $newHost;
792                     $Status{$host}{state}      = "Status_backup_starting";
793                     $Status{$host}{activeJob}  = 1;
794                     $Status{$host}{startTime}  = $Jobs{$host}{startTime};
795                     $Status{$host}{endTime}    = "";
796                     $Jobs{$host}{dhcp}         = 0;
797                 } else {
798                     print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
799                 }
800             } elsif ( $mesg =~ /^started (.*) dump, pid=(-?\d+), tarPid=(-?\d+), share=(.*)/ ) {
801                 $Jobs{$host}{type}      = $1;
802                 $Jobs{$host}{xferPid}   = $2;
803                 $Jobs{$host}{tarPid}    = $3;
804                 $Jobs{$host}{shareName} = $4;
805                 print(LOG $bpc->timeStamp,
806                           "Started $1 backup on $host"
807                           . " (pid=$Jobs{$host}{pid}, xferPid=$2",
808                           $Jobs{$host}{tarPid} > 0
809                                 ? ", tarPid=$Jobs{$host}{tarPid}" : "",
810                           $Jobs{$host}{dhcpHostIP}
811                                 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
812                           ", share=$Jobs{$host}{shareName})\n");
813                 $Status{$host}{state}     = "Status_backup_in_progress";
814                 $Status{$host}{reason}    = "";
815                 $Status{$host}{type}      = $1;
816                 $Status{$host}{startTime} = time;
817                 $Status{$host}{deadCnt}   = 0;
818                 $Status{$host}{aliveCnt}++;
819                 $Status{$host}{dhcpCheckCnt}--
820                                 if ( $Status{$host}{dhcpCheckCnt} > 0 );
821             } elsif ( $mesg =~ /^started_restore (\S+) (\S+)/ ) {
822                 $Jobs{$host}{type}    = "restore";
823                 $Jobs{$host}{xferPid} = $1;
824                 $Jobs{$host}{tarPid}  = $2;
825                 print(LOG $bpc->timeStamp,
826                           "Started restore on $host"
827                           . " (pid=$Jobs{$host}{pid}, xferPid=$2",
828                           $Jobs{$host}{tarPid} > 0
829                                 ? ", tarPid=$Jobs{$host}{tarPid}" : "",
830                           ")\n");
831                 $Status{$host}{state}     = "Status_restore_in_progress";
832                 $Status{$host}{reason}    = "";
833                 $Status{$host}{type}      = "restore";
834                 $Status{$host}{startTime} = time;
835                 $Status{$host}{deadCnt}   = 0;
836                 $Status{$host}{aliveCnt}++;
837             } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
838                 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
839                 $Status{$host}{reason}    = "Reason_backup_done";
840                 delete($Status{$host}{error});
841                 delete($Status{$host}{errorTime});
842                 $Status{$host}{endTime}   = time;
843             } elsif ( $mesg =~ /^restore complete/ ) {
844                 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
845                 $Status{$host}{reason}    = "Reason_restore_done";
846                 delete($Status{$host}{error});
847                 delete($Status{$host}{errorTime});
848                 $Status{$host}{endTime}   = time;
849             } elsif ( $mesg =~ /^nothing to do/ ) {
850                 $Status{$host}{state}     = "Status_idle";
851                 $Status{$host}{reason}    = "Reason_nothing_to_do";
852                 $Status{$host}{startTime} = time;
853                 $Status{$host}{dhcpCheckCnt}--
854                                 if ( $Status{$host}{dhcpCheckCnt} > 0 );
855             } elsif ( $mesg =~ /^no ping response/
856                             || $mesg =~ /^ping too slow/ ) {
857                 $Status{$host}{state}     = "Status_idle";
858                 if ( $Status{$host}{reason} ne "Reason_backup_failed" ) {
859                     $Status{$host}{reason}    = "Reason_no_ping";
860                     $Status{$host}{startTime} = time;
861                 }
862                 $Status{$host}{deadCnt}++;
863                 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
864                     $Status{$host}{aliveCnt} = 0;
865                 }
866             } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
867                 $Status{$host}{state}     = "Status_idle";
868                 $Status{$host}{reason}    = "Reason_backup_failed";
869                 $Status{$host}{error}     = $1;
870                 $Status{$host}{errorTime} = time;
871                 $Status{$host}{endTime}   = time;
872                 print(LOG $bpc->timeStamp, "backup failed on $host ($1)\n");
873             } elsif ( $mesg =~ /^log\s+(.*)/ ) {
874                 print(LOG $bpc->timeStamp, "$1\n");
875             } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
876                 my @f = split(/,/, $1);
877                 $Info{"$f[0]FileCnt"}       = $f[1];
878                 $Info{"$f[0]DirCnt"}        = $f[2];
879                 $Info{"$f[0]Kb"}            = $f[3];
880                 $Info{"$f[0]Kb2"}           = $f[4];
881                 $Info{"$f[0]KbRm"}          = $f[5];
882                 $Info{"$f[0]FileCntRm"}     = $f[6];
883                 $Info{"$f[0]FileCntRep"}    = $f[7];
884                 $Info{"$f[0]FileRepMax"}    = $f[8];
885                 $Info{"$f[0]FileCntRename"} = $f[9];
886                 $Info{"$f[0]FileLinkMax"}   = $f[10];
887                 $Info{"$f[0]Time"}          = time;
888                 printf(LOG "%s%s nightly clean removed %d files of"
889                            . " size %.2fGB\n",
890                              $bpc->timeStamp, ucfirst($f[0]),
891                              $Info{"$f[0]FileCntRm"},
892                              $Info{"$f[0]KbRm"} / (1000 * 1024));
893                 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
894                            . "%d max chain, %d max links), %d directories\n",
895                              $bpc->timeStamp, ucfirst($f[0]),
896                              $Info{"$f[0]Kb"} / (1000 * 1024),
897                              $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
898                              $Info{"$f[0]FileRepMax"},
899                              $Info{"$f[0]FileLinkMax"}, $Info{"$f[0]DirCnt"});
900             } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
901                 $RunNightlyWhenIdle = 0;
902             } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
903                 $Jobs{$host}{processState} = $1;
904             } elsif ( $mesg =~ /^link\s+(.+)/ ) {
905                 my($h) = $1;
906                 $Status{$h}{needLink} = 1;
907             } else {
908                 print(LOG $bpc->timeStamp, "$host: $mesg\n");
909             }
910         }
911         #
912         # shut down the client connection if we read EOF
913         #
914         if ( $nbytes <= 0 ) {
915             close($Jobs{$host}{fh});
916             vec($FDread, $Jobs{$host}{fn}, 1) = 0;
917             if ( $CmdJob eq $host ) {
918                 my $cmd = $Jobs{$host}{cmd};
919                 $cmd =~ s/$BinDir\///g;
920                 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
921                 $Status{$host}{state}    = "Status_idle";
922                 $Status{$host}{endTime}  = time;
923                 $CmdJob = "";
924                 $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
925                                             && $RunNightlyWhenIdle );
926             } else {
927                 #
928                 # Queue BackupPC_link to complete the backup
929                 # processing for this host.
930                 #
931                 if ( defined($Status{$host})
932                             && ($Status{$host}{reason} eq "Reason_backup_done"
933                                 || $Status{$host}{needLink}) ) {
934                     QueueLink($host);
935                 } elsif ( defined($Status{$host}) ) {
936                     $Status{$host}{state} = "Status_idle";
937                 }
938             }
939             delete($Jobs{$host});
940             $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
941         }
942     }
943     #
944     # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
945     # do a pass over %Status updating the deadCnt and aliveCnt for
946     # DHCP hosts.  The reason we need to do this later is we can't
947     # be sure whether a DHCP host is alive or dead until we have passed
948     # over all the DHCP pool.
949     #
950     return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
951     foreach my $host ( keys(%Status) ) {
952         next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
953         $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
954         $Status{$host}{dhcpCheckCnt} = 0;
955         if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
956             $Status{$host}{aliveCnt} = 0;
957         }
958     }
959 }
960
961 ############################################################################
962 # Main_Check_Client_Messages($fdRead)
963 #
964 # Check for, and process, any output from our clients.  Also checks
965 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
966 ############################################################################
967 sub Main_Check_Client_Messages
968 {
969     my($fdRead) = @_;
970     foreach my $client ( keys(%Clients) ) {
971         next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
972         my($mesg, $host);
973         #
974         # do a last check to make sure there is something to read so
975         # we are absolutely sure we won't block.
976         #
977         vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
978         if ( !select($readMask, undef, undef, 0.0) ) {
979             print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
980                         . " nothing to read from $client.  Debug dump:\n");
981             my($dump) = Data::Dumper->new(
982                          [  \%Clients, \%Jobs, \$FDread, \$fdRead],
983                          [qw(*Clients,  *Jobs   *FDread,  *fdRead)]);
984             $dump->Indent(1);
985             print(LOG $dump->Dump);
986             next;
987         }
988         my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
989         $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
990         #
991         # Process any complete lines received from this client.
992         #
993         while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
994             my($reply);
995             my $cmd = $1;
996             $Clients{$client}{mesg} = $2;
997             #
998             # Authenticate the message by checking the MD5 digest
999             #
1000             my $md5 = Digest::MD5->new;
1001             if ( $cmd !~ /^(.{22}) (.*)/
1002                 || ($md5->add($Clients{$client}{seed}
1003                             . $Clients{$client}{mesgCnt}
1004                             . $Conf{ServerMesgSecret} . $2),
1005                      $md5->b64digest ne $1) ) {
1006                 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1007                             . " client '$Clients{$client}{clientName}':"
1008                             . " shutting down client connection\n");
1009                 $nbytes = 0;
1010                 last;
1011             }
1012             $Clients{$client}{mesgCnt}++;
1013             $cmd = $2;
1014             if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1015                 $host = $1;
1016                 my $user = $2;
1017                 my $backoff = $3;
1018                 $host = $bpc->uriUnesc($host);
1019                 if ( $CmdJob ne $host && defined($Status{$host})
1020                                       && defined($Jobs{$host}) ) {
1021                     print(LOG $bpc->timeStamp,
1022                                "Stopping current backup of $host,"
1023                              . " request by $user (backoff=$backoff)\n");
1024                     kill(2, $Jobs{$host}{pid});
1025                     vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1026                     close($Jobs{$host}{fh});
1027                     delete($Jobs{$host});
1028                     $Status{$host}{state}     = "Status_idle";
1029                     $Status{$host}{reason}    = "Reason_backup_canceled_by_user"; #FIXME: user should be $user (we need to substitute the variable in the l10n stuff)
1030                     $Status{$host}{activeJob} = 0;
1031                     $Status{$host}{startTime} = time;
1032                     $reply = "ok: backup of $host cancelled";
1033                 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1034                     print(LOG $bpc->timeStamp,
1035                                "Stopping pending backup of $host,"
1036                              . " request by $user (backoff=$backoff)\n");
1037                     @BgQueue = grep($_->{host} ne $host, @BgQueue);
1038                     @UserQueue = grep($_->{host} ne $host, @UserQueue);
1039                     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1040                     $reply = "ok: pending backup of $host cancelled";
1041                 } else {
1042                     print(LOG $bpc->timeStamp,
1043                                "Nothing to do for stop backup of $host,"
1044                              . " request by $user (backoff=$backoff)\n");
1045                     $reply = "ok: no backup was pending or running";
1046                 }
1047                 if ( defined($Status{$host}) && $backoff ne "" ) {
1048                     if ( $backoff > 0 ) {
1049                         $Status{$host}{backoffTime} = time + $backoff * 3600;
1050                     } else {
1051                         delete($Status{$host}{backoffTime});
1052                     }
1053                 }
1054             } elsif ( $cmd =~ /^backup all$/ ) {
1055                 QueueAllPCs();
1056             } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1057                 my $hostIP = $1;
1058                 $host      = $2;
1059                 my $user   = $3;
1060                 my $doFull = $4;
1061                 $host      = $bpc->uriUnesc($host);
1062                 $hostIP    = $bpc->uriUnesc($hostIP);
1063                 if ( !defined($Status{$host}) ) {
1064                     print(LOG $bpc->timeStamp,
1065                                "User $user requested backup of unknown host"
1066                              . " $host\n");
1067                     $reply = "error: unknown host $host";
1068                 } elsif ( defined($Jobs{$host})
1069                                 && $Jobs{$host}{type} ne "restore" ) {
1070                     print(LOG $bpc->timeStamp,
1071                                "User $user requested backup of $host,"
1072                              . " but one is currently running\n");
1073                     $reply = "error: backup of $host is already running";
1074                 } else {
1075                     print(LOG $bpc->timeStamp,
1076                                "User $user requested backup of $host"
1077                              . " ($hostIP)\n");
1078                     if ( $BgQueueOn{$hostIP} ) {
1079                         @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1080                         $BgQueueOn{$hostIP} = 0;
1081                     }
1082                     if ( $UserQueueOn{$hostIP} ) {
1083                         @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1084                         $UserQueueOn{$hostIP} = 0;
1085                     }
1086                     unshift(@UserQueue, {
1087                                 host    => $hostIP,
1088                                 user    => $user,
1089                                 reqTime => time,
1090                                 doFull  => $doFull,
1091                                 dhcp    => $hostIP eq $host ? 0 : 1,
1092                         });
1093                     $UserQueueOn{$hostIP} = 1;
1094                     $reply = "ok: requested backup of $host";
1095                 }
1096             } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1097                 my $hostIP = $1;
1098                 $host      = $2;
1099                 my $user   = $3;
1100                 my $reqFileName = $4;
1101                 $host      = $bpc->uriUnesc($host);
1102                 $hostIP    = $bpc->uriUnesc($hostIP);
1103                 if ( !defined($Status{$host}) ) {
1104                     print(LOG $bpc->timeStamp,
1105                                "User $user requested restore to unknown host"
1106                              . " $host");
1107                     $reply = "restore error: unknown host $host";
1108                 } else {
1109                     print(LOG $bpc->timeStamp,
1110                                "User $user requested restore to $host"
1111                              . " ($hostIP)\n");
1112                     unshift(@UserQueue, {
1113                                 host    => $host,
1114                                 hostIP  => $hostIP,
1115                                 reqFileName => $reqFileName,
1116                                 reqTime => time,
1117                                 dhcp    => 0,
1118                                 restore => 1,
1119                         });
1120                     $UserQueueOn{$host} = 1;
1121                     if ( defined($Jobs{$host}) ) {
1122                         $reply = "ok: requested restore of $host, but a"
1123                                . " job is currently running,"
1124                                . " so this request will start later";
1125                     } else {
1126                         $reply = "ok: requested restore of $host";
1127                     }
1128                 }
1129             } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1130                 my($args) = $1;
1131                 my($dump, @values, @names);
1132                 foreach my $type ( split(/\s+/, $args) ) {
1133                     if ( $type =~ /^queues/ ) {
1134                         push(@values,  \@BgQueue, \@UserQueue, \@CmdQueue);
1135                         push(@names, qw(*BgQueue   *UserQueue   *CmdQueue));
1136                     } elsif ( $type =~ /^jobs/ ) {
1137                         push(@values,  \%Jobs);
1138                         push(@names, qw(*Jobs));
1139                     } elsif ( $type =~ /^queueLen/ ) {
1140                         push(@values,  {
1141                                 BgQueue   => scalar(@BgQueue),
1142                                 UserQueue => scalar(@UserQueue),
1143                                 CmdQueue  => scalar(@CmdQueue),
1144                             });
1145                         push(@names, qw(*QueueLen));
1146                     } elsif ( $type =~ /^info/ ) {
1147                         push(@values,  \%Info);
1148                         push(@names, qw(*Info));
1149                     } elsif ( $type =~ /^hosts/ ) {
1150                         push(@values,  \%Status);
1151                         push(@names, qw(*Status));
1152                     } elsif ( $type =~ /^host\((.*)\)/ ) {
1153                         my $h = $bpc->uriUnesc($1);
1154                         if ( defined($Status{$h}) ) {
1155                             push(@values,  {
1156                                     %{$Status{$h}},
1157                                     BgQueueOn => $BgQueueOn{$h},
1158                                     UserQueueOn => $UserQueueOn{$h},
1159                                     CmdQueueOn => $CmdQueueOn{$h},
1160                                 });
1161                             push(@names, qw(*StatusHost));
1162                         } else {
1163                             print(LOG $bpc->timeStamp,
1164                                       "Unknown host $h for status request\n");
1165                         }
1166                     } else {
1167                         print(LOG $bpc->timeStamp,
1168                                   "Unknown status request $type\n");
1169                     }
1170                 }
1171                 $dump = Data::Dumper->new(\@values, \@names);
1172                 $dump->Indent(0);
1173                 $reply = $dump->Dump;
1174             } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1175                 my($host) = $1;
1176                 $host = $bpc->uriUnesc($host);
1177                 QueueLink($host);
1178             } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1179                 print(LOG $bpc->timeStamp, "$1\n");
1180             } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1181                 $nbytes = 0;
1182                 last;
1183             } else {
1184                 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1185                 $reply = "error: bad command $cmd";
1186             }
1187             #
1188             # send a reply to the client, at a minimum "ok\n".
1189             #
1190             $reply = "ok" if ( $reply eq "" );
1191             $reply .= "\n";
1192             syswrite($Clients{$client}{fh}, $reply, length($reply));
1193         }
1194         #
1195         # Detect possible denial-of-service attack from sending a huge line
1196         # (ie: never terminated).  32K seems to be plenty big enough as
1197         # a limit.
1198         #
1199         if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1200             print(LOG $bpc->timeStamp, "Line too long from client"
1201                         . " '$Clients{$client}{clientName}':"
1202                         . " shutting down client connection\n");
1203             $nbytes = 0;
1204         }
1205         #
1206         # Shut down the client connection if we read EOF
1207         #
1208         if ( $nbytes <= 0 ) {
1209             close($Clients{$client}{fh});
1210             vec($FDread, $Clients{$client}{fn}, 1) = 0;
1211             delete($Clients{$client});
1212         }
1213     }
1214     #
1215     # Accept any new connections on each of our listen sockets
1216     #
1217     if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1218         local(*CLIENT);
1219         my $paddr = accept(CLIENT, SERVER_UNIX);
1220         $ClientConnCnt++;
1221         $Clients{$ClientConnCnt}{clientName} = "unix socket";
1222         $Clients{$ClientConnCnt}{mesg} = "";
1223         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1224         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
1225         vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1226         #
1227         # Generate and send unique seed for MD5 digests to avoid
1228         # replay attacks.  See BackupPC::Lib::ServerMesg().
1229         #
1230         my $seed = time . ",$ClientConnCnt,$$,0\n";
1231         $Clients{$ClientConnCnt}{seed}    = $seed;
1232         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1233         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1234     }
1235     if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1236         local(*CLIENT);
1237         my $paddr = accept(CLIENT, SERVER_INET);
1238         my($port,$iaddr) = sockaddr_in($paddr); 
1239         my $name = gethostbyaddr($iaddr, AF_INET);
1240         $ClientConnCnt++;
1241         $Clients{$ClientConnCnt}{mesg} = "";
1242         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1243         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
1244         $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1245         vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1246         #
1247         # Generate and send unique seed for MD5 digests to avoid
1248         # replay attacks.  See BackupPC::Lib::ServerMesg().
1249         #
1250         my $seed = time . ",$ClientConnCnt,$$,$port\n";
1251         $Clients{$ClientConnCnt}{seed}    = $seed;
1252         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1253         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1254     }
1255 }
1256
1257 ###########################################################################
1258 # Miscellaneous subroutines
1259 ###########################################################################
1260
1261 #
1262 # Write the current status to $TopDir/log/status.pl
1263 #
1264 sub StatusWrite
1265 {
1266     my($dump) = Data::Dumper->new(
1267              [  \%Info, \%Status],
1268              [qw(*Info   *Status)]);
1269     $dump->Indent(1);
1270     if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1271         print(STATUS $dump->Dump);
1272         close(STATUS);
1273     }
1274 }
1275
1276 #
1277 # Queue all the hosts for backup.  This means queuing all the fixed
1278 # ip hosts and all the dhcp address ranges.  We also additionally
1279 # queue the dhcp hosts with a -e flag to check for expired dumps.
1280 #
1281 sub QueueAllPCs
1282 {
1283     foreach my $host ( sort(keys(%$Hosts)) ) {
1284         delete($Status{$host}{backoffTime})
1285                 if ( defined($Status{$host}{backoffTime})
1286                   && $Status{$host}{backoffTime} < time );
1287         next if ( defined($Jobs{$host})
1288                 || $BgQueueOn{$host}
1289                 || $UserQueueOn{$host}
1290                 || $CmdQueueOn{$host} ); 
1291         if ( $Hosts->{$host}{dhcp} ) {
1292             $Status{$host}{dhcpCheckCnt}++;
1293             if ( $RunNightlyWhenIdle ) {
1294                 #
1295                 # Once per night queue a check for DHCP hosts that just
1296                 # checks for expired dumps.  We need to do this to handle
1297                 # the case when a DHCP host has not been on the network for
1298                 # a long time, and some of the old dumps need to be expired.
1299                 # Normally expiry checks are done by BackupPC_dump only
1300                 # after the DHCP hosts has been detected on the network.
1301                 #
1302                 unshift(@BgQueue,
1303                     {host => $host, user => "BackupPC", reqTime => time,
1304                      dhcp => 0, dumpExpire => 1});
1305                 $BgQueueOn{$host} = 1;
1306             }
1307         } else {
1308             #
1309             # this is a fixed ip host: queue it
1310             #
1311             unshift(@BgQueue,
1312                 {host => $host, user => "BackupPC", reqTime => time,
1313                  dhcp => $Hosts->{$host}{dhcp}});
1314             $BgQueueOn{$host} = 1;
1315         }
1316     }
1317     foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1318         for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1319             my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1320             next if ( defined($Jobs{$ipAddr})
1321                     || $BgQueueOn{$ipAddr}
1322                     || $UserQueueOn{$ipAddr}
1323                     || $CmdQueueOn{$ipAddr} ); 
1324             #
1325             # this is a potential dhcp ip address (we don't know the
1326             # host name yet): queue it
1327             #
1328             unshift(@BgQueue,
1329                 {host => $ipAddr, user => "BackupPC", reqTime => time,
1330                  dhcp => 1});
1331             $BgQueueOn{$ipAddr} = 1;
1332         }
1333     }
1334 }
1335
1336 #
1337 # Queue a BackupPC_link for the given host
1338 #
1339 sub QueueLink
1340 {
1341     my($host) = @_;
1342
1343     return if ( $CmdQueueOn{$host} );
1344     $Status{$host}{state}    = "Status_link_pending";
1345     $Status{$host}{needLink} = 0;
1346     unshift(@CmdQueue, {
1347             host    => $host,
1348             user    => "BackupPC",
1349             reqTime => time,
1350             cmd     => ["$BinDir/BackupPC_link",  $host],
1351         });
1352     $CmdQueueOn{$host} = 1;
1353 }
1354
1355 #
1356 # Read the hosts file, and update Status if any hosts have been
1357 # added or deleted.  We also track the mtime so the only need to
1358 # update the hosts file on changes.
1359 #
1360 # This function is called at startup, SIGHUP, and on each wakeup.
1361 # It returns 1 on success and undef on failure.
1362 #
1363 sub HostsUpdate
1364 {
1365     my($force) = @_;
1366     my $newHosts;
1367     #
1368     # Nothing to do if we already have the current hosts file
1369     #
1370     return 1 if ( !$force && defined($Hosts)
1371                           && $Info{HostsModTime} == $bpc->HostsMTime() );
1372     if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1373         print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1374         return;
1375     }
1376     print(LOG $bpc->timeStamp, "Reading hosts file\n");
1377     $Hosts = $newHosts;
1378     $Info{HostsModTime} = $bpc->HostsMTime();
1379     #
1380     # Now update %Status in case any hosts have been added or deleted
1381     #
1382     foreach my $host ( sort(keys(%$Hosts)) ) {
1383         next if ( defined($Status{$host}) );
1384         $Status{$host}{state} = "Status_idle";
1385         print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1386     }
1387     foreach my $host ( sort(keys(%Status)) ) {
1388         next if ( $host eq $bpc->trashJob
1389                      || $host eq $bpc->adminJob
1390                      || defined($Hosts->{$host})
1391                      || defined($Jobs{$host})
1392                      || $BgQueueOn{$host}
1393                      || $UserQueueOn{$host}
1394                      || $CmdQueueOn{$host} );
1395         print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1396         delete($Status{$host});
1397     }
1398     return 1;
1399 }
1400
1401 #
1402 # Remember the signal name for later processing
1403 #
1404 sub catch_signal
1405 {
1406     if ( $SigName ) {
1407         $SigName = shift;
1408         foreach my $host ( keys(%Jobs) ) {
1409             kill(2, $Jobs{$host}{pid});
1410         }
1411         #
1412         # In case we are inside the exit handler, reopen the log file
1413         #
1414         close(LOG);
1415         LogFileOpen();
1416         print(LOG "Fatal error: unhandled signal $SigName\n");
1417         unlink("$TopDir/log/BackupPC.pid");
1418         confess("Got new signal $SigName... quitting\n");
1419     }
1420     $SigName = shift;
1421 }
1422
1423 #
1424 # Open the log file and point STDOUT and STDERR there too
1425 #
1426 sub LogFileOpen
1427 {
1428     mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1429     open(LOG, ">>$TopDir/log/LOG")
1430             || die("Can't create LOG file $TopDir/log/LOG");
1431     close(STDOUT);
1432     close(STDERR);
1433     open(STDOUT, ">&LOG");
1434     open(STDERR, ">&LOG");
1435     select(LOG);    $| = 1;
1436     select(STDERR); $| = 1;
1437     select(STDOUT); $| = 1;
1438 }
1439
1440 #
1441 # Initialize the unix-domain and internet-domain sockets that
1442 # we listen to for client connections (from the CGI script and
1443 # some of the BackupPC sub-programs).
1444 #
1445 sub ServerSocketInit
1446 {
1447     if ( !defined(fileno(SERVER_UNIX)) ) {
1448         #
1449         # one-time only: initialize unix-domain socket
1450         #
1451         if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1452             print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1453             exit(1);
1454         }
1455         my $sockFile = "$TopDir/log/BackupPC.sock";
1456         unlink($sockFile);
1457         if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1458             print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1459             exit(1);
1460         }
1461         if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1462             print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1463             exit(1);
1464         }
1465         vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1466     }
1467     return if ( $ServerInetPort == $Conf{ServerPort} );
1468     if ( $ServerInetPort > 0 ) {
1469         vec($FDread, fileno(SERVER_INET), 1) = 0;
1470         close(SERVER_INET);
1471         $ServerInetPort = -1;
1472     }
1473     if ( $Conf{ServerPort} > 0 ) {
1474         #
1475         # Setup a socket to listen on $Conf{ServerPort}
1476         #
1477         my $proto = getprotobyname('tcp');
1478         if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1479             print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1480             exit(1);
1481         }
1482         if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1483             print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1484             exit(1);
1485         }
1486         if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1487             print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1488             exit(1);
1489         }
1490         if ( !listen(SERVER_INET, SOMAXCONN) ) {
1491             print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1492             exit(1);
1493         }
1494         vec($FDread, fileno(SERVER_INET), 1) = 1;
1495         $ServerInetPort = $Conf{ServerPort};
1496     }
1497 }