1 #============================================================= -*-perl-*-
3 # BackupPC::Lib package
7 # This library defines a BackupPC::Lib class and a variety of utility
8 # functions used by BackupPC.
11 # Craig Barratt <cbarratt@users.sourceforge.net>
14 # Copyright (C) 2001-2003 Craig Barratt
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.
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.
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
30 #========================================================================
32 # Version 3.1.0beta0, released 3 Sep 2007.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
38 package BackupPC::Lib;
42 use vars qw(%Conf %Lang);
43 use BackupPC::Storage;
52 use Encode qw/from_to encode_utf8/;
54 use vars qw( $IODirentOk );
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
60 @ISA = qw(Exporter DynaLoader);
61 @EXPORT_OK = qw( BPC_DT_UNKNOWN
71 %EXPORT_TAGS = ('BPC_DT_ALL' => [@EXPORT, @EXPORT_OK]);
74 eval "use IO::Dirent qw( readdirent DT_DIR );";
75 $IODirentOk = 1 if ( !$@ );
79 # The need to match the constants in IO::Dirent
81 use constant BPC_DT_UNKNOWN => 0;
82 use constant BPC_DT_FIFO => 1; ## named pipe (fifo)
83 use constant BPC_DT_CHR => 2; ## character special
84 use constant BPC_DT_DIR => 4; ## directory
85 use constant BPC_DT_BLK => 6; ## block special
86 use constant BPC_DT_REG => 8; ## regular
87 use constant BPC_DT_LNK => 10; ## symbolic link
88 use constant BPC_DT_SOCK => 12; ## socket
93 my($topDir, $installDir, $confDir, $noUserCheck) = @_;
96 # Whether to use filesystem hierarchy standard for file layout.
97 # If set, text config files are below /etc/BackupPC.
103 # Set defaults for $topDir and $installDir.
105 $topDir = '/tera0/backup/BackupPC' if ( $topDir eq "" );
106 $installDir = '/usr/local/BackupPC' if ( $installDir eq "" );
109 # Pick some initial defaults. For FHS the only critical
110 # path is the ConfDir, since we get everything else out
111 # of the main config file.
117 InstallDir => $installDir,
118 ConfDir => $confDir eq "" ? '/tera0/backup/BackupPC/conf' : $confDir,
119 LogDir => '/var/log/BackupPC',
125 InstallDir => $installDir,
126 ConfDir => $confDir eq "" ? "$topDir/conf" : $confDir,
127 LogDir => "$topDir/log",
133 Version => '3.1.0beta0',
136 $bpc->{storage} = BackupPC::Storage->new($paths);
139 # Clean up %ENV and setup other variables.
141 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
142 $bpc->{PoolDir} = "$bpc->{TopDir}/pool";
143 $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
144 if ( defined(my $error = $bpc->ConfigRead()) ) {
145 print(STDERR $error, "\n");
150 # Update the paths based on the config file
152 foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
153 next if ( $bpc->{Conf}{$dir} eq "" );
154 $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
156 $bpc->{storage}->setPaths($paths);
159 # Verify we are running as the correct user
162 && $bpc->{Conf}{BackupPCUserVerify}
163 && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
164 print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
165 . " ($bpc->{Conf}{BackupPCUser})\n");
166 print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
175 return $bpc->{TopDir};
181 return "$bpc->{InstallDir}/bin";
187 return $bpc->{LogDir};
193 return $bpc->{ConfDir};
199 return "$bpc->{InstallDir}/lib";
205 return $bpc->{InstallDir};
211 return $bpc->{useFHS};
217 return $bpc->{Version};
223 return %{$bpc->{Conf}};
235 return " admin " if ( !$num );
236 return " admin$num ";
242 return $str =~ /^ admin/;
247 return " trashClean ";
252 my($bpc, $param) = @_;
254 return $bpc->{Conf}{$param};
259 my($bpc, $param) = @_;
261 $bpc->{verbose} = $param if ( defined($param) );
262 return $bpc->{verbose};
269 if ( !defined($bpc->{SigName2Num}) ) {
271 foreach my $name ( split(' ', $Config{sig_name}) ) {
272 $bpc->{SigName2Num}{$name} = $i;
276 return $bpc->{SigName2Num}{$sig};
280 # Generate an ISO 8601 format timeStamp (but without the "T").
281 # See http://www.w3.org/TR/NOTE-datetime and
282 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
286 my($bpc, $t, $noPad) = @_;
287 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
288 = localtime($t || time);
289 return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
290 $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
291 . ($noPad ? "" : " ");
296 my($bpc, $host) = @_;
298 return $bpc->{storage}->BackupInfoRead($host);
303 my($bpc, $host, @Backups) = @_;
305 return $bpc->{storage}->BackupInfoWrite($host, @Backups);
310 my($bpc, $host) = @_;
312 return $bpc->{storage}->RestoreInfoRead($host);
317 my($bpc, $host, @Restores) = @_;
319 return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
324 my($bpc, $host) = @_;
326 return $bpc->{storage}->ArchiveInfoRead($host);
331 my($bpc, $host, @Archives) = @_;
333 return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
338 my($bpc, $host) = @_;
340 return $bpc->{storage}->ConfigDataRead($host);
345 my($bpc, $host, $conf) = @_;
347 return $bpc->{storage}->ConfigDataWrite($host, $conf);
352 my($bpc, $host) = @_;
356 # Read main config file
358 my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
359 return $mesg if ( defined($mesg) );
361 $bpc->{Conf} = $config;
364 # Read host config file
367 ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
368 return $mesg if ( defined($mesg) );
369 $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
373 # Load optional perl modules
375 if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
377 # Load any user-specified perl modules. This is for
378 # optional user-defined extensions.
380 $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
381 if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
382 foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
383 eval("use $module;");
390 return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
391 my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
392 if ( !defined($ret = do $langFile) && ($! || $@) ) {
393 $mesg = "Couldn't open language file $langFile: $!" if ( $! );
394 $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
395 $mesg =~ s/[\n\r]+//;
398 $bpc->{Lang} = \%Lang;
403 # Return the mtime of the config file
409 return $bpc->{storage}->ConfigMTime();
413 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
414 # With no argument a ref to a hash of hosts is returned. Each
415 # hash contains fields as specified in the hosts file. With an
416 # argument a ref to a single hash is returned with information
417 # for just that host.
421 my($bpc, $host) = @_;
423 return $bpc->{storage}->HostInfoRead($host);
428 my($bpc, $host) = @_;
430 return $bpc->{storage}->HostInfoWrite($host);
434 # Return the mtime of the hosts file
440 return $bpc->{storage}->HostsMTime();
444 # Read a directory and return the entries in sorted inode order.
445 # This relies on the IO::Dirent module being installed. If not,
446 # the inode data is empty and the default directory order is
449 # The returned data is a list of hashes with entries {name, type, inode, nlink}.
450 # The returned data includes "." and "..".
452 # $need is a hash of file attributes we need: type, inode, or nlink.
453 # If set, these parameters are added to the returned hash.
455 # To support browsing pre-3.0.0 backups where the charset encoding
456 # is typically iso-8859-1, the charsetLegacy option can be set in
457 # $need to convert the path from utf8 and convert the names to utf8.
459 # If IO::Dirent is successful if will get type and inode for free.
460 # Otherwise, a stat is done on each file, which is more expensive.
464 my($bpc, $path, $need) = @_;
465 my(@entries, $addInode);
467 from_to($path, "utf8", $need->{charsetLegacy})
468 if ( $need->{charsetLegacy} ne "" );
469 return if ( !opendir(my $fh, $path) );
471 @entries = sort({ $a->{inode} <=> $b->{inode} } readdirent($fh));
472 map { $_->{type} = 0 + $_->{type} } @entries; # make type numeric
474 @entries = map { { name => $_} } readdir($fh);
477 if ( defined($need) ) {
478 for ( my $i = 0 ; $i < @entries ; $i++ ) {
479 next if ( (!$need->{inode} || defined($entries[$i]{inode}))
480 && (!$need->{type} || defined($entries[$i]{type}))
481 && (!$need->{nlink} || defined($entries[$i]{nlink})) );
482 my @s = stat("$path/$entries[$i]{name}");
483 $entries[$i]{nlink} = $s[3] if ( $need->{nlink} );
484 if ( $need->{inode} && !defined($entries[$i]{inode}) ) {
486 $entries[$i]{inode} = $s[1];
488 if ( $need->{type} && !defined($entries[$i]{type}) ) {
489 my $mode = S_IFMT($s[2]);
490 $entries[$i]{type} = BPC_DT_FIFO if ( S_ISFIFO($mode) );
491 $entries[$i]{type} = BPC_DT_CHR if ( S_ISCHR($mode) );
492 $entries[$i]{type} = BPC_DT_DIR if ( S_ISDIR($mode) );
493 $entries[$i]{type} = BPC_DT_BLK if ( S_ISBLK($mode) );
494 $entries[$i]{type} = BPC_DT_REG if ( S_ISREG($mode) );
495 $entries[$i]{type} = BPC_DT_LNK if ( S_ISLNK($mode) );
496 $entries[$i]{type} = BPC_DT_SOCK if ( S_ISSOCK($mode) );
501 # Sort the entries if inodes were added (the IO::Dirent case already
504 @entries = sort({ $a->{inode} <=> $b->{inode} } @entries) if ( $addInode );
506 # for browing pre-3.0.0 backups, map iso-8859-1 to utf8 if requested
508 if ( $need->{charsetLegacy} ne "" ) {
509 for ( my $i = 0 ; $i < @entries ; $i++ ) {
510 from_to($entries[$i]{name}, $need->{charsetLegacy}, "utf8");
517 # Same as dirRead, but only returns the names (which will be sorted in
518 # inode order if IO::Dirent is installed)
522 my($bpc, $path, $need) = @_;
524 my $entries = $bpc->dirRead($path, $need);
525 return if ( !defined($entries) );
526 my @names = map { $_->{name} } @$entries;
532 my($bpc, $param, $dir, $dontDoCwd) = @_;
534 return if ( !chdir($dir) );
535 my $entries = $bpc->dirRead(".", {inode => 1, type => 1});
536 #print Dumper($entries);
537 foreach my $f ( @$entries ) {
538 next if ( $f->{name} eq ".." || $f->{name} eq "." && $dontDoCwd );
539 $param->{wanted}($f->{name}, "$dir/$f->{name}");
540 next if ( $f->{type} != BPC_DT_DIR || $f->{name} eq "." );
542 $bpc->find($param, "$dir/$f->{name}", 1);
543 return if ( !chdir("..") );
548 # Stripped down from File::Path. In particular we don't print
549 # many warnings and we try three times to delete each directory
550 # and file -- for some reason the original File::Path rmtree
551 # didn't always completely remove a directory tree on a NetApp.
553 # Warning: this routine changes the cwd.
557 my($bpc, $pwd, $roots) = @_;
560 if ( defined($roots) && length($roots) ) {
561 $roots = [$roots] unless ref $roots;
563 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
566 foreach $root (@{$roots}) {
567 $root = $1 if ( $root =~ m{(.*?)/*$} );
569 # Try first to simply unlink the file: this avoids an
570 # extra stat for every file. If it fails (which it
571 # will for directories), check if it is a directory and
574 if ( !unlink($root) ) {
576 my $d = $bpc->dirReadNames($root);
577 if ( !defined($d) ) {
578 print(STDERR "Can't read $pwd/$root: $!\n");
580 @files = grep $_ !~ /^\.{1,2}$/, @$d;
581 $bpc->RmTreeQuiet("$pwd/$root", \@files);
583 rmdir($root) || rmdir($root);
586 unlink($root) || unlink($root);
593 # Move a directory or file away for later deletion
597 my($bpc, $trashDir, $file) = @_;
600 return if ( !-e $file );
601 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
602 for ( $i = 0 ; $i < 1000 ; $i++ ) {
603 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
605 return if ( rename($file, $f) );
607 # shouldn't get here, but might if you tried to call this
608 # across file systems.... just remove the tree right now.
609 if ( $file =~ /(.*)\/([^\/]*)/ ) {
612 my($cwd) = Cwd::fastcwd();
613 $cwd = $1 if ( $cwd =~ /(.*)/ );
614 $bpc->RmTreeQuiet($d, $f);
615 chdir($cwd) if ( $cwd );
620 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
621 # did something, -1 if it failed to remove all the files.
625 my($bpc, $trashDir) = @_;
627 my($cwd) = Cwd::fastcwd();
629 $cwd = $1 if ( $cwd =~ /(.*)/ );
630 return if ( !-d $trashDir );
631 my $d = $bpc->dirReadNames($trashDir) or carp "Can't read $trashDir: $!";
632 @files = grep $_ !~ /^\.{1,2}$/, @$d;
633 return 0 if ( !@files );
634 $bpc->RmTreeQuiet($trashDir, \@files);
635 foreach my $f ( @files ) {
636 return -1 if ( -e $f );
638 chdir($cwd) if ( $cwd );
643 # Open a connection to the server. Returns an error string on failure.
644 # Returns undef on success.
648 my($bpc, $host, $port, $justConnect) = @_;
651 return if ( defined($bpc->{ServerFD}) );
653 # First try the unix-domain socket
655 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
656 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
657 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
658 my $err = "unix connect: $!";
661 my $proto = getprotobyname('tcp');
662 my $iaddr = inet_aton($host) || return "unknown host $host";
663 my $paddr = sockaddr_in($port, $iaddr);
665 socket(*FH, PF_INET, SOCK_STREAM, $proto)
666 || return "inet socket: $!";
667 connect(*FH, $paddr) || return "inet connect: $!";
672 my($oldFH) = select(*FH); $| = 1; select($oldFH);
673 $bpc->{ServerFD} = *FH;
674 return if ( $justConnect );
676 # Read the seed that we need for our MD5 message digest. See
679 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
680 $bpc->{ServerMesgCnt} = 0;
685 # Check that the server connection is still ok
691 return 0 if ( !defined($bpc->{ServerFD}) );
692 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
694 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
695 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
699 # Disconnect from the server
704 return if ( !defined($bpc->{ServerFD}) );
705 close($bpc->{ServerFD});
706 delete($bpc->{ServerFD});
710 # Sends a message to the server and returns with the reply.
712 # To avoid possible attacks via the TCP socket interface, every client
713 # message is protected by an MD5 digest. The MD5 digest includes four
715 # - a seed that is sent to us when we first connect
716 # - a sequence number that increments for each message
717 # - a shared secret that is stored in $Conf{ServerMesgSecret}
718 # - the message itself.
719 # The message is sent in plain text preceded by the MD5 digest. A
720 # snooper can see the plain-text seed sent by BackupPC and plain-text
721 # message, but cannot construct a valid MD5 digest since the secret in
722 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
723 # since the seed changes on a per-connection and per-message basis.
727 my($bpc, $mesg) = @_;
728 return if ( !defined(my $fh = $bpc->{ServerFD}) );
731 my $md5 = Digest::MD5->new;
732 $mesg = encode_utf8($mesg);
733 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
734 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
735 print($fh $md5->b64digest . " $mesg\n");
736 $bpc->{ServerMesgCnt}++;
741 # Do initialization for child processes
747 open(STDERR, ">&STDOUT");
748 select(STDERR); $| = 1;
749 select(STDOUT); $| = 1;
750 $ENV{PATH} = $bpc->{Conf}{MyPath};
754 # Compute the MD5 digest of a file. For efficiency we don't
755 # use the whole file for big files:
756 # - for files <= 256K we use the file size and the whole file.
757 # - for files <= 1M we use the file size, the first 128K and
759 # - for files > 1M, we use the file size, the first 128K and
760 # the 8th 128K (ie: the 128K up to 1MB).
761 # See the documentation for a discussion of the tradeoffs in
762 # how much data we use and how many collisions we get.
764 # Returns the MD5 digest (a hex string) and the file size.
768 my($bpc, $md5, $name) = @_;
769 my($data, $fileSize);
772 $fileSize = (stat($name))[7];
773 return ("", -1) if ( !-f _ );
774 $name = $1 if ( $name =~ /(.*)/ );
775 return ("", 0) if ( $fileSize == 0 );
776 return ("", -1) if ( !open(N, $name) );
779 $md5->add($fileSize);
780 if ( $fileSize > 262144 ) {
782 # read the first and last 131072 bytes of the file,
785 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
786 $md5->add($data) if ( sysread(N, $data, 131072) );
787 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
788 && sysread(N, $data, 131072) );
791 # read the whole file
793 $md5->add($data) if ( sysread(N, $data, $fileSize) );
796 return ($md5->hexdigest, $fileSize);
800 # Compute the MD5 digest of a buffer (string). For efficiency we don't
801 # use the whole string for big strings:
802 # - for files <= 256K we use the file size and the whole file.
803 # - for files <= 1M we use the file size, the first 128K and
805 # - for files > 1M, we use the file size, the first 128K and
806 # the 8th 128K (ie: the 128K up to 1MB).
807 # See the documentation for a discussion of the tradeoffs in
808 # how much data we use and how many collisions we get.
810 # Returns the MD5 digest (a hex string).
814 my($bpc, $md5, $fileSize, $dataRef) = @_;
817 $md5->add($fileSize);
818 if ( $fileSize > 262144 ) {
820 # add the first and last 131072 bytes of the string,
823 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
824 $md5->add(substr($$dataRef, 0, 131072));
825 $md5->add(substr($$dataRef, $seekPosn, 131072));
828 # add the whole string
830 $md5->add($$dataRef);
832 return $md5->hexdigest;
836 # Given an MD5 digest $d and a compress flag, return the full
841 my($bpc, $d, $compress, $poolDir) = @_;
843 return if ( $d !~ m{(.)(.)(.)(.*)} );
844 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
845 if ( !defined($poolDir) );
846 return "$poolDir/$1/$2/$3/$1$2$3$4";
850 # For each file, check if the file exists in $bpc->{TopDir}/pool.
851 # If so, remove the file and make a hardlink to the file in
852 # the pool. Otherwise, if the newFile flag is set, make a
853 # hardlink in the pool to the new file.
855 # Returns 0 if a link should be made to a new file (ie: when the file
856 # is a new file but the newFile flag is 0).
857 # Returns 1 if a link to an existing file is made,
858 # Returns 2 if a link to a new file is made (only if $newFile is set)
859 # Returns negative on error.
863 my($bpc, $name, $d, $newFile, $compress) = @_;
866 return -1 if ( !-f $name );
867 for ( $i = -1 ; ; $i++ ) {
868 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
869 $rawFile .= "_$i" if ( $i >= 0 );
871 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
872 && !compare($name, $rawFile) ) {
874 return -3 if ( !link($rawFile, $name) );
877 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
879 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
880 mkpath($newDir, 0, 0777) if ( !-d $newDir );
881 return -4 if ( !link($name, $rawFile) );
890 # Tests if we can create a hardlink from a file in directory
891 # $newDir to a file in directory $targetDir. A temporary
892 # file in $targetDir is created and an attempt to create a
893 # hardlink of the same name in $newDir is made. The temporary
896 # Like link(), returns true on success and false on failure.
900 my($bpc, $targetDir, $newDir) = @_;
902 my($targetFile, $newFile, $fd);
903 for ( my $i = 0 ; ; $i++ ) {
904 $targetFile = "$targetDir/.TestFileLink.$$.$i";
905 $newFile = "$newDir/.TestFileLink.$$.$i";
906 last if ( !-e $targetFile && !-e $newFile );
908 return 0 if ( !open($fd, ">", $targetFile) );
910 my $ret = link($targetFile, $newFile);
918 my($bpc, $host) = @_;
919 my($s, $pingCmd, $ret);
922 # Return success if the ping cmd is undefined or empty.
924 if ( $bpc->{Conf}{PingCmd} eq "" ) {
925 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
926 . " is empty\n") if ( $bpc->{verbose} );
931 pingPath => $bpc->{Conf}{PingPath},
934 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
937 # Do a first ping in case the PC needs to wakeup
939 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
941 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
942 if ( $bpc->{verbose} );
947 # Do a second ping and get the round-trip time in msec
949 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
951 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
952 if ( $bpc->{verbose} );
955 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
957 $ret /= 1000 if ( lc($2) eq "usec" );
958 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
960 $ret /= 1000 if ( lc($2) eq "usec" );
962 print(STDERR "CheckHostAlive: can't extract round-trip time"
963 . " (not fatal)\n") if ( $bpc->{verbose} );
966 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
970 sub CheckFileSystemUsage
973 my($topDir) = $bpc->{TopDir};
976 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
978 dfPath => $bpc->{Conf}{DfPath},
979 topDir => $bpc->{TopDir},
981 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
982 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
983 return 0 if ( $? || $s !~ /(\d+)%/s );
988 # Given an IP address, return the host name and user name via
993 my($bpc, $host) = @_;
994 my($netBiosHostName, $netBiosUserName);
998 # Skip NetBios check if NmbLookupCmd is emtpy
1000 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
1001 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
1002 . " is empty\n") if ( $bpc->{verbose} );
1003 return ($host, undef);
1007 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1010 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
1011 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
1012 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
1013 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
1014 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
1016 if ( !defined($netBiosHostName) ) {
1017 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
1018 if ( $bpc->{verbose} );
1021 $netBiosHostName = lc($netBiosHostName);
1022 $netBiosUserName = lc($netBiosUserName);
1023 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
1024 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
1025 return ($netBiosHostName, $netBiosUserName);
1029 # Given a NetBios name lookup the IP address via NetBios.
1030 # In the case of a host returning multiple interfaces we
1031 # return the first IP address that matches the subnet mask.
1032 # If none match the subnet mask (or nmblookup doesn't print
1033 # the subnet mask) then just the first IP address is returned.
1035 sub NetBiosHostIPFind
1037 my($bpc, $host) = @_;
1038 my($netBiosHostName, $netBiosUserName);
1039 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
1042 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
1044 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
1045 print(STDERR "NetBiosHostIPFind: return $host because"
1046 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
1047 if ( $bpc->{verbose} );
1052 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1055 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
1056 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
1058 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
1060 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
1061 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
1063 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
1064 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
1067 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
1068 if ( defined($ipAddr) ) {
1069 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
1070 . " host $host\n") if ( $bpc->{verbose} );
1073 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
1074 . " host $host\n") if ( $bpc->{verbose} );
1079 sub fileNameEltMangle
1081 my($bpc, $name) = @_;
1083 return "" if ( $name eq "" );
1084 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
1089 # We store files with every name preceded by "f". This
1090 # avoids possible name conflicts with other information
1091 # we store in the same directories (eg: attribute info).
1092 # The process of turning a normal path into one with each
1093 # node prefixed with "f" is called mangling.
1097 my($bpc, $name) = @_;
1099 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
1100 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
1105 # This undoes FileNameMangle
1107 sub fileNameUnmangle
1109 my($bpc, $name) = @_;
1113 $name =~ s{%(..)}{chr(hex($1))}eg;
1118 # Escape shell meta-characters with backslashes.
1119 # This should be applied to each argument seperately, not an
1120 # entire shell command.
1124 my($bpc, $cmd) = @_;
1126 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
1131 # For printing exec commands (which don't use a shell) so they look like
1132 # a valid shell command this function should be called with the exec
1133 # args. The shell command string is returned.
1135 sub execCmd2ShellCmd
1137 my($bpc, @args) = @_;
1140 foreach my $a ( @args ) {
1141 $str .= " " if ( $str ne "" );
1142 $str .= $bpc->shellEscape($a);
1148 # Do a URI-style escape to protect/encode special characters
1153 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1158 # Do a URI-style unescape to restore special characters
1163 $s =~ s{%(..)}{chr(hex($1))}eg;
1168 # Do variable substitution prior to execution of a command.
1170 sub cmdVarSubstitute
1172 my($bpc, $template, $vars) = @_;
1176 # Return without any substitution if the first entry starts with "&",
1177 # indicating this is perl code.
1179 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1182 if ( ref($template) ne "ARRAY" ) {
1184 # Split at white space, except if escaped by \
1186 $template = [split(/(?<!\\)\s+/, $template)];
1188 # Remove the \ that escaped white space.
1190 foreach ( @$template ) {
1195 # Merge variables into @tarClientCmd
1197 foreach my $arg ( @$template ) {
1199 # Replace scalar variables first
1201 $arg =~ s{\$(\w+)(\+?)}{
1202 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1203 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1207 # Now replicate any array arguments; this just works for just one
1208 # array var in each argument.
1210 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1215 foreach my $v ( @{$vars->{$var}} ) {
1216 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1217 push(@cmd, "$pre$v$post");
1227 # Exec or eval a command. $cmd is either a string on an array ref.
1229 # @args are optional arguments for the eval() case; they are not used
1234 my($bpc, $cmd, @args) = @_;
1236 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1237 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1238 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1239 if ( $bpc->{verbose} );
1241 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1244 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1245 print(STDERR "cmdExecOrEval: about to exec ",
1246 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1247 if ( $bpc->{verbose} );
1249 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1251 # force list-form of exec(), ie: no shell even for 1 arg
1253 exec { $cmd->[0] } @$cmd;
1254 print(STDERR "Exec failed for @$cmd\n");
1260 # System or eval a command. $cmd is either a string on an array ref.
1261 # $stdoutCB is a callback for output generated by the command. If it
1262 # is undef then output is returned. If it is a code ref then the function
1263 # is called with each piece of output as an argument. If it is a scalar
1264 # ref the output is appended to this variable.
1266 # @args are optional arguments for the eval() case; they are not used
1269 # Also, $? should be set when the CHILD pipe is closed.
1271 sub cmdSystemOrEvalLong
1273 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1274 my($pid, $out, $allOut);
1278 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1279 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1280 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1281 if ( $bpc->{verbose} );
1283 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1284 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1285 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1286 if ( $bpc->{verbose} );
1287 return $out if ( !defined($stdoutCB) );
1290 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1291 print(STDERR "cmdSystemOrEval: about to system ",
1292 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1293 if ( $bpc->{verbose} );
1294 if ( !defined($pid = open(CHILD, "-|")) ) {
1295 my $err = "Can't fork to run @$cmd\n";
1297 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1298 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1299 return $err if ( !defined($stdoutCB) );
1308 if ( $ignoreStderr ) {
1309 open(STDERR, ">", "/dev/null");
1311 open(STDERR, ">&STDOUT");
1314 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1316 # force list-form of exec(), ie: no shell even for 1 arg
1318 exec { $cmd->[0] } @$cmd;
1319 print(STDERR "Exec of @$cmd failed\n");
1324 # Notify caller of child's pid
1326 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1329 # The parent gathers the output from the child
1332 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1333 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1334 $out .= $_ if ( !defined($stdoutCB) );
1335 $allOut .= $_ if ( $bpc->{verbose} );
1340 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1341 if ( $bpc->{verbose} );
1346 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1347 # and stderr together.
1351 my($bpc, $cmd, $stdoutCB, @args) = @_;
1353 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1357 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1358 # to hashes and $conf->{$shareName} to an array.
1360 sub backupFileConfFix
1362 my($bpc, $conf, $shareName) = @_;
1364 $conf->{$shareName} = [ $conf->{$shareName} ]
1365 if ( ref($conf->{$shareName}) ne "ARRAY" );
1366 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1367 next if ( !defined($conf->{$param}) );
1368 if ( ref($conf->{$param}) eq "HASH" ) {
1370 # A "*" entry means wildcard - it is the default for
1371 # all shares. Replicate the "*" entry for all shares,
1372 # but still allow override of specific entries.
1374 next if ( !defined($conf->{$param}{"*"}) );
1376 map({ $_ => $conf->{$param}{"*"} }
1377 @{$conf->{$shareName}}),
1381 $conf->{$param} = [ $conf->{$param} ]
1382 if ( ref($conf->{$param}) ne "ARRAY" );
1383 $conf->{$param} = { map { $_ => $conf->{$param} }
1384 @{$conf->{$shareName}} };
1390 # This is sort() compare function, used below.
1392 # New client LOG names are LOG.MMYYYY. Old style names are
1393 # LOG, LOG.0, LOG.1 etc. Sort them so new names are
1394 # first, and newest to oldest.
1398 my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1399 my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1401 $na = -1 if ( !defined($na) );
1402 $nb = -1 if ( !defined($nb) );
1404 if ( length($na) >= 5 && length($nb) >= 5 ) {
1406 # Both new style: format is MMYYYY. Bigger dates are
1409 my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1410 my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1412 } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1414 } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1418 # Both old style. Smaller numbers are more recent.
1425 # Returns list of paths to a clients's (or main) LOG files,
1426 # most recent first.
1428 sub sortedPCLogFiles
1430 my($bpc, $host) = @_;
1434 if ( $host ne "" ) {
1435 $dir = "$bpc->{TopDir}/pc/$host";
1437 $dir = "$bpc->{LogDir}";
1439 if ( opendir(DIR, $dir) ) {
1440 foreach my $file ( readdir(DIR) ) {
1441 next if ( !-f "$dir/$file" );
1442 next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1443 push(@files, "$dir/$file");
1447 return sort(compareLOGName @files);