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