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