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.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 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",
146 Version => '3.1.0beta0',
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;
416 # Return the mtime of the config file
422 return $bpc->{storage}->ConfigMTime();
426 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
427 # With no argument a ref to a hash of hosts is returned. Each
428 # hash contains fields as specified in the hosts file. With an
429 # argument a ref to a single hash is returned with information
430 # for just that host.
434 my($bpc, $host) = @_;
436 return $bpc->{storage}->HostInfoRead($host);
441 my($bpc, $host) = @_;
443 return $bpc->{storage}->HostInfoWrite($host);
447 # Return the mtime of the hosts file
453 return $bpc->{storage}->HostsMTime();
457 # Read a directory and return the entries in sorted inode order.
458 # This relies on the IO::Dirent module being installed. If not,
459 # the inode data is empty and the default directory order is
462 # The returned data is a list of hashes with entries {name, type, inode, nlink}.
463 # The returned data includes "." and "..".
465 # $need is a hash of file attributes we need: type, inode, or nlink.
466 # If set, these parameters are added to the returned hash.
468 # To support browsing pre-3.0.0 backups where the charset encoding
469 # is typically iso-8859-1, the charsetLegacy option can be set in
470 # $need to convert the path from utf8 and convert the names to utf8.
472 # If IO::Dirent is successful if will get type and inode for free.
473 # Otherwise, a stat is done on each file, which is more expensive.
477 my($bpc, $path, $need) = @_;
478 my(@entries, $addInode);
480 from_to($path, "utf8", $need->{charsetLegacy})
481 if ( $need->{charsetLegacy} ne "" );
482 return if ( !opendir(my $fh, $path) );
484 @entries = sort({ $a->{inode} <=> $b->{inode} } readdirent($fh));
485 map { $_->{type} = 0 + $_->{type} } @entries; # make type numeric
487 @entries = map { { name => $_} } readdir($fh);
490 if ( defined($need) ) {
491 for ( my $i = 0 ; $i < @entries ; $i++ ) {
492 next if ( (!$need->{inode} || defined($entries[$i]{inode}))
493 && (!$need->{type} || defined($entries[$i]{type}))
494 && (!$need->{nlink} || defined($entries[$i]{nlink})) );
495 my @s = stat("$path/$entries[$i]{name}");
496 $entries[$i]{nlink} = $s[3] if ( $need->{nlink} );
497 if ( $need->{inode} && !defined($entries[$i]{inode}) ) {
499 $entries[$i]{inode} = $s[1];
501 if ( $need->{type} && !defined($entries[$i]{type}) ) {
502 my $mode = S_IFMT($s[2]);
503 $entries[$i]{type} = BPC_DT_FIFO if ( S_ISFIFO($mode) );
504 $entries[$i]{type} = BPC_DT_CHR if ( S_ISCHR($mode) );
505 $entries[$i]{type} = BPC_DT_DIR if ( S_ISDIR($mode) );
506 $entries[$i]{type} = BPC_DT_BLK if ( S_ISBLK($mode) );
507 $entries[$i]{type} = BPC_DT_REG if ( S_ISREG($mode) );
508 $entries[$i]{type} = BPC_DT_LNK if ( S_ISLNK($mode) );
509 $entries[$i]{type} = BPC_DT_SOCK if ( S_ISSOCK($mode) );
514 # Sort the entries if inodes were added (the IO::Dirent case already
517 @entries = sort({ $a->{inode} <=> $b->{inode} } @entries) if ( $addInode );
519 # for browing pre-3.0.0 backups, map iso-8859-1 to utf8 if requested
521 if ( $need->{charsetLegacy} ne "" ) {
522 for ( my $i = 0 ; $i < @entries ; $i++ ) {
523 from_to($entries[$i]{name}, $need->{charsetLegacy}, "utf8");
530 # Same as dirRead, but only returns the names (which will be sorted in
531 # inode order if IO::Dirent is installed)
535 my($bpc, $path, $need) = @_;
537 my $entries = $bpc->dirRead($path, $need);
538 return if ( !defined($entries) );
539 my @names = map { $_->{name} } @$entries;
545 my($bpc, $param, $dir, $dontDoCwd) = @_;
547 return if ( !chdir($dir) );
548 my $entries = $bpc->dirRead(".", {inode => 1, type => 1});
549 #print Dumper($entries);
550 foreach my $f ( @$entries ) {
551 next if ( $f->{name} eq ".." || $f->{name} eq "." && $dontDoCwd );
552 $param->{wanted}($f->{name}, "$dir/$f->{name}");
553 next if ( $f->{type} != BPC_DT_DIR || $f->{name} eq "." );
555 $bpc->find($param, "$dir/$f->{name}", 1);
556 return if ( !chdir("..") );
561 # Stripped down from File::Path. In particular we don't print
562 # many warnings and we try three times to delete each directory
563 # and file -- for some reason the original File::Path rmtree
564 # didn't always completely remove a directory tree on a NetApp.
566 # Warning: this routine changes the cwd.
570 my($bpc, $pwd, $roots) = @_;
573 if ( defined($roots) && length($roots) ) {
574 $roots = [$roots] unless ref $roots;
576 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
579 foreach $root (@{$roots}) {
580 $root = $1 if ( $root =~ m{(.*?)/*$} );
582 # Try first to simply unlink the file: this avoids an
583 # extra stat for every file. If it fails (which it
584 # will for directories), check if it is a directory and
587 if ( !unlink($root) ) {
589 my $d = $bpc->dirReadNames($root);
590 if ( !defined($d) ) {
591 print(STDERR "Can't read $pwd/$root: $!\n");
593 @files = grep $_ !~ /^\.{1,2}$/, @$d;
594 $bpc->RmTreeQuiet("$pwd/$root", \@files);
596 rmdir($root) || rmdir($root);
599 unlink($root) || unlink($root);
606 # Move a directory or file away for later deletion
610 my($bpc, $trashDir, $file) = @_;
613 return if ( !-e $file );
614 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
615 for ( $i = 0 ; $i < 1000 ; $i++ ) {
616 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
618 return if ( rename($file, $f) );
620 # shouldn't get here, but might if you tried to call this
621 # across file systems.... just remove the tree right now.
622 if ( $file =~ /(.*)\/([^\/]*)/ ) {
625 my($cwd) = Cwd::fastcwd();
626 $cwd = $1 if ( $cwd =~ /(.*)/ );
627 $bpc->RmTreeQuiet($d, $f);
628 chdir($cwd) if ( $cwd );
633 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
634 # did something, -1 if it failed to remove all the files.
638 my($bpc, $trashDir) = @_;
640 my($cwd) = Cwd::fastcwd();
642 $cwd = $1 if ( $cwd =~ /(.*)/ );
643 return if ( !-d $trashDir );
644 my $d = $bpc->dirReadNames($trashDir) or carp "Can't read $trashDir: $!";
645 @files = grep $_ !~ /^\.{1,2}$/, @$d;
646 return 0 if ( !@files );
647 $bpc->RmTreeQuiet($trashDir, \@files);
648 foreach my $f ( @files ) {
649 return -1 if ( -e $f );
651 chdir($cwd) if ( $cwd );
656 # Open a connection to the server. Returns an error string on failure.
657 # Returns undef on success.
661 my($bpc, $host, $port, $justConnect) = @_;
664 return if ( defined($bpc->{ServerFD}) );
666 # First try the unix-domain socket
668 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
669 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
670 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
671 my $err = "unix connect: $!";
674 my $proto = getprotobyname('tcp');
675 my $iaddr = inet_aton($host) || return "unknown host $host";
676 my $paddr = sockaddr_in($port, $iaddr);
678 socket(*FH, PF_INET, SOCK_STREAM, $proto)
679 || return "inet socket: $!";
680 connect(*FH, $paddr) || return "inet connect: $!";
685 my($oldFH) = select(*FH); $| = 1; select($oldFH);
686 $bpc->{ServerFD} = *FH;
687 return if ( $justConnect );
689 # Read the seed that we need for our MD5 message digest. See
692 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
693 $bpc->{ServerMesgCnt} = 0;
698 # Check that the server connection is still ok
704 return 0 if ( !defined($bpc->{ServerFD}) );
705 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
707 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
708 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
712 # Disconnect from the server
717 return if ( !defined($bpc->{ServerFD}) );
718 close($bpc->{ServerFD});
719 delete($bpc->{ServerFD});
723 # Sends a message to the server and returns with the reply.
725 # To avoid possible attacks via the TCP socket interface, every client
726 # message is protected by an MD5 digest. The MD5 digest includes four
728 # - a seed that is sent to us when we first connect
729 # - a sequence number that increments for each message
730 # - a shared secret that is stored in $Conf{ServerMesgSecret}
731 # - the message itself.
732 # The message is sent in plain text preceded by the MD5 digest. A
733 # snooper can see the plain-text seed sent by BackupPC and plain-text
734 # message, but cannot construct a valid MD5 digest since the secret in
735 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
736 # since the seed changes on a per-connection and per-message basis.
740 my($bpc, $mesg) = @_;
741 return if ( !defined(my $fh = $bpc->{ServerFD}) );
744 my $md5 = Digest::MD5->new;
745 $mesg = encode_utf8($mesg);
746 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
747 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
748 print($fh $md5->b64digest . " $mesg\n");
749 $bpc->{ServerMesgCnt}++;
754 # Do initialization for child processes
760 open(STDERR, ">&STDOUT");
761 select(STDERR); $| = 1;
762 select(STDOUT); $| = 1;
763 $ENV{PATH} = $bpc->{Conf}{MyPath};
767 # Compute the MD5 digest of a file. For efficiency we don't
768 # use the whole file for big files:
769 # - for files <= 256K we use the file size and the whole file.
770 # - for files <= 1M we use the file size, the first 128K and
772 # - for files > 1M, we use the file size, the first 128K and
773 # the 8th 128K (ie: the 128K up to 1MB).
774 # See the documentation for a discussion of the tradeoffs in
775 # how much data we use and how many collisions we get.
777 # Returns the MD5 digest (a hex string) and the file size.
781 my($bpc, $md5, $name) = @_;
782 my($data, $fileSize);
785 $fileSize = (stat($name))[7];
786 return ("", -1) if ( !-f _ );
787 $name = $1 if ( $name =~ /(.*)/ );
788 return ("", 0) if ( $fileSize == 0 );
789 return ("", -1) if ( !open(N, $name) );
792 $md5->add($fileSize);
793 if ( $fileSize > 262144 ) {
795 # read the first and last 131072 bytes of the file,
798 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
799 $md5->add($data) if ( sysread(N, $data, 131072) );
800 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
801 && sysread(N, $data, 131072) );
804 # read the whole file
806 $md5->add($data) if ( sysread(N, $data, $fileSize) );
809 return ($md5->hexdigest, $fileSize);
813 # Compute the MD5 digest of a buffer (string). For efficiency we don't
814 # use the whole string for big strings:
815 # - for files <= 256K we use the file size and the whole file.
816 # - for files <= 1M we use the file size, the first 128K and
818 # - for files > 1M, we use the file size, the first 128K and
819 # the 8th 128K (ie: the 128K up to 1MB).
820 # See the documentation for a discussion of the tradeoffs in
821 # how much data we use and how many collisions we get.
823 # Returns the MD5 digest (a hex string).
827 my($bpc, $md5, $fileSize, $dataRef) = @_;
830 $md5->add($fileSize);
831 if ( $fileSize > 262144 ) {
833 # add the first and last 131072 bytes of the string,
836 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
837 $md5->add(substr($$dataRef, 0, 131072));
838 $md5->add(substr($$dataRef, $seekPosn, 131072));
841 # add the whole string
843 $md5->add($$dataRef);
845 return $md5->hexdigest;
849 # Given an MD5 digest $d and a compress flag, return the full
854 my($bpc, $d, $compress, $poolDir) = @_;
856 return if ( $d !~ m{(.)(.)(.)(.*)} );
857 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
858 if ( !defined($poolDir) );
859 return "$poolDir/$1/$2/$3/$1$2$3$4";
863 # For each file, check if the file exists in $bpc->{TopDir}/pool.
864 # If so, remove the file and make a hardlink to the file in
865 # the pool. Otherwise, if the newFile flag is set, make a
866 # hardlink in the pool to the new file.
868 # Returns 0 if a link should be made to a new file (ie: when the file
869 # is a new file but the newFile flag is 0).
870 # Returns 1 if a link to an existing file is made,
871 # Returns 2 if a link to a new file is made (only if $newFile is set)
872 # Returns negative on error.
876 my($bpc, $name, $d, $newFile, $compress) = @_;
879 return -1 if ( !-f $name );
880 for ( $i = -1 ; ; $i++ ) {
881 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
882 $rawFile .= "_$i" if ( $i >= 0 );
884 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
885 && !compare($name, $rawFile) ) {
887 return -3 if ( !link($rawFile, $name) );
890 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
892 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
893 mkpath($newDir, 0, 0777) if ( !-d $newDir );
894 return -4 if ( !link($name, $rawFile) );
903 # Tests if we can create a hardlink from a file in directory
904 # $newDir to a file in directory $targetDir. A temporary
905 # file in $targetDir is created and an attempt to create a
906 # hardlink of the same name in $newDir is made. The temporary
909 # Like link(), returns true on success and false on failure.
913 my($bpc, $targetDir, $newDir) = @_;
915 my($targetFile, $newFile, $fd);
916 for ( my $i = 0 ; ; $i++ ) {
917 $targetFile = "$targetDir/.TestFileLink.$$.$i";
918 $newFile = "$newDir/.TestFileLink.$$.$i";
919 last if ( !-e $targetFile && !-e $newFile );
921 return 0 if ( !open($fd, ">", $targetFile) );
923 my $ret = link($targetFile, $newFile);
931 my($bpc, $host) = @_;
932 my($s, $pingCmd, $ret);
935 # Return success if the ping cmd is undefined or empty.
937 if ( $bpc->{Conf}{PingCmd} eq "" ) {
938 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
939 . " is empty\n") if ( $bpc->{verbose} );
944 pingPath => $bpc->{Conf}{PingPath},
947 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
950 # Do a first ping in case the PC needs to wakeup
952 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
954 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
955 if ( $bpc->{verbose} );
960 # Do a second ping and get the round-trip time in msec
962 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
964 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
965 if ( $bpc->{verbose} );
968 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
970 $ret /= 1000 if ( lc($2) eq "usec" );
971 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
973 $ret /= 1000 if ( lc($2) eq "usec" );
975 print(STDERR "CheckHostAlive: can't extract round-trip time"
976 . " (not fatal)\n") if ( $bpc->{verbose} );
979 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
983 sub CheckFileSystemUsage
986 my($topDir) = $bpc->{TopDir};
989 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
991 dfPath => $bpc->{Conf}{DfPath},
992 topDir => $bpc->{TopDir},
994 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
995 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
996 return 0 if ( $? || $s !~ /(\d+)%/s );
1001 # Given an IP address, return the host name and user name via
1006 my($bpc, $host) = @_;
1007 my($netBiosHostName, $netBiosUserName);
1011 # Skip NetBios check if NmbLookupCmd is emtpy
1013 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
1014 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
1015 . " is empty\n") if ( $bpc->{verbose} );
1016 return ($host, undef);
1020 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1023 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
1024 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
1025 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
1026 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
1027 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
1029 if ( !defined($netBiosHostName) ) {
1030 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
1031 if ( $bpc->{verbose} );
1034 $netBiosHostName = lc($netBiosHostName);
1035 $netBiosUserName = lc($netBiosUserName);
1036 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
1037 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
1038 return ($netBiosHostName, $netBiosUserName);
1042 # Given a NetBios name lookup the IP address via NetBios.
1043 # In the case of a host returning multiple interfaces we
1044 # return the first IP address that matches the subnet mask.
1045 # If none match the subnet mask (or nmblookup doesn't print
1046 # the subnet mask) then just the first IP address is returned.
1048 sub NetBiosHostIPFind
1050 my($bpc, $host) = @_;
1051 my($netBiosHostName, $netBiosUserName);
1052 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
1055 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
1057 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
1058 print(STDERR "NetBiosHostIPFind: return $host because"
1059 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
1060 if ( $bpc->{verbose} );
1065 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1068 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
1069 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
1071 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
1073 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
1074 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
1076 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
1077 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
1080 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
1081 if ( defined($ipAddr) ) {
1082 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
1083 . " host $host\n") if ( $bpc->{verbose} );
1086 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
1087 . " host $host\n") if ( $bpc->{verbose} );
1092 sub fileNameEltMangle
1094 my($bpc, $name) = @_;
1096 return "" if ( $name eq "" );
1097 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
1102 # We store files with every name preceded by "f". This
1103 # avoids possible name conflicts with other information
1104 # we store in the same directories (eg: attribute info).
1105 # The process of turning a normal path into one with each
1106 # node prefixed with "f" is called mangling.
1110 my($bpc, $name) = @_;
1112 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
1113 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
1118 # This undoes FileNameMangle
1120 sub fileNameUnmangle
1122 my($bpc, $name) = @_;
1126 $name =~ s{%(..)}{chr(hex($1))}eg;
1131 # Escape shell meta-characters with backslashes.
1132 # This should be applied to each argument seperately, not an
1133 # entire shell command.
1137 my($bpc, $cmd) = @_;
1139 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
1144 # For printing exec commands (which don't use a shell) so they look like
1145 # a valid shell command this function should be called with the exec
1146 # args. The shell command string is returned.
1148 sub execCmd2ShellCmd
1150 my($bpc, @args) = @_;
1153 foreach my $a ( @args ) {
1154 $str .= " " if ( $str ne "" );
1155 $str .= $bpc->shellEscape($a);
1161 # Do a URI-style escape to protect/encode special characters
1166 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1171 # Do a URI-style unescape to restore special characters
1176 $s =~ s{%(..)}{chr(hex($1))}eg;
1181 # Do variable substitution prior to execution of a command.
1183 sub cmdVarSubstitute
1185 my($bpc, $template, $vars) = @_;
1189 # Return without any substitution if the first entry starts with "&",
1190 # indicating this is perl code.
1192 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1195 if ( ref($template) ne "ARRAY" ) {
1197 # Split at white space, except if escaped by \
1199 $template = [split(/(?<!\\)\s+/, $template)];
1201 # Remove the \ that escaped white space.
1203 foreach ( @$template ) {
1208 # Merge variables into @tarClientCmd
1210 foreach my $arg ( @$template ) {
1212 # Replace scalar variables first
1214 $arg =~ s{\$(\w+)(\+?)}{
1215 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1216 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1220 # Now replicate any array arguments; this just works for just one
1221 # array var in each argument.
1223 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1228 foreach my $v ( @{$vars->{$var}} ) {
1229 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1230 push(@cmd, "$pre$v$post");
1240 # Exec or eval a command. $cmd is either a string on an array ref.
1242 # @args are optional arguments for the eval() case; they are not used
1247 my($bpc, $cmd, @args) = @_;
1249 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1250 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1251 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1252 if ( $bpc->{verbose} );
1254 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1257 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1258 print(STDERR "cmdExecOrEval: about to exec ",
1259 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1260 if ( $bpc->{verbose} );
1262 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1264 # force list-form of exec(), ie: no shell even for 1 arg
1266 exec { $cmd->[0] } @$cmd;
1267 print(STDERR "Exec failed for @$cmd\n");
1273 # System or eval a command. $cmd is either a string on an array ref.
1274 # $stdoutCB is a callback for output generated by the command. If it
1275 # is undef then output is returned. If it is a code ref then the function
1276 # is called with each piece of output as an argument. If it is a scalar
1277 # ref the output is appended to this variable.
1279 # @args are optional arguments for the eval() case; they are not used
1282 # Also, $? should be set when the CHILD pipe is closed.
1284 sub cmdSystemOrEvalLong
1286 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1287 my($pid, $out, $allOut);
1291 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1292 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1293 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1294 if ( $bpc->{verbose} );
1296 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1297 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1298 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1299 if ( $bpc->{verbose} );
1300 return $out if ( !defined($stdoutCB) );
1303 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1304 print(STDERR "cmdSystemOrEval: about to system ",
1305 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1306 if ( $bpc->{verbose} );
1307 if ( !defined($pid = open(CHILD, "-|")) ) {
1308 my $err = "Can't fork to run @$cmd\n";
1310 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1311 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1312 return $err if ( !defined($stdoutCB) );
1321 if ( $ignoreStderr ) {
1322 open(STDERR, ">", "/dev/null");
1324 open(STDERR, ">&STDOUT");
1327 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1329 # force list-form of exec(), ie: no shell even for 1 arg
1331 exec { $cmd->[0] } @$cmd;
1332 print(STDERR "Exec of @$cmd failed\n");
1337 # Notify caller of child's pid
1339 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1342 # The parent gathers the output from the child
1345 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1346 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1347 $out .= $_ if ( !defined($stdoutCB) );
1348 $allOut .= $_ if ( $bpc->{verbose} );
1353 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1354 if ( $bpc->{verbose} );
1359 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1360 # and stderr together.
1364 my($bpc, $cmd, $stdoutCB, @args) = @_;
1366 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1370 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1371 # to hashes and $conf->{$shareName} to an array.
1373 sub backupFileConfFix
1375 my($bpc, $conf, $shareName) = @_;
1377 $conf->{$shareName} = [ $conf->{$shareName} ]
1378 if ( ref($conf->{$shareName}) ne "ARRAY" );
1379 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1380 next if ( !defined($conf->{$param}) );
1381 if ( ref($conf->{$param}) eq "HASH" ) {
1383 # A "*" entry means wildcard - it is the default for
1384 # all shares. Replicate the "*" entry for all shares,
1385 # but still allow override of specific entries.
1387 next if ( !defined($conf->{$param}{"*"}) );
1389 map({ $_ => $conf->{$param}{"*"} }
1390 @{$conf->{$shareName}}),
1394 $conf->{$param} = [ $conf->{$param} ]
1395 if ( ref($conf->{$param}) ne "ARRAY" );
1396 $conf->{$param} = { map { $_ => $conf->{$param} }
1397 @{$conf->{$shareName}} };
1403 # This is sort() compare function, used below.
1405 # New client LOG names are LOG.MMYYYY. Old style names are
1406 # LOG, LOG.0, LOG.1 etc. Sort them so new names are
1407 # first, and newest to oldest.
1411 my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1412 my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1414 $na = -1 if ( !defined($na) );
1415 $nb = -1 if ( !defined($nb) );
1417 if ( length($na) >= 5 && length($nb) >= 5 ) {
1419 # Both new style: format is MMYYYY. Bigger dates are
1422 my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1423 my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1425 } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1427 } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1431 # Both old style. Smaller numbers are more recent.
1438 # Returns list of paths to a clients's (or main) LOG files,
1439 # most recent first.
1441 sub sortedPCLogFiles
1443 my($bpc, $host) = @_;
1447 if ( $host ne "" ) {
1448 $dir = "$bpc->{TopDir}/pc/$host";
1450 $dir = "$bpc->{LogDir}";
1452 if ( opendir(DIR, $dir) ) {
1453 foreach my $file ( readdir(DIR) ) {
1454 next if ( !-f "$dir/$file" );
1455 next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1456 push(@files, "$dir/$file");
1460 return sort(compareLOGName @files);