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