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