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