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