86a3b3f74c3d884189038a5d1309ebb9fa8bdf98
[BackupPC.git] / lib / BackupPC / Lib.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Lib package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Lib class and a variety of utility
8 #   functions used by BackupPC.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001-2003  Craig Barratt
15 #
16 #   This program is free software; you can redistribute it and/or modify
17 #   it under the terms of the GNU General Public License as published by
18 #   the Free Software Foundation; either version 2 of the License, or
19 #   (at your option) any later version.
20 #
21 #   This program is distributed in the hope that it will be useful,
22 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
23 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 #   GNU General Public License for more details.
25 #
26 #   You should have received a copy of the GNU General Public License
27 #   along with this program; if not, write to the Free Software
28 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 #
30 #========================================================================
31 #
32 # Version 3.0.0beta2, released 11 Nov 2006.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Lib;
39
40 use strict;
41
42 use vars qw(%Conf %Lang);
43 use BackupPC::Storage;
44 use Fcntl qw/:flock/;
45 use Carp;
46 use DirHandle ();
47 use File::Path;
48 use File::Compare;
49 use Socket;
50 use Cwd;
51 use Digest::MD5;
52 use Config;
53
54 sub new
55 {
56     my $class = shift;
57     my($topDir, $installDir, $confDir, $noUserCheck) = @_;
58
59     #
60     # Whether to use filesystem hierarchy standard for file layout.
61     # If set, text config files are below /etc/BackupPC.
62     #
63     my $useFHS = 0;
64     my $paths;
65
66     #
67     # Set defaults for $topDir and $installDir.
68     #
69     $topDir     = '/tera0/backup/BackupPC' if ( $topDir eq "" );
70     $installDir = '/usr/local/BackupPC'    if ( $installDir eq "" );
71
72     #
73     # Pick some initial defaults.  For FHS the only critical
74     # path is the ConfDir, since we get everything else out
75     # of the main config file.
76     #
77     if ( $useFHS ) {
78         $paths = {
79             useFHS     => $useFHS,
80             TopDir     => $topDir,
81             InstallDir => $installDir,
82             ConfDir    => $confDir eq "" ? '/etc/BackupPC' : $confDir,
83             LogDir     => '/var/log/BackupPC',
84         };
85     } else {
86         $paths = {
87             useFHS     => $useFHS,
88             TopDir     => $topDir,
89             InstallDir => $installDir,
90             ConfDir    => $confDir eq "" ? "$topDir/conf" : $confDir,
91             LogDir     => "$topDir/log",
92         };
93     }
94
95     my $bpc = bless {
96         %$paths,
97         Version => '3.0.0beta2',
98     }, $class;
99
100     $bpc->{storage} = BackupPC::Storage->new($paths);
101
102     #
103     # Clean up %ENV and setup other variables.
104     #
105     delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
106     $bpc->{PoolDir}  = "$bpc->{TopDir}/pool";
107     $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
108     if ( defined(my $error = $bpc->ConfigRead()) ) {
109         print(STDERR $error, "\n");
110         return;
111     }
112
113     #
114     # Update the paths based on the config file
115     #
116     foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
117         next if ( $bpc->{Conf}{$dir} eq "" );
118         $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
119     }
120     $bpc->{storage}->setPaths($paths);
121
122     #
123     # Verify we are running as the correct user
124     #
125     if ( !$noUserCheck
126             && $bpc->{Conf}{BackupPCUserVerify}
127             && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
128         print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
129             . " ($bpc->{Conf}{BackupPCUser})\n");
130         print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
131         return;
132     }
133     return $bpc;
134 }
135
136 sub TopDir
137 {
138     my($bpc) = @_;
139     return $bpc->{TopDir};
140 }
141
142 sub BinDir
143 {
144     my($bpc) = @_;
145     return "$bpc->{InstallDir}/bin";
146 }
147
148 sub LogDir
149 {
150     my($bpc) = @_;
151     return $bpc->{LogDir};
152 }
153
154 sub ConfDir
155 {
156     my($bpc) = @_;
157     return $bpc->{ConfDir};
158 }
159
160 sub LibDir
161 {
162     my($bpc) = @_;
163     return "$bpc->{InstallDir}/lib";
164 }
165
166 sub InstallDir
167 {
168     my($bpc) = @_;
169     return $bpc->{InstallDir};
170 }
171
172 sub useFHS
173 {
174     my($bpc) = @_;
175     return $bpc->{useFHS};
176 }
177
178 sub Version
179 {
180     my($bpc) = @_;
181     return $bpc->{Version};
182 }
183
184 sub Conf
185 {
186     my($bpc) = @_;
187     return %{$bpc->{Conf}};
188 }
189
190 sub Lang
191 {
192     my($bpc) = @_;
193     return $bpc->{Lang};
194 }
195
196 sub adminJob
197 {
198     my($bpc, $num) = @_;
199     return " admin " if ( !$num );
200     return " admin$num ";
201 }
202
203 sub isAdminJob
204 {
205     my($bpc, $str) = @_;
206     return $str =~ /^ admin/;
207 }
208
209 sub trashJob
210 {
211     return " trashClean ";
212 }
213
214 sub ConfValue
215 {
216     my($bpc, $param) = @_;
217
218     return $bpc->{Conf}{$param};
219 }
220
221 sub verbose
222 {
223     my($bpc, $param) = @_;
224
225     $bpc->{verbose} = $param if ( defined($param) );
226     return $bpc->{verbose};
227 }
228
229 sub sigName2num
230 {
231     my($bpc, $sig) = @_;
232
233     if ( !defined($bpc->{SigName2Num}) ) {
234         my $i = 0;
235         foreach my $name ( split(' ', $Config{sig_name}) ) {
236             $bpc->{SigName2Num}{$name} = $i;
237             $i++;
238         }
239     }
240     return $bpc->{SigName2Num}{$sig};
241 }
242
243 #
244 # Generate an ISO 8601 format timeStamp (but without the "T").
245 # See http://www.w3.org/TR/NOTE-datetime and
246 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
247 #
248 sub timeStamp
249 {
250     my($bpc, $t, $noPad) = @_;
251     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
252               = localtime($t || time);
253     return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
254                     $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
255              . ($noPad ? "" : " ");
256 }
257
258 sub BackupInfoRead
259 {
260     my($bpc, $host) = @_;
261
262     return $bpc->{storage}->BackupInfoRead($host);
263 }
264
265 sub BackupInfoWrite
266 {
267     my($bpc, $host, @Backups) = @_;
268
269     return $bpc->{storage}->BackupInfoWrite($host, @Backups);
270 }
271
272 sub RestoreInfoRead
273 {
274     my($bpc, $host) = @_;
275
276     return $bpc->{storage}->RestoreInfoRead($host);
277 }
278
279 sub RestoreInfoWrite
280 {
281     my($bpc, $host, @Restores) = @_;
282
283     return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
284 }
285
286 sub ArchiveInfoRead
287 {
288     my($bpc, $host) = @_;
289
290     return $bpc->{storage}->ArchiveInfoRead($host);
291 }
292
293 sub ArchiveInfoWrite
294 {
295     my($bpc, $host, @Archives) = @_;
296
297     return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
298 }
299
300 sub ConfigDataRead
301 {
302     my($bpc, $host) = @_;
303
304     return $bpc->{storage}->ConfigDataRead($host);
305 }
306
307 sub ConfigDataWrite
308 {
309     my($bpc, $host, $conf) = @_;
310
311     return $bpc->{storage}->ConfigDataWrite($host, $conf);
312 }
313
314 sub ConfigRead
315 {
316     my($bpc, $host) = @_;
317     my($ret);
318
319     #
320     # Read main config file
321     #
322     my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
323     return $mesg if ( defined($mesg) );
324
325     $bpc->{Conf} = $config;
326
327     #
328     # Read host config file
329     #
330     if ( $host ne "" ) {
331         ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
332         return $mesg if ( defined($mesg) );
333         $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
334     }
335
336     #
337     # Load optional perl modules
338     #
339     if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
340         #
341         # Load any user-specified perl modules.  This is for
342         # optional user-defined extensions.
343         #
344         $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
345                     if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
346         foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
347             eval("use $module;");
348         }
349     }
350
351     #
352     # Load language file
353     #
354     return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
355     my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
356     if ( !defined($ret = do $langFile) && ($! || $@) ) {
357         $mesg = "Couldn't open language file $langFile: $!" if ( $! );
358         $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
359         $mesg =~ s/[\n\r]+//;
360         return $mesg;
361     }
362     $bpc->{Lang} = \%Lang;
363     return;
364 }
365
366 #
367 # Return the mtime of the config file
368 #
369 sub ConfigMTime
370 {
371     my($bpc) = @_;
372
373     return $bpc->{storage}->ConfigMTime();
374 }
375
376 #
377 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
378 # With no argument a ref to a hash of hosts is returned.  Each
379 # hash contains fields as specified in the hosts file.  With an
380 # argument a ref to a single hash is returned with information
381 # for just that host.
382 #
383 sub HostInfoRead
384 {
385     my($bpc, $host) = @_;
386
387     return $bpc->{storage}->HostInfoRead($host);
388 }
389
390 sub HostInfoWrite
391 {
392     my($bpc, $host) = @_;
393
394     return $bpc->{storage}->HostInfoWrite($host);
395 }
396
397 #
398 # Return the mtime of the hosts file
399 #
400 sub HostsMTime
401 {
402     my($bpc) = @_;
403
404     return $bpc->{storage}->HostsMTime();
405 }
406
407 #
408 # Stripped down from File::Path.  In particular we don't print
409 # many warnings and we try three times to delete each directory
410 # and file -- for some reason the original File::Path rmtree
411 # didn't always completely remove a directory tree on the NetApp.
412 #
413 # Warning: this routine changes the cwd.
414 #
415 sub RmTreeQuiet
416 {
417     my($bpc, $pwd, $roots) = @_;
418     my(@files, $root);
419
420     if ( defined($roots) && length($roots) ) {
421       $roots = [$roots] unless ref $roots;
422     } else {
423       print(STDERR "RmTreeQuiet: No root path(s) specified\n");
424     }
425     chdir($pwd);
426     foreach $root (@{$roots}) {
427         $root = $1 if ( $root =~ m{(.*?)/*$} );
428         #
429         # Try first to simply unlink the file: this avoids an
430         # extra stat for every file.  If it fails (which it
431         # will for directories), check if it is a directory and
432         # then recurse.
433         #
434         if ( !unlink($root) ) {
435             if ( -d $root ) {
436                 my $d = DirHandle->new($root);
437                 if ( !defined($d) ) {
438                     print(STDERR "Can't read $pwd/$root: $!\n");
439                 } else {
440                     @files = $d->read;
441                     $d->close;
442                     @files = grep $_!~/^\.{1,2}$/, @files;
443                     $bpc->RmTreeQuiet("$pwd/$root", \@files);
444                     chdir($pwd);
445                     rmdir($root) || rmdir($root);
446                 }
447             } else {
448                 unlink($root) || unlink($root);
449             }
450         }
451     }
452 }
453
454 #
455 # Move a directory or file away for later deletion
456 #
457 sub RmTreeDefer
458 {
459     my($bpc, $trashDir, $file) = @_;
460     my($i, $f);
461
462     return if ( !-e $file );
463     mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
464     for ( $i = 0 ; $i < 1000 ; $i++ ) {
465         $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
466         next if ( -e $f );
467         return if ( rename($file, $f) );
468     }
469     # shouldn't get here, but might if you tried to call this
470     # across file systems.... just remove the tree right now.
471     if ( $file =~ /(.*)\/([^\/]*)/ ) {
472         my($d) = $1;
473         my($f) = $2;
474         my($cwd) = Cwd::fastcwd();
475         $cwd = $1 if ( $cwd =~ /(.*)/ );
476         $bpc->RmTreeQuiet($d, $f);
477         chdir($cwd) if ( $cwd );
478     }
479 }
480
481 #
482 # Empty the trash directory.  Returns 0 if it did nothing, 1 if it
483 # did something, -1 if it failed to remove all the files.
484 #
485 sub RmTreeTrashEmpty
486 {
487     my($bpc, $trashDir) = @_;
488     my(@files);
489     my($cwd) = Cwd::fastcwd();
490
491     $cwd = $1 if ( $cwd =~ /(.*)/ );
492     return if ( !-d $trashDir );
493     my $d = DirHandle->new($trashDir) or carp "Can't read $trashDir: $!";
494     @files = $d->read;
495     $d->close;
496     @files = grep $_!~/^\.{1,2}$/, @files;
497     return 0 if ( !@files );
498     $bpc->RmTreeQuiet($trashDir, \@files);
499     foreach my $f ( @files ) {
500         return -1 if ( -e $f );
501     }
502     chdir($cwd) if ( $cwd );
503     return 1;
504 }
505
506 #
507 # Open a connection to the server.  Returns an error string on failure.
508 # Returns undef on success.
509 #
510 sub ServerConnect
511 {
512     my($bpc, $host, $port, $justConnect) = @_;
513     local(*FH);
514
515     return if ( defined($bpc->{ServerFD}) );
516     #
517     # First try the unix-domain socket
518     #
519     my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
520     socket(*FH, PF_UNIX, SOCK_STREAM, 0)     || return "unix socket: $!";
521     if ( !connect(*FH, sockaddr_un($sockFile)) ) {
522         my $err = "unix connect: $!";
523         close(*FH);
524         if ( $port > 0 ) {
525             my $proto = getprotobyname('tcp');
526             my $iaddr = inet_aton($host)     || return "unknown host $host";
527             my $paddr = sockaddr_in($port, $iaddr);
528
529             socket(*FH, PF_INET, SOCK_STREAM, $proto)
530                                              || return "inet socket: $!";
531             connect(*FH, $paddr)             || return "inet connect: $!";
532         } else {
533             return $err;
534         }
535     }
536     my($oldFH) = select(*FH); $| = 1; select($oldFH);
537     $bpc->{ServerFD} = *FH;
538     return if ( $justConnect );
539     #
540     # Read the seed that we need for our MD5 message digest.  See
541     # ServerMesg below.
542     #
543     sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
544     $bpc->{ServerMesgCnt} = 0;
545     return;
546 }
547
548 #
549 # Check that the server connection is still ok
550 #
551 sub ServerOK
552 {
553     my($bpc) = @_;
554
555     return 0 if ( !defined($bpc->{ServerFD}) );
556     vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
557     my $ein = $FDread;
558     return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
559     return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
560 }
561
562 #
563 # Disconnect from the server
564 #
565 sub ServerDisconnect
566 {
567     my($bpc) = @_;
568     return if ( !defined($bpc->{ServerFD}) );
569     close($bpc->{ServerFD});
570     delete($bpc->{ServerFD});
571 }
572
573 #
574 # Sends a message to the server and returns with the reply.
575 #
576 # To avoid possible attacks via the TCP socket interface, every client
577 # message is protected by an MD5 digest. The MD5 digest includes four
578 # items:
579 #   - a seed that is sent to us when we first connect
580 #   - a sequence number that increments for each message
581 #   - a shared secret that is stored in $Conf{ServerMesgSecret}
582 #   - the message itself.
583 # The message is sent in plain text preceded by the MD5 digest. A
584 # snooper can see the plain-text seed sent by BackupPC and plain-text
585 # message, but cannot construct a valid MD5 digest since the secret in
586 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
587 # since the seed changes on a per-connection and per-message basis.
588 #
589 sub ServerMesg
590 {
591     my($bpc, $mesg) = @_;
592     return if ( !defined(my $fh = $bpc->{ServerFD}) );
593     my $md5 = Digest::MD5->new;
594     $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
595             . $bpc->{Conf}{ServerMesgSecret} . $mesg);
596     print($fh $md5->b64digest . " $mesg\n");
597     $bpc->{ServerMesgCnt}++;
598     return <$fh>;
599 }
600
601 #
602 # Do initialization for child processes
603 #
604 sub ChildInit
605 {
606     my($bpc) = @_;
607     close(STDERR);
608     open(STDERR, ">&STDOUT");
609     select(STDERR); $| = 1;
610     select(STDOUT); $| = 1;
611     $ENV{PATH} = $bpc->{Conf}{MyPath};
612 }
613
614 #
615 # Compute the MD5 digest of a file.  For efficiency we don't
616 # use the whole file for big files:
617 #   - for files <= 256K we use the file size and the whole file.
618 #   - for files <= 1M we use the file size, the first 128K and
619 #     the last 128K.
620 #   - for files > 1M, we use the file size, the first 128K and
621 #     the 8th 128K (ie: the 128K up to 1MB).
622 # See the documentation for a discussion of the tradeoffs in
623 # how much data we use and how many collisions we get.
624 #
625 # Returns the MD5 digest (a hex string) and the file size.
626 #
627 sub File2MD5
628 {
629     my($bpc, $md5, $name) = @_;
630     my($data, $fileSize);
631     local(*N);
632
633     $fileSize = (stat($name))[7];
634     return ("", -1) if ( !-f _ );
635     $name = $1 if ( $name =~ /(.*)/ );
636     return ("", 0) if ( $fileSize == 0 );
637     return ("", -1) if ( !open(N, $name) );
638     binmode(N);
639     $md5->reset();
640     $md5->add($fileSize);
641     if ( $fileSize > 262144 ) {
642         #
643         # read the first and last 131072 bytes of the file,
644         # up to 1MB.
645         #
646         my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
647         $md5->add($data) if ( sysread(N, $data, 131072) );
648         $md5->add($data) if ( sysseek(N, $seekPosn, 0)
649                                 && sysread(N, $data, 131072) );
650     } else {
651         #
652         # read the whole file
653         #
654         $md5->add($data) if ( sysread(N, $data, $fileSize) );
655     }
656     close(N);
657     return ($md5->hexdigest, $fileSize);
658 }
659
660 #
661 # Compute the MD5 digest of a buffer (string).  For efficiency we don't
662 # use the whole string for big strings:
663 #   - for files <= 256K we use the file size and the whole file.
664 #   - for files <= 1M we use the file size, the first 128K and
665 #     the last 128K.
666 #   - for files > 1M, we use the file size, the first 128K and
667 #     the 8th 128K (ie: the 128K up to 1MB).
668 # See the documentation for a discussion of the tradeoffs in
669 # how much data we use and how many collisions we get.
670 #
671 # Returns the MD5 digest (a hex string).
672 #
673 sub Buffer2MD5
674 {
675     my($bpc, $md5, $fileSize, $dataRef) = @_;
676
677     $md5->reset();
678     $md5->add($fileSize);
679     if ( $fileSize > 262144 ) {
680         #
681         # add the first and last 131072 bytes of the string,
682         # up to 1MB.
683         #
684         my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
685         $md5->add(substr($$dataRef, 0, 131072));
686         $md5->add(substr($$dataRef, $seekPosn, 131072));
687     } else {
688         #
689         # add the whole string
690         #
691         $md5->add($$dataRef);
692     }
693     return $md5->hexdigest;
694 }
695
696 #
697 # Given an MD5 digest $d and a compress flag, return the full
698 # path in the pool.
699 #
700 sub MD52Path
701 {
702     my($bpc, $d, $compress, $poolDir) = @_;
703
704     return if ( $d !~ m{(.)(.)(.)(.*)} );
705     $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
706                     if ( !defined($poolDir) );
707     return "$poolDir/$1/$2/$3/$1$2$3$4";
708 }
709
710 #
711 # For each file, check if the file exists in $bpc->{TopDir}/pool.
712 # If so, remove the file and make a hardlink to the file in
713 # the pool.  Otherwise, if the newFile flag is set, make a
714 # hardlink in the pool to the new file.
715 #
716 # Returns 0 if a link should be made to a new file (ie: when the file
717 #    is a new file but the newFile flag is 0).
718 # Returns 1 if a link to an existing file is made,
719 # Returns 2 if a link to a new file is made (only if $newFile is set)
720 # Returns negative on error.
721 #
722 sub MakeFileLink
723 {
724     my($bpc, $name, $d, $newFile, $compress) = @_;
725     my($i, $rawFile);
726
727     return -1 if ( !-f $name );
728     for ( $i = -1 ; ; $i++ ) {
729         return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
730         $rawFile .= "_$i" if ( $i >= 0 );
731         if ( -f $rawFile ) {
732             if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
733                     && !compare($name, $rawFile) ) {
734                 unlink($name);
735                 return -3 if ( !link($rawFile, $name) );
736                 return 1;
737             }
738         } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
739             my($newDir);
740             ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
741             mkpath($newDir, 0, 0777) if ( !-d $newDir );
742             return -4 if ( !link($name, $rawFile) );
743             return 2;
744         } else {
745             return 0;
746         }
747     }
748 }
749
750 sub CheckHostAlive
751 {
752     my($bpc, $host) = @_;
753     my($s, $pingCmd, $ret);
754
755     #
756     # Return success if the ping cmd is undefined or empty.
757     #
758     if ( $bpc->{Conf}{PingCmd} eq "" ) {
759         print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
760                    . " is empty\n") if ( $bpc->{verbose} );
761         return 0;
762     }
763
764     my $args = {
765         pingPath => $bpc->{Conf}{PingPath},
766         host     => $host,
767     };
768     $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
769
770     #
771     # Do a first ping in case the PC needs to wakeup
772     #
773     $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
774     if ( $? ) {
775         print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
776                         if ( $bpc->{verbose} );
777         return -1;
778     }
779
780     #
781     # Do a second ping and get the round-trip time in msec
782     #
783     $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
784     if ( $? ) {
785         print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
786                         if ( $bpc->{verbose} );
787         return -1;
788     }
789     if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
790         $ret = $1;
791         $ret /= 1000 if ( lc($2) eq "usec" );
792     } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
793         $ret = $1;
794         $ret /= 1000 if ( lc($2) eq "usec" );
795     } else {
796         print(STDERR "CheckHostAlive: can't extract round-trip time"
797                    . " (not fatal)\n") if ( $bpc->{verbose} );
798         $ret = 0;
799     }
800     print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
801     return $ret;
802 }
803
804 sub CheckFileSystemUsage
805 {
806     my($bpc) = @_;
807     my($topDir) = $bpc->{TopDir};
808     my($s, $dfCmd);
809
810     return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
811     my $args = {
812         dfPath   => $bpc->{Conf}{DfPath},
813         topDir   => $bpc->{TopDir},
814     };
815     $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
816     $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
817     return 0 if ( $? || $s !~ /(\d+)%/s );
818     return $1;
819 }
820
821 #
822 # Given an IP address, return the host name and user name via
823 # NetBios.
824 #
825 sub NetBiosInfoGet
826 {
827     my($bpc, $host) = @_;
828     my($netBiosHostName, $netBiosUserName);
829     my($s, $nmbCmd);
830
831     #
832     # Skip NetBios check if NmbLookupCmd is emtpy
833     #
834     if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
835         print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
836                    . " is empty\n") if ( $bpc->{verbose} );
837         return ($host, undef);
838     }
839
840     my $args = {
841         nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
842         host          => $host,
843     };
844     $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
845     foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
846         next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
847         $netBiosHostName ||= $1 if ( $2 eq "00" );  # host is first 00
848         $netBiosUserName   = $1 if ( $2 eq "03" );  # user is last 03
849     }
850     if ( !defined($netBiosHostName) ) {
851         print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
852                         if ( $bpc->{verbose} );
853         return;
854     }
855     $netBiosHostName = lc($netBiosHostName);
856     $netBiosUserName = lc($netBiosUserName);
857     print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
858                . " user $netBiosUserName\n") if ( $bpc->{verbose} );
859     return ($netBiosHostName, $netBiosUserName);
860 }
861
862 #
863 # Given a NetBios name lookup the IP address via NetBios.
864 # In the case of a host returning multiple interfaces we
865 # return the first IP address that matches the subnet mask.
866 # If none match the subnet mask (or nmblookup doesn't print
867 # the subnet mask) then just the first IP address is returned.
868 #
869 sub NetBiosHostIPFind
870 {
871     my($bpc, $host) = @_;
872     my($netBiosHostName, $netBiosUserName);
873     my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
874
875     #
876     # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
877     #
878     if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
879         print(STDERR "NetBiosHostIPFind: return $host because"
880             . " \$Conf{NmbLookupFindHostCmd} is empty\n")
881                 if ( $bpc->{verbose} );
882         return $host;
883     }
884
885     my $args = {
886         nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
887         host          => $host,
888     };
889     $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
890     foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
891                                                               $args) ) ) {
892         if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
893             $subnet = $1;
894             $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
895         } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
896             my $ip = $1;
897             $firstIpAddr = $ip if ( !defined($firstIpAddr) );
898             $ipAddr      = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
899         }
900     }
901     $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
902     if ( defined($ipAddr) ) {
903         print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
904                    . " host $host\n") if ( $bpc->{verbose} );
905         return $ipAddr;
906     } else {
907         print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
908                    . " host $host\n") if ( $bpc->{verbose} );
909         return;
910     }
911 }
912
913 sub fileNameEltMangle
914 {
915     my($bpc, $name) = @_;
916
917     return "" if ( $name eq "" );
918     $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
919     return "f$name";
920 }
921
922 #
923 # We store files with every name preceded by "f".  This
924 # avoids possible name conflicts with other information
925 # we store in the same directories (eg: attribute info).
926 # The process of turning a normal path into one with each
927 # node prefixed with "f" is called mangling.
928 #
929 sub fileNameMangle
930 {
931     my($bpc, $name) = @_;
932
933     $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
934     $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
935     return $name;
936 }
937
938 #
939 # This undoes FileNameMangle
940 #
941 sub fileNameUnmangle
942 {
943     my($bpc, $name) = @_;
944
945     $name =~ s{/f}{/}g;
946     $name =~ s{^f}{};
947     $name =~ s{%(..)}{chr(hex($1))}eg;
948     return $name;
949 }
950
951 #
952 # Escape shell meta-characters with backslashes.
953 # This should be applied to each argument seperately, not an
954 # entire shell command.
955 #
956 sub shellEscape
957 {
958     my($bpc, $cmd) = @_;
959
960     $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
961     return $cmd;
962 }
963
964 #
965 # For printing exec commands (which don't use a shell) so they look like
966 # a valid shell command this function should be called with the exec
967 # args.  The shell command string is returned.
968 #
969 sub execCmd2ShellCmd
970 {
971     my($bpc, @args) = @_;
972     my $str;
973
974     foreach my $a ( @args ) {
975         $str .= " " if ( $str ne "" );
976         $str .= $bpc->shellEscape($a);
977     }
978     return $str;
979 }
980
981 #
982 # Do a URI-style escape to protect/encode special characters
983 #
984 sub uriEsc
985 {
986     my($bpc, $s) = @_;
987     $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
988     return $s;
989 }
990
991 #
992 # Do a URI-style unescape to restore special characters
993 #
994 sub uriUnesc
995 {
996     my($bpc, $s) = @_;
997     $s =~ s{%(..)}{chr(hex($1))}eg;
998     return $s;
999 }
1000
1001 #
1002 # Do variable substitution prior to execution of a command.
1003 #
1004 sub cmdVarSubstitute
1005 {
1006     my($bpc, $template, $vars) = @_;
1007     my(@cmd);
1008
1009     #
1010     # Return without any substitution if the first entry starts with "&",
1011     # indicating this is perl code.
1012     #
1013     if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1014         return $template;
1015     }
1016     if ( ref($template) ne "ARRAY" ) {
1017         #
1018         # Split at white space, except if escaped by \
1019         #
1020         $template = [split(/(?<!\\)\s+/, $template)];
1021         #
1022         # Remove the \ that escaped white space.
1023         #
1024         foreach ( @$template ) {
1025             s{\\(\s)}{$1}g;
1026         }
1027     }
1028     #
1029     # Merge variables into @tarClientCmd
1030     #
1031     foreach my $arg ( @$template ) {
1032         #
1033         # Replace scalar variables first
1034         #
1035         $arg =~ s{\$(\w+)(\+?)}{
1036             exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1037                 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1038                 : "\$$1$2"
1039         }eg;
1040         #
1041         # Now replicate any array arguments; this just works for just one
1042         # array var in each argument.
1043         #
1044         if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1045             my $pre  = $1;
1046             my $var  = $2;
1047             my $esc  = $3;
1048             my $post = $4;
1049             foreach my $v ( @{$vars->{$var}} ) {
1050                 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1051                 push(@cmd, "$pre$v$post");
1052             }
1053         } else {
1054             push(@cmd, $arg);
1055         }
1056     }
1057     return \@cmd;
1058 }
1059
1060 #
1061 # Exec or eval a command.  $cmd is either a string on an array ref.
1062 #
1063 # @args are optional arguments for the eval() case; they are not used
1064 # for exec().
1065 #
1066 sub cmdExecOrEval
1067 {
1068     my($bpc, $cmd, @args) = @_;
1069     
1070     if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1071         $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1072         print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1073                         if ( $bpc->{verbose} );
1074         eval($cmd);
1075         print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1076         exit(1);
1077     } else {
1078         $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1079         print(STDERR "cmdExecOrEval: about to exec ",
1080               $bpc->execCmd2ShellCmd(@$cmd), "\n")
1081                         if ( $bpc->{verbose} );
1082         alarm(0);
1083         $cmd = [map { m/(.*)/ } @$cmd];         # untaint
1084         #
1085         # force list-form of exec(), ie: no shell even for 1 arg
1086         #
1087         exec { $cmd->[0] } @$cmd;
1088         print(STDERR "Exec failed for @$cmd\n");
1089         exit(1);
1090     }
1091 }
1092
1093 #
1094 # System or eval a command.  $cmd is either a string on an array ref.
1095 # $stdoutCB is a callback for output generated by the command.  If it
1096 # is undef then output is returned.  If it is a code ref then the function
1097 # is called with each piece of output as an argument.  If it is a scalar
1098 # ref the output is appended to this variable.
1099 #
1100 # @args are optional arguments for the eval() case; they are not used
1101 # for system().
1102 #
1103 # Also, $? should be set when the CHILD pipe is closed.
1104 #
1105 sub cmdSystemOrEvalLong
1106 {
1107     my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1108     my($pid, $out, $allOut);
1109     local(*CHILD);
1110     
1111     $? = 0;
1112     if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1113         $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1114         print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1115                         if ( $bpc->{verbose} );
1116         $out = eval($cmd);
1117         $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1118         &$stdoutCB($out)   if ( ref($stdoutCB) eq 'CODE' );
1119         print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1120                         if ( $bpc->{verbose} );
1121         return $out        if ( !defined($stdoutCB) );
1122         return;
1123     } else {
1124         $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1125         print(STDERR "cmdSystemOrEval: about to system ",
1126               $bpc->execCmd2ShellCmd(@$cmd), "\n")
1127                         if ( $bpc->{verbose} );
1128         if ( !defined($pid = open(CHILD, "-|")) ) {
1129             my $err = "Can't fork to run @$cmd\n";
1130             $? = 1;
1131             $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1132             &$stdoutCB($err)   if ( ref($stdoutCB) eq 'CODE' );
1133             return $err        if ( !defined($stdoutCB) );
1134             return;
1135         }
1136         binmode(CHILD);
1137         if ( !$pid ) {
1138             #
1139             # This is the child
1140             #
1141             close(STDERR);
1142             if ( $ignoreStderr ) {
1143                 open(STDERR, ">", "/dev/null");
1144             } else {
1145                 open(STDERR, ">&STDOUT");
1146             }
1147             alarm(0);
1148             $cmd = [map { m/(.*)/ } @$cmd];             # untaint
1149             #
1150             # force list-form of exec(), ie: no shell even for 1 arg
1151             #
1152             exec { $cmd->[0] } @$cmd;
1153             print(STDERR "Exec of @$cmd failed\n");
1154             exit(1);
1155         }
1156
1157         #
1158         # Notify caller of child's pid
1159         #
1160         &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1161
1162         #
1163         # The parent gathers the output from the child
1164         #
1165         while ( <CHILD> ) {
1166             $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1167             &$stdoutCB($_)   if ( ref($stdoutCB) eq 'CODE' );
1168             $out .= $_       if ( !defined($stdoutCB) );
1169             $allOut .= $_    if ( $bpc->{verbose} );
1170         }
1171         $? = 0;
1172         close(CHILD);
1173     }
1174     print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1175                         if ( $bpc->{verbose} );
1176     return $out;
1177 }
1178
1179 #
1180 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1181 # and stderr together.
1182 #
1183 sub cmdSystemOrEval
1184 {
1185     my($bpc, $cmd, $stdoutCB, @args) = @_;
1186
1187     return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1188 }
1189
1190 #
1191 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1192 # to hashes and $conf->{$shareName} to an array.
1193 #
1194 sub backupFileConfFix
1195 {
1196     my($bpc, $conf, $shareName) = @_;
1197
1198     $conf->{$shareName} = [ $conf->{$shareName} ]
1199                     if ( ref($conf->{$shareName}) ne "ARRAY" );
1200     foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1201         next if ( !defined($conf->{$param}) );
1202         if ( ref($conf->{$param}) eq "HASH" ) {
1203             #
1204             # A "*" entry means wildcard - it is the default for
1205             # all shares.  Replicate the "*" entry for all shares,
1206             # but still allow override of specific entries.
1207             #
1208             next if ( !defined($conf->{$param}{"*"}) );
1209             $conf->{$param} = {
1210                                     map({ $_ => $conf->{$param}{"*"} }
1211                                             @{$conf->{$shareName}}),
1212                                     %{$conf->{$param}}
1213                               };
1214         } else {
1215             $conf->{$param} = [ $conf->{$param} ]
1216                                     if ( ref($conf->{$param}) ne "ARRAY" );
1217             $conf->{$param} = { map { $_ => $conf->{$param} }
1218                                     @{$conf->{$shareName}} };
1219         }
1220     }
1221 }
1222
1223 #
1224 # This is sort() compare function, used below.
1225 #
1226 # New client LOG names are LOG.MMYYYY.  Old style names are
1227 # LOG, LOG.0, LOG.1 etc.  Sort them so new names are
1228 # first, and newest to oldest.
1229 #
1230 sub compareLOGName
1231 {
1232     my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1233     my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1234
1235     $na = -1 if ( !defined($na) );
1236     $nb = -1 if ( !defined($nb) );
1237
1238     if ( length($na) >= 5 && length($nb) >= 5 ) {
1239         #
1240         # Both new style.  Bigger numbers are more recent.
1241         #
1242         return $nb - $na;
1243     } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1244         return -1;
1245     } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1246         return 1;
1247     } else {
1248         #
1249         # Both old style.  Smaller numbers are more recent.
1250         #
1251         return $na - $nb;
1252     }
1253 }
1254
1255 #
1256 # Returns list of paths to a clients's (or main) LOG files,
1257 # most recent first.
1258 #
1259 sub sortedPCLogFiles
1260 {
1261     my($bpc, $host) = @_;
1262
1263     my(@files, $dir);
1264
1265     if ( $host ne "" ) {
1266         $dir = "$bpc->{TopDir}/pc/$host";
1267     } else {
1268         $dir = "$bpc->{LogDir}";
1269     }
1270     if ( opendir(DIR, $dir) ) {
1271         foreach my $file ( readdir(DIR) ) {
1272             next if ( !-f "$dir/$file" );
1273             next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1274             push(@files, "$dir/$file");
1275         }
1276         closedir(DIR);
1277     }
1278     return sort(compareLOGName @files);
1279 }
1280
1281 1;