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