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-2007 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.0, released 25 Nov 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 if ( !$@ && opendir(my $fh, ".") ) {
77 # Make sure the IO::Dirent really works - some installs
78 # on certain file systems don't return a valid type.
80 my $dt_dir = eval("DT_DIR");
81 foreach my $e ( readdirent($fh) ) {
82 if ( $e->{name} eq "." && $e->{type} == $dt_dir ) {
92 # The need to match the constants in IO::Dirent
94 use constant BPC_DT_UNKNOWN => 0;
95 use constant BPC_DT_FIFO => 1; ## named pipe (fifo)
96 use constant BPC_DT_CHR => 2; ## character special
97 use constant BPC_DT_DIR => 4; ## directory
98 use constant BPC_DT_BLK => 6; ## block special
99 use constant BPC_DT_REG => 8; ## regular
100 use constant BPC_DT_LNK => 10; ## symbolic link
101 use constant BPC_DT_SOCK => 12; ## socket
106 my($topDir, $installDir, $confDir, $noUserCheck) = @_;
109 # Whether to use filesystem hierarchy standard for file layout.
110 # If set, text config files are below /etc/BackupPC.
116 # Set defaults for $topDir and $installDir.
118 $topDir = '/tera0/backup/BackupPC' if ( $topDir eq "" );
119 $installDir = '/usr/local/BackupPC' if ( $installDir eq "" );
122 # Pick some initial defaults. For FHS the only critical
123 # path is the ConfDir, since we get everything else out
124 # of the main config file.
130 InstallDir => $installDir,
131 ConfDir => $confDir eq "" ? '/tera0/backup/BackupPC/conf' : $confDir,
132 LogDir => '/var/log/BackupPC',
138 InstallDir => $installDir,
139 ConfDir => $confDir eq "" ? "$topDir/conf" : $confDir,
140 LogDir => "$topDir/log",
149 $bpc->{storage} = BackupPC::Storage->new($paths);
152 # Clean up %ENV and setup other variables.
154 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
155 $bpc->{PoolDir} = "$bpc->{TopDir}/pool";
156 $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
157 if ( defined(my $error = $bpc->ConfigRead()) ) {
158 print(STDERR $error, "\n");
163 # Update the paths based on the config file
165 foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
166 next if ( $bpc->{Conf}{$dir} eq "" );
167 $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
169 $bpc->{storage}->setPaths($paths);
172 # Verify we are running as the correct user
175 && $bpc->{Conf}{BackupPCUserVerify}
176 && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
177 print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
178 . " ($bpc->{Conf}{BackupPCUser})\n");
179 print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
188 return $bpc->{TopDir};
194 return "$bpc->{InstallDir}/bin";
200 return $bpc->{LogDir};
206 return $bpc->{ConfDir};
212 return "$bpc->{InstallDir}/lib";
218 return $bpc->{InstallDir};
224 return $bpc->{useFHS};
230 return $bpc->{Version};
236 return %{$bpc->{Conf}};
248 return " admin " if ( !$num );
249 return " admin$num ";
255 return $str =~ /^ admin/;
260 return " trashClean ";
265 my($bpc, $param) = @_;
267 return $bpc->{Conf}{$param};
272 my($bpc, $param) = @_;
274 $bpc->{verbose} = $param if ( defined($param) );
275 return $bpc->{verbose};
282 if ( !defined($bpc->{SigName2Num}) ) {
284 foreach my $name ( split(' ', $Config{sig_name}) ) {
285 $bpc->{SigName2Num}{$name} = $i;
289 return $bpc->{SigName2Num}{$sig};
293 # Generate an ISO 8601 format timeStamp (but without the "T").
294 # See http://www.w3.org/TR/NOTE-datetime and
295 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
299 my($bpc, $t, $noPad) = @_;
300 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
301 = localtime($t || time);
302 return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
303 $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
304 . ($noPad ? "" : " ");
309 my($bpc, $host) = @_;
311 return $bpc->{storage}->BackupInfoRead($host);
316 my($bpc, $host, @Backups) = @_;
318 return $bpc->{storage}->BackupInfoWrite($host, @Backups);
323 my($bpc, $host) = @_;
325 return $bpc->{storage}->RestoreInfoRead($host);
330 my($bpc, $host, @Restores) = @_;
332 return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
337 my($bpc, $host) = @_;
339 return $bpc->{storage}->ArchiveInfoRead($host);
344 my($bpc, $host, @Archives) = @_;
346 return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
351 my($bpc, $host) = @_;
353 return $bpc->{storage}->ConfigDataRead($host);
358 my($bpc, $host, $conf) = @_;
360 return $bpc->{storage}->ConfigDataWrite($host, $conf);
365 my($bpc, $host) = @_;
369 # Read main config file
371 my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
372 return $mesg if ( defined($mesg) );
374 $bpc->{Conf} = $config;
377 # Read host config file
380 ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
381 return $mesg if ( defined($mesg) );
382 $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
386 # Load optional perl modules
388 if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
390 # Load any user-specified perl modules. This is for
391 # optional user-defined extensions.
393 $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
394 if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
395 foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
396 eval("use $module;");
403 return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
404 my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
405 if ( !defined($ret = do $langFile) && ($! || $@) ) {
406 $mesg = "Couldn't open language file $langFile: $!" if ( $! );
407 $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
408 $mesg =~ s/[\n\r]+//;
411 $bpc->{Lang} = \%Lang;
414 # Make sure IncrLevels is defined
416 $bpc->{Conf}{IncrLevels} = [1] if ( !defined($bpc->{Conf}{IncrLevels}) );
422 # Return the mtime of the config file
428 return $bpc->{storage}->ConfigMTime();
432 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
433 # With no argument a ref to a hash of hosts is returned. Each
434 # hash contains fields as specified in the hosts file. With an
435 # argument a ref to a single hash is returned with information
436 # for just that host.
440 my($bpc, $host) = @_;
442 return $bpc->{storage}->HostInfoRead($host);
447 my($bpc, $host) = @_;
449 return $bpc->{storage}->HostInfoWrite($host);
453 # Return the mtime of the hosts file
459 return $bpc->{storage}->HostsMTime();
463 # Read a directory and return the entries in sorted inode order.
464 # This relies on the IO::Dirent module being installed. If not,
465 # the inode data is empty and the default directory order is
468 # The returned data is a list of hashes with entries {name, type, inode, nlink}.
469 # The returned data includes "." and "..".
471 # $need is a hash of file attributes we need: type, inode, or nlink.
472 # If set, these parameters are added to the returned hash.
474 # To support browsing pre-3.0.0 backups where the charset encoding
475 # is typically iso-8859-1, the charsetLegacy option can be set in
476 # $need to convert the path from utf8 and convert the names to utf8.
478 # If IO::Dirent is successful if will get type and inode for free.
479 # Otherwise, a stat is done on each file, which is more expensive.
483 my($bpc, $path, $need) = @_;
484 my(@entries, $addInode);
486 from_to($path, "utf8", $need->{charsetLegacy})
487 if ( $need->{charsetLegacy} ne "" );
488 return if ( !opendir(my $fh, $path) );
490 @entries = sort({ $a->{inode} <=> $b->{inode} } readdirent($fh));
491 map { $_->{type} = 0 + $_->{type} } @entries; # make type numeric
493 @entries = map { { name => $_} } readdir($fh);
496 if ( defined($need) ) {
497 for ( my $i = 0 ; $i < @entries ; $i++ ) {
498 next if ( (!$need->{inode} || defined($entries[$i]{inode}))
499 && (!$need->{type} || defined($entries[$i]{type}))
500 && (!$need->{nlink} || defined($entries[$i]{nlink})) );
501 my @s = stat("$path/$entries[$i]{name}");
502 $entries[$i]{nlink} = $s[3] if ( $need->{nlink} );
503 if ( $need->{inode} && !defined($entries[$i]{inode}) ) {
505 $entries[$i]{inode} = $s[1];
507 if ( $need->{type} && !defined($entries[$i]{type}) ) {
508 my $mode = S_IFMT($s[2]);
509 $entries[$i]{type} = BPC_DT_FIFO if ( S_ISFIFO($mode) );
510 $entries[$i]{type} = BPC_DT_CHR if ( S_ISCHR($mode) );
511 $entries[$i]{type} = BPC_DT_DIR if ( S_ISDIR($mode) );
512 $entries[$i]{type} = BPC_DT_BLK if ( S_ISBLK($mode) );
513 $entries[$i]{type} = BPC_DT_REG if ( S_ISREG($mode) );
514 $entries[$i]{type} = BPC_DT_LNK if ( S_ISLNK($mode) );
515 $entries[$i]{type} = BPC_DT_SOCK if ( S_ISSOCK($mode) );
520 # Sort the entries if inodes were added (the IO::Dirent case already
523 @entries = sort({ $a->{inode} <=> $b->{inode} } @entries) if ( $addInode );
525 # for browing pre-3.0.0 backups, map iso-8859-1 to utf8 if requested
527 if ( $need->{charsetLegacy} ne "" ) {
528 for ( my $i = 0 ; $i < @entries ; $i++ ) {
529 from_to($entries[$i]{name}, $need->{charsetLegacy}, "utf8");
536 # Same as dirRead, but only returns the names (which will be sorted in
537 # inode order if IO::Dirent is installed)
541 my($bpc, $path, $need) = @_;
543 my $entries = $bpc->dirRead($path, $need);
544 return if ( !defined($entries) );
545 my @names = map { $_->{name} } @$entries;
551 my($bpc, $param, $dir, $dontDoCwd) = @_;
553 return if ( !chdir($dir) );
554 my $entries = $bpc->dirRead(".", {inode => 1, type => 1});
555 #print Dumper($entries);
556 foreach my $f ( @$entries ) {
557 next if ( $f->{name} eq ".." || $f->{name} eq "." && $dontDoCwd );
558 $param->{wanted}($f->{name}, "$dir/$f->{name}");
559 next if ( $f->{type} != BPC_DT_DIR || $f->{name} eq "." );
561 $bpc->find($param, "$dir/$f->{name}", 1);
562 return if ( !chdir("..") );
567 # Stripped down from File::Path. In particular we don't print
568 # many warnings and we try three times to delete each directory
569 # and file -- for some reason the original File::Path rmtree
570 # didn't always completely remove a directory tree on a NetApp.
572 # Warning: this routine changes the cwd.
576 my($bpc, $pwd, $roots) = @_;
579 if ( defined($roots) && length($roots) ) {
580 $roots = [$roots] unless ref $roots;
582 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
585 foreach $root (@{$roots}) {
586 $root = $1 if ( $root =~ m{(.*?)/*$} );
588 # Try first to simply unlink the file: this avoids an
589 # extra stat for every file. If it fails (which it
590 # will for directories), check if it is a directory and
593 if ( !unlink($root) ) {
595 my $d = $bpc->dirReadNames($root);
596 if ( !defined($d) ) {
597 print(STDERR "Can't read $pwd/$root: $!\n");
599 @files = grep $_ !~ /^\.{1,2}$/, @$d;
600 $bpc->RmTreeQuiet("$pwd/$root", \@files);
602 rmdir($root) || rmdir($root);
605 unlink($root) || unlink($root);
612 # Move a directory or file away for later deletion
616 my($bpc, $trashDir, $file) = @_;
619 return if ( !-e $file );
620 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
621 for ( $i = 0 ; $i < 1000 ; $i++ ) {
622 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
624 return if ( rename($file, $f) );
626 # shouldn't get here, but might if you tried to call this
627 # across file systems.... just remove the tree right now.
628 if ( $file =~ /(.*)\/([^\/]*)/ ) {
631 my($cwd) = Cwd::fastcwd();
632 $cwd = $1 if ( $cwd =~ /(.*)/ );
633 $bpc->RmTreeQuiet($d, $f);
634 chdir($cwd) if ( $cwd );
639 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
640 # did something, -1 if it failed to remove all the files.
644 my($bpc, $trashDir) = @_;
646 my($cwd) = Cwd::fastcwd();
648 $cwd = $1 if ( $cwd =~ /(.*)/ );
649 return if ( !-d $trashDir );
650 my $d = $bpc->dirReadNames($trashDir) or carp "Can't read $trashDir: $!";
651 @files = grep $_ !~ /^\.{1,2}$/, @$d;
652 return 0 if ( !@files );
653 $bpc->RmTreeQuiet($trashDir, \@files);
654 foreach my $f ( @files ) {
655 return -1 if ( -e $f );
657 chdir($cwd) if ( $cwd );
662 # Open a connection to the server. Returns an error string on failure.
663 # Returns undef on success.
667 my($bpc, $host, $port, $justConnect) = @_;
670 return if ( defined($bpc->{ServerFD}) );
672 # First try the unix-domain socket
674 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
675 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
676 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
677 my $err = "unix connect: $!";
680 my $proto = getprotobyname('tcp');
681 my $iaddr = inet_aton($host) || return "unknown host $host";
682 my $paddr = sockaddr_in($port, $iaddr);
684 socket(*FH, PF_INET, SOCK_STREAM, $proto)
685 || return "inet socket: $!";
686 connect(*FH, $paddr) || return "inet connect: $!";
691 my($oldFH) = select(*FH); $| = 1; select($oldFH);
692 $bpc->{ServerFD} = *FH;
693 return if ( $justConnect );
695 # Read the seed that we need for our MD5 message digest. See
698 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
699 $bpc->{ServerMesgCnt} = 0;
704 # Check that the server connection is still ok
710 return 0 if ( !defined($bpc->{ServerFD}) );
711 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
713 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
714 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
718 # Disconnect from the server
723 return if ( !defined($bpc->{ServerFD}) );
724 close($bpc->{ServerFD});
725 delete($bpc->{ServerFD});
729 # Sends a message to the server and returns with the reply.
731 # To avoid possible attacks via the TCP socket interface, every client
732 # message is protected by an MD5 digest. The MD5 digest includes four
734 # - a seed that is sent to us when we first connect
735 # - a sequence number that increments for each message
736 # - a shared secret that is stored in $Conf{ServerMesgSecret}
737 # - the message itself.
738 # The message is sent in plain text preceded by the MD5 digest. A
739 # snooper can see the plain-text seed sent by BackupPC and plain-text
740 # message, but cannot construct a valid MD5 digest since the secret in
741 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
742 # since the seed changes on a per-connection and per-message basis.
746 my($bpc, $mesg) = @_;
747 return if ( !defined(my $fh = $bpc->{ServerFD}) );
750 my $md5 = Digest::MD5->new;
751 $mesg = encode_utf8($mesg);
752 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
753 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
754 print($fh $md5->b64digest . " $mesg\n");
755 $bpc->{ServerMesgCnt}++;
760 # Do initialization for child processes
766 open(STDERR, ">&STDOUT");
767 select(STDERR); $| = 1;
768 select(STDOUT); $| = 1;
769 $ENV{PATH} = $bpc->{Conf}{MyPath};
773 # Compute the MD5 digest of a file. For efficiency we don't
774 # use the whole file for big files:
775 # - for files <= 256K we use the file size and the whole file.
776 # - for files <= 1M we use the file size, the first 128K and
778 # - for files > 1M, we use the file size, the first 128K and
779 # the 8th 128K (ie: the 128K up to 1MB).
780 # See the documentation for a discussion of the tradeoffs in
781 # how much data we use and how many collisions we get.
783 # Returns the MD5 digest (a hex string) and the file size.
787 my($bpc, $md5, $name) = @_;
788 my($data, $fileSize);
791 $fileSize = (stat($name))[7];
792 return ("", -1) if ( !-f _ );
793 $name = $1 if ( $name =~ /(.*)/ );
794 return ("", 0) if ( $fileSize == 0 );
795 return ("", -1) if ( !open(N, $name) );
798 $md5->add($fileSize);
799 if ( $fileSize > 262144 ) {
801 # read the first and last 131072 bytes of the file,
804 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
805 $md5->add($data) if ( sysread(N, $data, 131072) );
806 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
807 && sysread(N, $data, 131072) );
810 # read the whole file
812 $md5->add($data) if ( sysread(N, $data, $fileSize) );
815 return ($md5->hexdigest, $fileSize);
819 # Compute the MD5 digest of a buffer (string). For efficiency we don't
820 # use the whole string for big strings:
821 # - for files <= 256K we use the file size and the whole file.
822 # - for files <= 1M we use the file size, the first 128K and
824 # - for files > 1M, we use the file size, the first 128K and
825 # the 8th 128K (ie: the 128K up to 1MB).
826 # See the documentation for a discussion of the tradeoffs in
827 # how much data we use and how many collisions we get.
829 # Returns the MD5 digest (a hex string).
833 my($bpc, $md5, $fileSize, $dataRef) = @_;
836 $md5->add($fileSize);
837 if ( $fileSize > 262144 ) {
839 # add the first and last 131072 bytes of the string,
842 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
843 $md5->add(substr($$dataRef, 0, 131072));
844 $md5->add(substr($$dataRef, $seekPosn, 131072));
847 # add the whole string
849 $md5->add($$dataRef);
851 return $md5->hexdigest;
855 # Given an MD5 digest $d and a compress flag, return the full
860 my($bpc, $d, $compress, $poolDir) = @_;
862 return if ( $d !~ m{(.)(.)(.)(.*)} );
863 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
864 if ( !defined($poolDir) );
865 return "$poolDir/$1/$2/$3/$1$2$3$4";
869 # For each file, check if the file exists in $bpc->{TopDir}/pool.
870 # If so, remove the file and make a hardlink to the file in
871 # the pool. Otherwise, if the newFile flag is set, make a
872 # hardlink in the pool to the new file.
874 # Returns 0 if a link should be made to a new file (ie: when the file
875 # is a new file but the newFile flag is 0).
876 # Returns 1 if a link to an existing file is made,
877 # Returns 2 if a link to a new file is made (only if $newFile is set)
878 # Returns negative on error.
882 my($bpc, $name, $d, $newFile, $compress) = @_;
885 return -1 if ( !-f $name );
886 for ( $i = -1 ; ; $i++ ) {
887 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
888 $rawFile .= "_$i" if ( $i >= 0 );
890 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
891 && !compare($name, $rawFile) ) {
893 return -3 if ( !link($rawFile, $name) );
896 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
898 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
899 mkpath($newDir, 0, 0777) if ( !-d $newDir );
900 return -4 if ( !link($name, $rawFile) );
909 # Tests if we can create a hardlink from a file in directory
910 # $newDir to a file in directory $targetDir. A temporary
911 # file in $targetDir is created and an attempt to create a
912 # hardlink of the same name in $newDir is made. The temporary
915 # Like link(), returns true on success and false on failure.
919 my($bpc, $targetDir, $newDir) = @_;
921 my($targetFile, $newFile, $fd);
922 for ( my $i = 0 ; ; $i++ ) {
923 $targetFile = "$targetDir/.TestFileLink.$$.$i";
924 $newFile = "$newDir/.TestFileLink.$$.$i";
925 last if ( !-e $targetFile && !-e $newFile );
927 return 0 if ( !open($fd, ">", $targetFile) );
929 my $ret = link($targetFile, $newFile);
937 my($bpc, $host) = @_;
938 my($s, $pingCmd, $ret);
941 # Return success if the ping cmd is undefined or empty.
943 if ( $bpc->{Conf}{PingCmd} eq "" ) {
944 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
945 . " is empty\n") if ( $bpc->{verbose} );
950 pingPath => $bpc->{Conf}{PingPath},
953 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
956 # Do a first ping in case the PC needs to wakeup
958 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
960 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
961 if ( $bpc->{verbose} );
966 # Do a second ping and get the round-trip time in msec
968 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
970 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
971 if ( $bpc->{verbose} );
974 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
976 $ret /= 1000 if ( lc($2) eq "usec" );
977 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
979 $ret /= 1000 if ( lc($2) eq "usec" );
981 print(STDERR "CheckHostAlive: can't extract round-trip time"
982 . " (not fatal)\n") if ( $bpc->{verbose} );
985 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
989 sub CheckFileSystemUsage
992 my($topDir) = $bpc->{TopDir};
995 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
997 dfPath => $bpc->{Conf}{DfPath},
998 topDir => $bpc->{TopDir},
1000 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
1001 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
1002 return 0 if ( $? || $s !~ /(\d+)%/s );
1007 # Given an IP address, return the host name and user name via
1012 my($bpc, $host) = @_;
1013 my($netBiosHostName, $netBiosUserName);
1017 # Skip NetBios check if NmbLookupCmd is emtpy
1019 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
1020 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
1021 . " is empty\n") if ( $bpc->{verbose} );
1022 return ($host, undef);
1026 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1029 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
1030 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
1031 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
1032 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
1033 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
1035 if ( !defined($netBiosHostName) ) {
1036 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
1037 if ( $bpc->{verbose} );
1040 $netBiosHostName = lc($netBiosHostName);
1041 $netBiosUserName = lc($netBiosUserName);
1042 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
1043 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
1044 return ($netBiosHostName, $netBiosUserName);
1048 # Given a NetBios name lookup the IP address via NetBios.
1049 # In the case of a host returning multiple interfaces we
1050 # return the first IP address that matches the subnet mask.
1051 # If none match the subnet mask (or nmblookup doesn't print
1052 # the subnet mask) then just the first IP address is returned.
1054 sub NetBiosHostIPFind
1056 my($bpc, $host) = @_;
1057 my($netBiosHostName, $netBiosUserName);
1058 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
1061 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
1063 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
1064 print(STDERR "NetBiosHostIPFind: return $host because"
1065 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
1066 if ( $bpc->{verbose} );
1071 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1074 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
1075 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
1077 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
1079 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
1080 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
1082 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
1083 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
1086 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
1087 if ( defined($ipAddr) ) {
1088 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
1089 . " host $host\n") if ( $bpc->{verbose} );
1092 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
1093 . " host $host\n") if ( $bpc->{verbose} );
1098 sub fileNameEltMangle
1100 my($bpc, $name) = @_;
1102 return "" if ( $name eq "" );
1103 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
1108 # We store files with every name preceded by "f". This
1109 # avoids possible name conflicts with other information
1110 # we store in the same directories (eg: attribute info).
1111 # The process of turning a normal path into one with each
1112 # node prefixed with "f" is called mangling.
1116 my($bpc, $name) = @_;
1118 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
1119 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
1124 # This undoes FileNameMangle
1126 sub fileNameUnmangle
1128 my($bpc, $name) = @_;
1132 $name =~ s{%(..)}{chr(hex($1))}eg;
1137 # Escape shell meta-characters with backslashes.
1138 # This should be applied to each argument seperately, not an
1139 # entire shell command.
1143 my($bpc, $cmd) = @_;
1145 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
1150 # For printing exec commands (which don't use a shell) so they look like
1151 # a valid shell command this function should be called with the exec
1152 # args. The shell command string is returned.
1154 sub execCmd2ShellCmd
1156 my($bpc, @args) = @_;
1159 foreach my $a ( @args ) {
1160 $str .= " " if ( $str ne "" );
1161 $str .= $bpc->shellEscape($a);
1167 # Do a URI-style escape to protect/encode special characters
1172 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1177 # Do a URI-style unescape to restore special characters
1182 $s =~ s{%(..)}{chr(hex($1))}eg;
1187 # Do variable substitution prior to execution of a command.
1189 sub cmdVarSubstitute
1191 my($bpc, $template, $vars) = @_;
1195 # Return without any substitution if the first entry starts with "&",
1196 # indicating this is perl code.
1198 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1201 if ( ref($template) ne "ARRAY" ) {
1203 # Split at white space, except if escaped by \
1205 $template = [split(/(?<!\\)\s+/, $template)];
1207 # Remove the \ that escaped white space.
1209 foreach ( @$template ) {
1214 # Merge variables into @tarClientCmd
1216 foreach my $arg ( @$template ) {
1218 # Replace scalar variables first
1220 $arg =~ s{\$(\w+)(\+?)}{
1221 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1222 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1226 # Now replicate any array arguments; this just works for just one
1227 # array var in each argument.
1229 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1234 foreach my $v ( @{$vars->{$var}} ) {
1235 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1236 push(@cmd, "$pre$v$post");
1246 # Exec or eval a command. $cmd is either a string on an array ref.
1248 # @args are optional arguments for the eval() case; they are not used
1253 my($bpc, $cmd, @args) = @_;
1255 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1256 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1257 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1258 if ( $bpc->{verbose} );
1260 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1263 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1264 print(STDERR "cmdExecOrEval: about to exec ",
1265 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1266 if ( $bpc->{verbose} );
1268 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1270 # force list-form of exec(), ie: no shell even for 1 arg
1272 exec { $cmd->[0] } @$cmd;
1273 print(STDERR "Exec failed for @$cmd\n");
1279 # System or eval a command. $cmd is either a string on an array ref.
1280 # $stdoutCB is a callback for output generated by the command. If it
1281 # is undef then output is returned. If it is a code ref then the function
1282 # is called with each piece of output as an argument. If it is a scalar
1283 # ref the output is appended to this variable.
1285 # @args are optional arguments for the eval() case; they are not used
1288 # Also, $? should be set when the CHILD pipe is closed.
1290 sub cmdSystemOrEvalLong
1292 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1293 my($pid, $out, $allOut);
1297 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1298 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1299 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1300 if ( $bpc->{verbose} );
1302 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1303 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1304 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1305 if ( $bpc->{verbose} );
1306 return $out if ( !defined($stdoutCB) );
1309 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1310 print(STDERR "cmdSystemOrEval: about to system ",
1311 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1312 if ( $bpc->{verbose} );
1313 if ( !defined($pid = open(CHILD, "-|")) ) {
1314 my $err = "Can't fork to run @$cmd\n";
1316 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1317 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1318 return $err if ( !defined($stdoutCB) );
1327 if ( $ignoreStderr ) {
1328 open(STDERR, ">", "/dev/null");
1330 open(STDERR, ">&STDOUT");
1333 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1335 # force list-form of exec(), ie: no shell even for 1 arg
1337 exec { $cmd->[0] } @$cmd;
1338 print(STDERR "Exec of @$cmd failed\n");
1343 # Notify caller of child's pid
1345 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1348 # The parent gathers the output from the child
1351 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1352 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1353 $out .= $_ if ( !defined($stdoutCB) );
1354 $allOut .= $_ if ( $bpc->{verbose} );
1359 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1360 if ( $bpc->{verbose} );
1365 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1366 # and stderr together.
1370 my($bpc, $cmd, $stdoutCB, @args) = @_;
1372 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1376 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1377 # to hashes and $conf->{$shareName} to an array.
1379 sub backupFileConfFix
1381 my($bpc, $conf, $shareName) = @_;
1383 $conf->{$shareName} = [ $conf->{$shareName} ]
1384 if ( ref($conf->{$shareName}) ne "ARRAY" );
1385 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1386 next if ( !defined($conf->{$param}) );
1387 if ( ref($conf->{$param}) eq "HASH" ) {
1389 # A "*" entry means wildcard - it is the default for
1390 # all shares. Replicate the "*" entry for all shares,
1391 # but still allow override of specific entries.
1393 next if ( !defined($conf->{$param}{"*"}) );
1395 map({ $_ => $conf->{$param}{"*"} }
1396 @{$conf->{$shareName}}),
1400 $conf->{$param} = [ $conf->{$param} ]
1401 if ( ref($conf->{$param}) ne "ARRAY" );
1402 $conf->{$param} = { map { $_ => $conf->{$param} }
1403 @{$conf->{$shareName}} };
1409 # This is sort() compare function, used below.
1411 # New client LOG names are LOG.MMYYYY. Old style names are
1412 # LOG, LOG.0, LOG.1 etc. Sort them so new names are
1413 # first, and newest to oldest.
1417 my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1418 my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1420 $na = -1 if ( !defined($na) );
1421 $nb = -1 if ( !defined($nb) );
1423 if ( length($na) >= 5 && length($nb) >= 5 ) {
1425 # Both new style: format is MMYYYY. Bigger dates are
1428 my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1429 my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1431 } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1433 } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1437 # Both old style. Smaller numbers are more recent.
1444 # Returns list of paths to a clients's (or main) LOG files,
1445 # most recent first.
1447 sub sortedPCLogFiles
1449 my($bpc, $host) = @_;
1453 if ( $host ne "" ) {
1454 $dir = "$bpc->{TopDir}/pc/$host";
1456 $dir = "$bpc->{LogDir}";
1458 if ( opendir(DIR, $dir) ) {
1459 foreach my $file ( readdir(DIR) ) {
1460 next if ( !-f "$dir/$file" );
1461 next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1462 push(@files, "$dir/$file");
1466 return sort(compareLOGName @files);