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