a7247c831bcdce8997f7737a3674a03564f12d4e
[BackupPC.git] / bin / BackupPC
1 #!/bin/perl
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.0beta0, released 20 Mar 2004.
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($bpc->sigName2num("INT"), $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 =~ /^started_archive/ ) {
822                 $Jobs{$host}{type}    = "archive";
823                 print(LOG $bpc->timeStamp,
824                           "Started archive on $host"
825                           . " (pid=$Jobs{$host}{pid})\n");
826                 $Status{$host}{state}     = "Status_archive_in_progress";
827                 $Status{$host}{reason}    = "";
828                 $Status{$host}{type}      = "archive";
829                 $Status{$host}{startTime} = time;
830                 $Status{$host}{deadCnt}   = 0;
831                 $Status{$host}{aliveCnt}++;
832             } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
833                 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
834                 $Status{$host}{reason}    = "Reason_backup_done";
835                 delete($Status{$host}{error});
836                 delete($Status{$host}{errorTime});
837                 $Status{$host}{endTime}   = time;
838             } elsif ( $mesg =~ /^backups disabled/ ) {
839                 print(LOG $bpc->timeStamp,
840                             "Ignoring old backup error on $host\n");
841                 $Status{$host}{reason}    = "Reason_backup_done";
842                 delete($Status{$host}{error});
843                 delete($Status{$host}{errorTime});
844                 $Status{$host}{endTime}   = time;
845             } elsif ( $mesg =~ /^restore complete/ ) {
846                 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
847                 $Status{$host}{reason}    = "Reason_restore_done";
848                 delete($Status{$host}{error});
849                 delete($Status{$host}{errorTime});
850                 $Status{$host}{endTime}   = time;
851             } elsif ( $mesg =~ /^archive complete/ ) {
852                 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
853                 $Status{$host}{reason}    = "Reason_archive_done";
854                 delete($Status{$host}{error});
855                 delete($Status{$host}{errorTime});
856                 $Status{$host}{endTime}   = time;
857             } elsif ( $mesg =~ /^nothing to do/ ) {
858                 if ( $Status{$host}{reason} ne "Reason_backup_failed"
859                         && $Status{$host}{reason} ne "Reason_restore_failed" ) {
860                     $Status{$host}{state}     = "Status_idle";
861                     $Status{$host}{reason}    = "Reason_nothing_to_do";
862                     $Status{$host}{startTime} = time;
863                 }
864                 $Status{$host}{dhcpCheckCnt}--
865                                 if ( $Status{$host}{dhcpCheckCnt} > 0 );
866             } elsif ( $mesg =~ /^no ping response/
867                             || $mesg =~ /^ping too slow/
868                             || $mesg =~ /^host not found/ ) {
869                 $Status{$host}{state}     = "Status_idle";
870                 if ( $Status{$host}{userReq}
871                         || $Status{$host}{reason} ne "Reason_backup_failed"
872                         || $Status{$host}{error} =~ /^aborted by user/ ) {
873                     $Status{$host}{reason}    = "Reason_no_ping";
874                     $Status{$host}{error}     = $mesg;
875                     $Status{$host}{startTime} = time;
876                 }
877                 $Status{$host}{deadCnt}++;
878                 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
879                     $Status{$host}{aliveCnt} = 0;
880                 }
881             } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
882                 $Status{$host}{state}     = "Status_idle";
883                 $Status{$host}{error}     = $1;
884                 $Status{$host}{errorTime} = time;
885                 $Status{$host}{endTime}   = time;
886                 if ( $Status{$host}{reason}
887                         eq "Reason_backup_canceled_by_user" ) {
888                     print(LOG $bpc->timeStamp,
889                             "Backup canceled on $host ($1)\n");
890                 } else {
891                     $Status{$host}{reason} = "Reason_backup_failed";
892                     print(LOG $bpc->timeStamp,
893                             "Backup failed on $host ($1)\n");
894                 }
895             } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
896                 $Status{$host}{state}     = "Status_idle";
897                 $Status{$host}{error}     = $1;
898                 $Status{$host}{errorTime} = time;
899                 $Status{$host}{endTime}   = time;
900                 if ( $Status{$host}{reason}
901                          eq "Reason_restore_canceled_by_user" ) {
902                     print(LOG $bpc->timeStamp,
903                             "Restore canceled on $host ($1)\n");
904                 } else {
905                     $Status{$host}{reason} = "Reason_restore_failed";
906                     print(LOG $bpc->timeStamp,
907                             "Restore failed on $host ($1)\n");
908                 }
909             } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
910                 $Status{$host}{state}     = "Status_idle";
911                 $Status{$host}{error}     = $1;
912                 $Status{$host}{errorTime} = time;
913                 $Status{$host}{endTime}   = time;
914                 if ( $Status{$host}{reason}
915                          eq "Reason_archive_canceled_by_user" ) {
916                     print(LOG $bpc->timeStamp,
917                             "Archive canceled on $host ($1)\n");
918                 } else {
919                     $Status{$host}{reason} = "Reason_archive_failed";
920                     print(LOG $bpc->timeStamp,
921                             "Archive failed on $host ($1)\n");
922                 }
923             } elsif ( $mesg =~ /^log\s+(.*)/ ) {
924                 print(LOG $bpc->timeStamp, "$1\n");
925             } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
926                 my @f = split(/,/, $1);
927                 $Info{"$f[0]FileCnt"}       = $f[1];
928                 $Info{"$f[0]DirCnt"}        = $f[2];
929                 $Info{"$f[0]Kb"}            = $f[3];
930                 $Info{"$f[0]Kb2"}           = $f[4];
931                 $Info{"$f[0]KbRm"}          = $f[5];
932                 $Info{"$f[0]FileCntRm"}     = $f[6];
933                 $Info{"$f[0]FileCntRep"}    = $f[7];
934                 $Info{"$f[0]FileRepMax"}    = $f[8];
935                 $Info{"$f[0]FileCntRename"} = $f[9];
936                 $Info{"$f[0]FileLinkMax"}   = $f[10];
937                 $Info{"$f[0]Time"}          = time;
938                 printf(LOG "%s%s nightly clean removed %d files of"
939                            . " size %.2fGB\n",
940                              $bpc->timeStamp, ucfirst($f[0]),
941                              $Info{"$f[0]FileCntRm"},
942                              $Info{"$f[0]KbRm"} / (1000 * 1024));
943                 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
944                            . "%d max chain, %d max links), %d directories\n",
945                              $bpc->timeStamp, ucfirst($f[0]),
946                              $Info{"$f[0]Kb"} / (1000 * 1024),
947                              $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
948                              $Info{"$f[0]FileRepMax"},
949                              $Info{"$f[0]FileLinkMax"}, $Info{"$f[0]DirCnt"});
950             } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
951                 $RunNightlyWhenIdle = 0;
952             } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
953                 $Jobs{$host}{processState} = $1;
954             } elsif ( $mesg =~ /^link\s+(.+)/ ) {
955                 my($h) = $1;
956                 $Status{$h}{needLink} = 1;
957             } else {
958                 print(LOG $bpc->timeStamp, "$host: $mesg\n");
959             }
960         }
961         #
962         # shut down the client connection if we read EOF
963         #
964         if ( $nbytes <= 0 ) {
965             close($Jobs{$host}{fh});
966             vec($FDread, $Jobs{$host}{fn}, 1) = 0;
967             if ( $CmdJob eq $host ) {
968                 my $cmd = $Jobs{$host}{cmd};
969                 $cmd =~ s/$BinDir\///g;
970                 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
971                 $Status{$host}{state}    = "Status_idle";
972                 $Status{$host}{endTime}  = time;
973                 $CmdJob = "";
974                 $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
975                                             && $RunNightlyWhenIdle );
976             } else {
977                 #
978                 # Queue BackupPC_link to complete the backup
979                 # processing for this host.
980                 #
981                 if ( defined($Status{$host})
982                             && ($Status{$host}{reason} eq "Reason_backup_done"
983                                 || $Status{$host}{needLink}) ) {
984                     QueueLink($host);
985                 } elsif ( defined($Status{$host}) ) {
986                     $Status{$host}{state} = "Status_idle";
987                 }
988             }
989             delete($Jobs{$host});
990             $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
991         }
992     }
993     #
994     # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
995     # do a pass over %Status updating the deadCnt and aliveCnt for
996     # DHCP hosts.  The reason we need to do this later is we can't
997     # be sure whether a DHCP host is alive or dead until we have passed
998     # over all the DHCP pool.
999     #
1000     return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1001     foreach my $host ( keys(%Status) ) {
1002         next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1003         $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1004         $Status{$host}{dhcpCheckCnt} = 0;
1005         if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1006             $Status{$host}{aliveCnt} = 0;
1007         }
1008     }
1009 }
1010
1011 ############################################################################
1012 # Main_Check_Client_Messages($fdRead)
1013 #
1014 # Check for, and process, any output from our clients.  Also checks
1015 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1016 ############################################################################
1017 sub Main_Check_Client_Messages
1018 {
1019     my($fdRead) = @_;
1020     foreach my $client ( keys(%Clients) ) {
1021         next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1022         my($mesg, $host);
1023         #
1024         # do a last check to make sure there is something to read so
1025         # we are absolutely sure we won't block.
1026         #
1027         vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1028         if ( !select($readMask, undef, undef, 0.0) ) {
1029             print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1030                         . " nothing to read from $client.  Debug dump:\n");
1031             my($dump) = Data::Dumper->new(
1032                          [  \%Clients, \%Jobs, \$FDread, \$fdRead],
1033                          [qw(*Clients,  *Jobs   *FDread,  *fdRead)]);
1034             $dump->Indent(1);
1035             print(LOG $dump->Dump);
1036             next;
1037         }
1038         my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1039         $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1040         #
1041         # Process any complete lines received from this client.
1042         #
1043         while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1044             my($reply);
1045             my $cmd = $1;
1046             $Clients{$client}{mesg} = $2;
1047             #
1048             # Authenticate the message by checking the MD5 digest
1049             #
1050             my $md5 = Digest::MD5->new;
1051             if ( $cmd !~ /^(.{22}) (.*)/
1052                 || ($md5->add($Clients{$client}{seed}
1053                             . $Clients{$client}{mesgCnt}
1054                             . $Conf{ServerMesgSecret} . $2),
1055                      $md5->b64digest ne $1) ) {
1056                 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1057                             . " client '$Clients{$client}{clientName}':"
1058                             . " shutting down client connection\n");
1059                 $nbytes = 0;
1060                 last;
1061             }
1062             $Clients{$client}{mesgCnt}++;
1063             $cmd = $2;
1064             if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1065                 $host = $1;
1066                 my $user = $2;
1067                 my $backoff = $3;
1068                 $host = $bpc->uriUnesc($host);
1069                 if ( $CmdJob ne $host && defined($Status{$host})
1070                                       && defined($Jobs{$host}) ) {
1071                     print(LOG $bpc->timeStamp,
1072                                "Stopping current $Jobs{$host}{type} of $host,"
1073                              . " request by $user (backoff=$backoff)\n");
1074                     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1075                     #
1076                     # Don't close the pipe now; wait until the child
1077                     # really exits later.  Otherwise close() will
1078                     # block until the child has exited.
1079                     #  old code:
1080                     ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1081                     ##close($Jobs{$host}{fh});
1082                     ##delete($Jobs{$host});
1083
1084                     $Status{$host}{state}    = "Status_idle";
1085                     if ( $Jobs{$host}{type} eq "restore" ) {
1086                         $Status{$host}{reason}
1087                                     = "Reason_restore_canceled_by_user";
1088                     } elsif ( $Jobs{$host}{type} eq "archive" ) {
1089                         $Status{$host}{reason}
1090                                     = "Reason_archive_canceled_by_user";
1091                     } else {
1092                         $Status{$host}{reason}
1093                                     = "Reason_backup_canceled_by_user";
1094                     }
1095                     $Status{$host}{activeJob} = 0;
1096                     $Status{$host}{startTime} = time;
1097                     $reply = "ok: $Jobs{$host}{type} of $host canceled";
1098                 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1099                     print(LOG $bpc->timeStamp,
1100                                "Stopping pending backup of $host,"
1101                              . " request by $user (backoff=$backoff)\n");
1102                     @BgQueue = grep($_->{host} ne $host, @BgQueue);
1103                     @UserQueue = grep($_->{host} ne $host, @UserQueue);
1104                     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1105                     $reply = "ok: pending backup of $host canceled";
1106                 } else {
1107                     print(LOG $bpc->timeStamp,
1108                                "Nothing to do for stop backup of $host,"
1109                              . " request by $user (backoff=$backoff)\n");
1110                     $reply = "ok: no backup was pending or running";
1111                 }
1112                 if ( defined($Status{$host}) && $backoff ne "" ) {
1113                     if ( $backoff > 0 ) {
1114                         $Status{$host}{backoffTime} = time + $backoff * 3600;
1115                     } else {
1116                         delete($Status{$host}{backoffTime});
1117                     }
1118                 }
1119             } elsif ( $cmd =~ /^backup all$/ ) {
1120                 QueueAllPCs();
1121             } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1122                 my $hostIP = $1;
1123                 $host      = $2;
1124                 my $user   = $3;
1125                 my $doFull = $4;
1126                 $host      = $bpc->uriUnesc($host);
1127                 $hostIP    = $bpc->uriUnesc($hostIP);
1128                 if ( !defined($Status{$host}) ) {
1129                     print(LOG $bpc->timeStamp,
1130                                "User $user requested backup of unknown host"
1131                              . " $host\n");
1132                     $reply = "error: unknown host $host";
1133                 } elsif ( defined($Jobs{$host})
1134                                 && $Jobs{$host}{type} ne "restore" ) {
1135                     print(LOG $bpc->timeStamp,
1136                                "User $user requested backup of $host,"
1137                              . " but one is currently running\n");
1138                     $reply = "error: backup of $host is already running";
1139                 } else {
1140                     print(LOG $bpc->timeStamp,
1141                                "User $user requested backup of $host"
1142                              . " ($hostIP)\n");
1143                     if ( $BgQueueOn{$hostIP} ) {
1144                         @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1145                         $BgQueueOn{$hostIP} = 0;
1146                     }
1147                     if ( $UserQueueOn{$hostIP} ) {
1148                         @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1149                         $UserQueueOn{$hostIP} = 0;
1150                     }
1151                     unshift(@UserQueue, {
1152                                 host    => $hostIP,
1153                                 user    => $user,
1154                                 reqTime => time,
1155                                 doFull  => $doFull,
1156                                 userReq => 1,
1157                                 dhcp    => $hostIP eq $host ? 0 : 1,
1158                         });
1159                     $UserQueueOn{$hostIP} = 1;
1160                     $reply = "ok: requested backup of $host";
1161                 }
1162             } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1163                 my $user         = $1;
1164                 my $archivehost  = $2;
1165                 my $reqFileName  = $3;
1166                 $host      = $bpc->uriUnesc($archivehost);
1167                 if ( !defined($Status{$host}) ) {
1168                     print(LOG $bpc->timeStamp,
1169                                "User $user requested archive of unknown archive host"
1170                              . " $host");
1171                     $reply = "archive error: unknown archive host $host";
1172                 } else {
1173                     print(LOG $bpc->timeStamp,
1174                                "User $user requested archive on $host"
1175                              . " ($host)\n");
1176                     if ( defined($Jobs{$host}) ) {
1177                         $reply = "Archive currently running on $host, please try later";
1178                     } else {
1179                         unshift(@UserQueue, {
1180                                 host    => $host,
1181                                 hostIP  => $user,
1182                                 reqFileName => $reqFileName,
1183                                 reqTime => time,
1184                                 dhcp    => 0,
1185                                 archive => 1,
1186                                 userReq => 1,
1187                         });
1188                         $UserQueueOn{$host} = 1;
1189                         $reply = "ok: requested archive on $host";
1190                     }
1191                 }
1192             } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1193                 my $hostIP = $1;
1194                 $host      = $2;
1195                 my $user   = $3;
1196                 my $reqFileName = $4;
1197                 $host      = $bpc->uriUnesc($host);
1198                 $hostIP    = $bpc->uriUnesc($hostIP);
1199                 if ( !defined($Status{$host}) ) {
1200                     print(LOG $bpc->timeStamp,
1201                                "User $user requested restore to unknown host"
1202                              . " $host");
1203                     $reply = "restore error: unknown host $host";
1204                 } else {
1205                     print(LOG $bpc->timeStamp,
1206                                "User $user requested restore to $host"
1207                              . " ($hostIP)\n");
1208                     unshift(@UserQueue, {
1209                                 host    => $host,
1210                                 hostIP  => $hostIP,
1211                                 reqFileName => $reqFileName,
1212                                 reqTime => time,
1213                                 dhcp    => 0,
1214                                 restore => 1,
1215                                 userReq => 1,
1216                         });
1217                     $UserQueueOn{$host} = 1;
1218                     if ( defined($Jobs{$host}) ) {
1219                         $reply = "ok: requested restore of $host, but a"
1220                                . " job is currently running,"
1221                                . " so this request will start later";
1222                     } else {
1223                         $reply = "ok: requested restore of $host";
1224                     }
1225                 }
1226             } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1227                 my($args) = $1;
1228                 my($dump, @values, @names);
1229                 foreach my $type ( split(/\s+/, $args) ) {
1230                     if ( $type =~ /^queues/ ) {
1231                         push(@values,  \@BgQueue, \@UserQueue, \@CmdQueue);
1232                         push(@names, qw(*BgQueue   *UserQueue   *CmdQueue));
1233                     } elsif ( $type =~ /^jobs/ ) {
1234                         push(@values,  \%Jobs);
1235                         push(@names, qw(*Jobs));
1236                     } elsif ( $type =~ /^queueLen/ ) {
1237                         push(@values,  {
1238                                 BgQueue   => scalar(@BgQueue),
1239                                 UserQueue => scalar(@UserQueue),
1240                                 CmdQueue  => scalar(@CmdQueue),
1241                             });
1242                         push(@names, qw(*QueueLen));
1243                     } elsif ( $type =~ /^info/ ) {
1244                         push(@values,  \%Info);
1245                         push(@names, qw(*Info));
1246                     } elsif ( $type =~ /^hosts/ ) {
1247                         push(@values,  \%Status);
1248                         push(@names, qw(*Status));
1249                     } elsif ( $type =~ /^host\((.*)\)/ ) {
1250                         my $h = $bpc->uriUnesc($1);
1251                         if ( defined($Status{$h}) ) {
1252                             push(@values,  {
1253                                     %{$Status{$h}},
1254                                     BgQueueOn => $BgQueueOn{$h},
1255                                     UserQueueOn => $UserQueueOn{$h},
1256                                     CmdQueueOn => $CmdQueueOn{$h},
1257                                 });
1258                             push(@names, qw(*StatusHost));
1259                         } else {
1260                             print(LOG $bpc->timeStamp,
1261                                       "Unknown host $h for status request\n");
1262                         }
1263                     } else {
1264                         print(LOG $bpc->timeStamp,
1265                                   "Unknown status request $type\n");
1266                     }
1267                 }
1268                 $dump = Data::Dumper->new(\@values, \@names);
1269                 $dump->Indent(0);
1270                 $reply = $dump->Dump;
1271             } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1272                 my($host) = $1;
1273                 $host = $bpc->uriUnesc($host);
1274                 QueueLink($host);
1275             } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1276                 print(LOG $bpc->timeStamp, "$1\n");
1277             } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1278                 my($type) = $1;
1279                 if ( $type eq 'reload' ) {
1280                     ServerReload("Reloading config/host files via CGI request");
1281                 } elsif ( $type eq 'shutdown' ) {
1282                     $reply = "Shutting down...\n";
1283                     syswrite($Clients{$client}{fh}, $reply, length($reply));
1284                     ServerShutdown("Server shutting down...");
1285                 }
1286             } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1287                 $nbytes = 0;
1288                 last;
1289             } else {
1290                 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1291                 $reply = "error: bad command $cmd";
1292             }
1293             #
1294             # send a reply to the client, at a minimum "ok\n".
1295             #
1296             $reply = "ok" if ( $reply eq "" );
1297             $reply .= "\n";
1298             syswrite($Clients{$client}{fh}, $reply, length($reply));
1299         }
1300         #
1301         # Detect possible denial-of-service attack from sending a huge line
1302         # (ie: never terminated).  32K seems to be plenty big enough as
1303         # a limit.
1304         #
1305         if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1306             print(LOG $bpc->timeStamp, "Line too long from client"
1307                         . " '$Clients{$client}{clientName}':"
1308                         . " shutting down client connection\n");
1309             $nbytes = 0;
1310         }
1311         #
1312         # Shut down the client connection if we read EOF
1313         #
1314         if ( $nbytes <= 0 ) {
1315             close($Clients{$client}{fh});
1316             vec($FDread, $Clients{$client}{fn}, 1) = 0;
1317             delete($Clients{$client});
1318         }
1319     }
1320     #
1321     # Accept any new connections on each of our listen sockets
1322     #
1323     if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1324         local(*CLIENT);
1325         my $paddr = accept(CLIENT, SERVER_UNIX);
1326         $ClientConnCnt++;
1327         $Clients{$ClientConnCnt}{clientName} = "unix socket";
1328         $Clients{$ClientConnCnt}{mesg} = "";
1329         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1330         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
1331         vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1332         #
1333         # Generate and send unique seed for MD5 digests to avoid
1334         # replay attacks.  See BackupPC::Lib::ServerMesg().
1335         #
1336         my $seed = time . ",$ClientConnCnt,$$,0\n";
1337         $Clients{$ClientConnCnt}{seed}    = $seed;
1338         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1339         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1340     }
1341     if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1342         local(*CLIENT);
1343         my $paddr = accept(CLIENT, SERVER_INET);
1344         my($port,$iaddr) = sockaddr_in($paddr); 
1345         my $name = gethostbyaddr($iaddr, AF_INET);
1346         $ClientConnCnt++;
1347         $Clients{$ClientConnCnt}{mesg} = "";
1348         $Clients{$ClientConnCnt}{fh}   = *CLIENT;
1349         $Clients{$ClientConnCnt}{fn}   = fileno(CLIENT);
1350         $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1351         vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1352         #
1353         # Generate and send unique seed for MD5 digests to avoid
1354         # replay attacks.  See BackupPC::Lib::ServerMesg().
1355         #
1356         my $seed = time . ",$ClientConnCnt,$$,$port\n";
1357         $Clients{$ClientConnCnt}{seed}    = $seed;
1358         $Clients{$ClientConnCnt}{mesgCnt} = 0;
1359         syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1360     }
1361 }
1362
1363 ###########################################################################
1364 # Miscellaneous subroutines
1365 ###########################################################################
1366
1367 #
1368 # Write the current status to $TopDir/log/status.pl
1369 #
1370 sub StatusWrite
1371 {
1372     my($dump) = Data::Dumper->new(
1373              [  \%Info, \%Status],
1374              [qw(*Info   *Status)]);
1375     $dump->Indent(1);
1376     if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1377         print(STATUS $dump->Dump);
1378         close(STATUS);
1379     }
1380 }
1381
1382 #
1383 # Queue all the hosts for backup.  This means queuing all the fixed
1384 # ip hosts and all the dhcp address ranges.  We also additionally
1385 # queue the dhcp hosts with a -e flag to check for expired dumps.
1386 #
1387 sub QueueAllPCs
1388 {
1389     foreach my $host ( sort(keys(%$Hosts)) ) {
1390         delete($Status{$host}{backoffTime})
1391                 if ( defined($Status{$host}{backoffTime})
1392                   && $Status{$host}{backoffTime} < time );
1393         next if ( defined($Jobs{$host})
1394                 || $BgQueueOn{$host}
1395                 || $UserQueueOn{$host}
1396                 || $CmdQueueOn{$host} ); 
1397         if ( $Hosts->{$host}{dhcp} ) {
1398             $Status{$host}{dhcpCheckCnt}++;
1399             if ( $RunNightlyWhenIdle ) {
1400                 #
1401                 # Once per night queue a check for DHCP hosts that just
1402                 # checks for expired dumps.  We need to do this to handle
1403                 # the case when a DHCP host has not been on the network for
1404                 # a long time, and some of the old dumps need to be expired.
1405                 # Normally expiry checks are done by BackupPC_dump only
1406                 # after the DHCP hosts has been detected on the network.
1407                 #
1408                 unshift(@BgQueue,
1409                     {host => $host, user => "BackupPC", reqTime => time,
1410                      dhcp => 0, dumpExpire => 1});
1411                 $BgQueueOn{$host} = 1;
1412             }
1413         } else {
1414             #
1415             # this is a fixed ip host: queue it
1416             #
1417             unshift(@BgQueue,
1418                 {host => $host, user => "BackupPC", reqTime => time,
1419                  dhcp => $Hosts->{$host}{dhcp}});
1420             $BgQueueOn{$host} = 1;
1421         }
1422     }
1423     foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1424         for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1425             my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1426             next if ( defined($Jobs{$ipAddr})
1427                     || $BgQueueOn{$ipAddr}
1428                     || $UserQueueOn{$ipAddr}
1429                     || $CmdQueueOn{$ipAddr} ); 
1430             #
1431             # this is a potential dhcp ip address (we don't know the
1432             # host name yet): queue it
1433             #
1434             unshift(@BgQueue,
1435                 {host => $ipAddr, user => "BackupPC", reqTime => time,
1436                  dhcp => 1});
1437             $BgQueueOn{$ipAddr} = 1;
1438         }
1439     }
1440 }
1441
1442 #
1443 # Queue a BackupPC_link for the given host
1444 #
1445 sub QueueLink
1446 {
1447     my($host) = @_;
1448
1449     return if ( $CmdQueueOn{$host} );
1450     $Status{$host}{state}    = "Status_link_pending";
1451     $Status{$host}{needLink} = 0;
1452     unshift(@CmdQueue, {
1453             host    => $host,
1454             user    => "BackupPC",
1455             reqTime => time,
1456             cmd     => ["$BinDir/BackupPC_link",  $host],
1457         });
1458     $CmdQueueOn{$host} = 1;
1459 }
1460
1461 #
1462 # Read the hosts file, and update Status if any hosts have been
1463 # added or deleted.  We also track the mtime so the only need to
1464 # update the hosts file on changes.
1465 #
1466 # This function is called at startup, SIGHUP, and on each wakeup.
1467 # It returns 1 on success and undef on failure.
1468 #
1469 sub HostsUpdate
1470 {
1471     my($force) = @_;
1472     my $newHosts;
1473     #
1474     # Nothing to do if we already have the current hosts file
1475     #
1476     return 1 if ( !$force && defined($Hosts)
1477                           && $Info{HostsModTime} == $bpc->HostsMTime() );
1478     if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1479         print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1480         return;
1481     }
1482     print(LOG $bpc->timeStamp, "Reading hosts file\n");
1483     $Hosts = $newHosts;
1484     $Info{HostsModTime} = $bpc->HostsMTime();
1485     #
1486     # Now update %Status in case any hosts have been added or deleted
1487     #
1488     foreach my $host ( sort(keys(%$Hosts)) ) {
1489         next if ( defined($Status{$host}) );
1490         $Status{$host}{state} = "Status_idle";
1491         print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1492     }
1493     foreach my $host ( sort(keys(%Status)) ) {
1494         next if ( $host eq $bpc->trashJob
1495                      || $host eq $bpc->adminJob
1496                      || defined($Hosts->{$host})
1497                      || defined($Jobs{$host})
1498                      || $BgQueueOn{$host}
1499                      || $UserQueueOn{$host}
1500                      || $CmdQueueOn{$host} );
1501         print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1502         delete($Status{$host});
1503     }
1504     return 1;
1505 }
1506
1507 #
1508 # Remember the signal name for later processing
1509 #
1510 sub catch_signal
1511 {
1512     if ( $SigName ) {
1513         $SigName = shift;
1514         foreach my $host ( keys(%Jobs) ) {
1515             kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1516         }
1517         #
1518         # In case we are inside the exit handler, reopen the log file
1519         #
1520         close(LOG);
1521         LogFileOpen();
1522         print(LOG "Fatal error: unhandled signal $SigName\n");
1523         unlink("$TopDir/log/BackupPC.pid");
1524         confess("Got new signal $SigName... quitting\n");
1525     } else {
1526         $SigName = shift;
1527     }
1528 }
1529
1530 #
1531 # Open the log file and point STDOUT and STDERR there too
1532 #
1533 sub LogFileOpen
1534 {
1535     mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1536     open(LOG, ">>$TopDir/log/LOG")
1537             || die("Can't create LOG file $TopDir/log/LOG");
1538     close(STDOUT);
1539     close(STDERR);
1540     open(STDOUT, ">&LOG");
1541     open(STDERR, ">&LOG");
1542     select(LOG);    $| = 1;
1543     select(STDERR); $| = 1;
1544     select(STDOUT); $| = 1;
1545 }
1546
1547 #
1548 # Initialize the unix-domain and internet-domain sockets that
1549 # we listen to for client connections (from the CGI script and
1550 # some of the BackupPC sub-programs).
1551 #
1552 sub ServerSocketInit
1553 {
1554     if ( !defined(fileno(SERVER_UNIX)) ) {
1555         #
1556         # one-time only: initialize unix-domain socket
1557         #
1558         if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1559             print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1560             exit(1);
1561         }
1562         my $sockFile = "$TopDir/log/BackupPC.sock";
1563         unlink($sockFile);
1564         if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1565             print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1566             exit(1);
1567         }
1568         if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1569             print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1570             exit(1);
1571         }
1572         vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1573     }
1574     return if ( $ServerInetPort == $Conf{ServerPort} );
1575     if ( $ServerInetPort > 0 ) {
1576         vec($FDread, fileno(SERVER_INET), 1) = 0;
1577         close(SERVER_INET);
1578         $ServerInetPort = -1;
1579     }
1580     if ( $Conf{ServerPort} > 0 ) {
1581         #
1582         # Setup a socket to listen on $Conf{ServerPort}
1583         #
1584         my $proto = getprotobyname('tcp');
1585         if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1586             print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1587             exit(1);
1588         }
1589         if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1590             print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1591             exit(1);
1592         }
1593         if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1594             print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1595             exit(1);
1596         }
1597         if ( !listen(SERVER_INET, SOMAXCONN) ) {
1598             print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1599             exit(1);
1600         }
1601         vec($FDread, fileno(SERVER_INET), 1) = 1;
1602         $ServerInetPort = $Conf{ServerPort};
1603     }
1604 }
1605
1606 #
1607 # Reload the server.  Used by Main_Process_Signal when $SigName eq "HUP"
1608 # or when the command "server reload" is received.
1609 #
1610 sub ServerReload
1611 {
1612     my($mesg) = @_;
1613     $mesg = $bpc->ConfigRead() || $mesg;
1614     print(LOG $bpc->timeStamp, "$mesg\n");
1615     $Info{ConfigModTime} = $bpc->ConfigMTime();
1616     %Conf = $bpc->Conf();
1617     umask($Conf{UmaskMode});
1618     ServerSocketInit();
1619     HostsUpdate(0);
1620     $NextWakeup = 0;
1621     $Info{ConfigLTime} = time;
1622 }
1623
1624 #
1625 # Gracefully shutdown the server.  Used by Main_Process_Signal when
1626 # $SigName ne "" && $SigName ne "HUP" or when the command
1627 # "server shutdown" is received.
1628 #
1629 sub ServerShutdown
1630 {
1631     my($mesg) = @_;
1632     print(LOG $bpc->timeStamp, "$mesg\n");
1633     if ( keys(%Jobs) ) {
1634         foreach my $host ( keys(%Jobs) ) {
1635             kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1636         }
1637         sleep(1);
1638         foreach my $host ( keys(%Jobs) ) {
1639             kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1640         }
1641         %Jobs = ();
1642     }
1643     StatusWrite();
1644     unlink("$TopDir/log/BackupPC.pid");
1645     exit(1);
1646 }
1647