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.0.0, released 28 Jan 2007.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
38 package BackupPC::Lib;
42 use vars qw(%Conf %Lang);
43 use BackupPC::Storage;
53 use vars qw( $IODirentOk );
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
59 @ISA = qw(Exporter DynaLoader);
60 @EXPORT_OK = qw( BPC_DT_UNKNOWN
70 %EXPORT_TAGS = ('BPC_DT_ALL' => [@EXPORT, @EXPORT_OK]);
73 eval "use IO::Dirent qw( readdirent DT_DIR );";
74 $IODirentOk = 1 if ( !$@ );
78 # The need to match the constants in IO::Dirent
80 use constant BPC_DT_UNKNOWN => 0;
81 use constant BPC_DT_FIFO => 1; ## named pipe (fifo)
82 use constant BPC_DT_CHR => 2; ## character special
83 use constant BPC_DT_DIR => 4; ## directory
84 use constant BPC_DT_BLK => 6; ## block special
85 use constant BPC_DT_REG => 8; ## regular
86 use constant BPC_DT_LNK => 10; ## symbolic link
87 use constant BPC_DT_SOCK => 12; ## socket
92 my($topDir, $installDir, $confDir, $noUserCheck) = @_;
95 # Whether to use filesystem hierarchy standard for file layout.
96 # If set, text config files are below /etc/BackupPC.
102 # Set defaults for $topDir and $installDir.
104 $topDir = '/tera0/backup/BackupPC' if ( $topDir eq "" );
105 $installDir = '/usr/local/BackupPC' if ( $installDir eq "" );
108 # Pick some initial defaults. For FHS the only critical
109 # path is the ConfDir, since we get everything else out
110 # of the main config file.
116 InstallDir => $installDir,
117 ConfDir => $confDir eq "" ? '/etc/BackupPC' : $confDir,
118 LogDir => '/var/log/BackupPC',
124 InstallDir => $installDir,
125 ConfDir => $confDir eq "" ? "$topDir/conf" : $confDir,
126 LogDir => "$topDir/log",
135 $bpc->{storage} = BackupPC::Storage->new($paths);
138 # Clean up %ENV and setup other variables.
140 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
141 $bpc->{PoolDir} = "$bpc->{TopDir}/pool";
142 $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
143 if ( defined(my $error = $bpc->ConfigRead()) ) {
144 print(STDERR $error, "\n");
149 # Update the paths based on the config file
151 foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
152 next if ( $bpc->{Conf}{$dir} eq "" );
153 $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
155 $bpc->{storage}->setPaths($paths);
158 # Verify we are running as the correct user
161 && $bpc->{Conf}{BackupPCUserVerify}
162 && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
163 print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
164 . " ($bpc->{Conf}{BackupPCUser})\n");
165 print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
174 return $bpc->{TopDir};
180 return "$bpc->{InstallDir}/bin";
186 return $bpc->{LogDir};
192 return $bpc->{ConfDir};
198 return "$bpc->{InstallDir}/lib";
204 return $bpc->{InstallDir};
210 return $bpc->{useFHS};
216 return $bpc->{Version};
222 return %{$bpc->{Conf}};
234 return " admin " if ( !$num );
235 return " admin$num ";
241 return $str =~ /^ admin/;
246 return " trashClean ";
251 my($bpc, $param) = @_;
253 return $bpc->{Conf}{$param};
258 my($bpc, $param) = @_;
260 $bpc->{verbose} = $param if ( defined($param) );
261 return $bpc->{verbose};
268 if ( !defined($bpc->{SigName2Num}) ) {
270 foreach my $name ( split(' ', $Config{sig_name}) ) {
271 $bpc->{SigName2Num}{$name} = $i;
275 return $bpc->{SigName2Num}{$sig};
279 # Generate an ISO 8601 format timeStamp (but without the "T").
280 # See http://www.w3.org/TR/NOTE-datetime and
281 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
285 my($bpc, $t, $noPad) = @_;
286 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
287 = localtime($t || time);
288 return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
289 $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
290 . ($noPad ? "" : " ");
295 my($bpc, $host) = @_;
297 return $bpc->{storage}->BackupInfoRead($host);
302 my($bpc, $host, @Backups) = @_;
304 return $bpc->{storage}->BackupInfoWrite($host, @Backups);
309 my($bpc, $host) = @_;
311 return $bpc->{storage}->RestoreInfoRead($host);
316 my($bpc, $host, @Restores) = @_;
318 return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
323 my($bpc, $host) = @_;
325 return $bpc->{storage}->ArchiveInfoRead($host);
330 my($bpc, $host, @Archives) = @_;
332 return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
337 my($bpc, $host) = @_;
339 return $bpc->{storage}->ConfigDataRead($host);
344 my($bpc, $host, $conf) = @_;
346 return $bpc->{storage}->ConfigDataWrite($host, $conf);
351 my($bpc, $host) = @_;
355 # Read main config file
357 my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
358 return $mesg if ( defined($mesg) );
360 $bpc->{Conf} = $config;
363 # Read host config file
366 ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
367 return $mesg if ( defined($mesg) );
368 $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
372 # Load optional perl modules
374 if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
376 # Load any user-specified perl modules. This is for
377 # optional user-defined extensions.
379 $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
380 if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
381 foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
382 eval("use $module;");
389 return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
390 my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
391 if ( !defined($ret = do $langFile) && ($! || $@) ) {
392 $mesg = "Couldn't open language file $langFile: $!" if ( $! );
393 $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
394 $mesg =~ s/[\n\r]+//;
397 $bpc->{Lang} = \%Lang;
402 # Return the mtime of the config file
408 return $bpc->{storage}->ConfigMTime();
412 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
413 # With no argument a ref to a hash of hosts is returned. Each
414 # hash contains fields as specified in the hosts file. With an
415 # argument a ref to a single hash is returned with information
416 # for just that host.
420 my($bpc, $host) = @_;
422 return $bpc->{storage}->HostInfoRead($host);
427 my($bpc, $host) = @_;
429 return $bpc->{storage}->HostInfoWrite($host);
433 # Return the mtime of the hosts file
439 return $bpc->{storage}->HostsMTime();
443 # Read a directory and return the entries in sorted inode order.
444 # This relies on the IO::Dirent module being installed. If not,
445 # the inode data is empty and the default directory order is
448 # The returned data is a list of hashes with entries {name, type, inode, nlink}.
449 # The returned data includes "." and "..".
451 # $need is a hash of file attributes we need: type, inode, or nlink.
452 # If set, these parameters are added to the returned hash.
454 # If IO::Dirent is successful if will get type and inode for free.
455 # Otherwise, a stat is done on each file, which is more expensive.
459 my($bpc, $path, $need) = @_;
460 my(@entries, $addInode);
462 return if ( !opendir(my $fh, $path) );
464 @entries = sort({ $a->{inode} <=> $b->{inode} } readdirent($fh));
465 map { $_->{type} = 0 + $_->{type} } @entries; # make type numeric
467 @entries = map { { name => $_} } readdir($fh);
470 if ( defined($need) ) {
471 for ( my $i = 0 ; $i < @entries ; $i++ ) {
472 next if ( (!$need->{inode} || defined($entries[$i]{inode}))
473 && (!$need->{type} || defined($entries[$i]{type}))
474 && (!$need->{nlink} || defined($entries[$i]{nlink})) );
475 my @s = stat("$path/$entries[$i]{name}");
476 $entries[$i]{nlink} = $s[3] if ( $need->{nlink} );
477 if ( $need->{inode} && !defined($entries[$i]{inode}) ) {
479 $entries[$i]{inode} = $s[1];
481 if ( $need->{type} && !defined($entries[$i]{type}) ) {
482 my $mode = S_IFMT($s[2]);
483 $entries[$i]{type} = BPC_DT_FIFO if ( S_ISFIFO($mode) );
484 $entries[$i]{type} = BPC_DT_CHR if ( S_ISCHR($mode) );
485 $entries[$i]{type} = BPC_DT_DIR if ( S_ISDIR($mode) );
486 $entries[$i]{type} = BPC_DT_BLK if ( S_ISBLK($mode) );
487 $entries[$i]{type} = BPC_DT_REG if ( S_ISREG($mode) );
488 $entries[$i]{type} = BPC_DT_LNK if ( S_ISLNK($mode) );
489 $entries[$i]{type} = BPC_DT_SOCK if ( S_ISSOCK($mode) );
494 # Sort the entries if inodes were added (the IO::Dirent case already
497 @entries = sort({ $a->{inode} <=> $b->{inode} } @entries) if ( $addInode );
502 # Same as dirRead, but only returns the names (which will be sorted in
503 # inode order if IO::Dirent is installed)
507 my($bpc, $path) = @_;
509 my $entries = $bpc->dirRead($path);
510 return if ( !defined($entries) );
511 my @names = map { $_->{name} } @$entries;
517 my($bpc, $param, $dir, $dontDoCwd) = @_;
519 return if ( !chdir($dir) );
520 my $entries = $bpc->dirRead(".", {inode => 1, type => 1});
521 #print Dumper($entries);
522 foreach my $f ( @$entries ) {
523 next if ( $f->{name} eq ".." || $f->{name} eq "." && $dontDoCwd );
524 $param->{wanted}($f->{name}, "$dir/$f->{name}");
525 next if ( $f->{type} != BPC_DT_DIR || $f->{name} eq "." );
527 $bpc->find($param, "$dir/$f->{name}", 1);
528 return if ( !chdir("..") );
533 # Stripped down from File::Path. In particular we don't print
534 # many warnings and we try three times to delete each directory
535 # and file -- for some reason the original File::Path rmtree
536 # didn't always completely remove a directory tree on a NetApp.
538 # Warning: this routine changes the cwd.
542 my($bpc, $pwd, $roots) = @_;
545 if ( defined($roots) && length($roots) ) {
546 $roots = [$roots] unless ref $roots;
548 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
551 foreach $root (@{$roots}) {
552 $root = $1 if ( $root =~ m{(.*?)/*$} );
554 # Try first to simply unlink the file: this avoids an
555 # extra stat for every file. If it fails (which it
556 # will for directories), check if it is a directory and
559 if ( !unlink($root) ) {
561 my $d = $bpc->dirReadNames($root);
562 if ( !defined($d) ) {
563 print(STDERR "Can't read $pwd/$root: $!\n");
565 @files = grep $_ !~ /^\.{1,2}$/, @$d;
566 $bpc->RmTreeQuiet("$pwd/$root", \@files);
568 rmdir($root) || rmdir($root);
571 unlink($root) || unlink($root);
578 # Move a directory or file away for later deletion
582 my($bpc, $trashDir, $file) = @_;
585 return if ( !-e $file );
586 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
587 for ( $i = 0 ; $i < 1000 ; $i++ ) {
588 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
590 return if ( rename($file, $f) );
592 # shouldn't get here, but might if you tried to call this
593 # across file systems.... just remove the tree right now.
594 if ( $file =~ /(.*)\/([^\/]*)/ ) {
597 my($cwd) = Cwd::fastcwd();
598 $cwd = $1 if ( $cwd =~ /(.*)/ );
599 $bpc->RmTreeQuiet($d, $f);
600 chdir($cwd) if ( $cwd );
605 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
606 # did something, -1 if it failed to remove all the files.
610 my($bpc, $trashDir) = @_;
612 my($cwd) = Cwd::fastcwd();
614 $cwd = $1 if ( $cwd =~ /(.*)/ );
615 return if ( !-d $trashDir );
616 my $d = $bpc->dirReadNames($trashDir) or carp "Can't read $trashDir: $!";
617 @files = grep $_ !~ /^\.{1,2}$/, @$d;
618 return 0 if ( !@files );
619 $bpc->RmTreeQuiet($trashDir, \@files);
620 foreach my $f ( @files ) {
621 return -1 if ( -e $f );
623 chdir($cwd) if ( $cwd );
628 # Open a connection to the server. Returns an error string on failure.
629 # Returns undef on success.
633 my($bpc, $host, $port, $justConnect) = @_;
636 return if ( defined($bpc->{ServerFD}) );
638 # First try the unix-domain socket
640 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
641 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
642 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
643 my $err = "unix connect: $!";
646 my $proto = getprotobyname('tcp');
647 my $iaddr = inet_aton($host) || return "unknown host $host";
648 my $paddr = sockaddr_in($port, $iaddr);
650 socket(*FH, PF_INET, SOCK_STREAM, $proto)
651 || return "inet socket: $!";
652 connect(*FH, $paddr) || return "inet connect: $!";
657 my($oldFH) = select(*FH); $| = 1; select($oldFH);
658 $bpc->{ServerFD} = *FH;
659 return if ( $justConnect );
661 # Read the seed that we need for our MD5 message digest. See
664 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
665 $bpc->{ServerMesgCnt} = 0;
670 # Check that the server connection is still ok
676 return 0 if ( !defined($bpc->{ServerFD}) );
677 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
679 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
680 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
684 # Disconnect from the server
689 return if ( !defined($bpc->{ServerFD}) );
690 close($bpc->{ServerFD});
691 delete($bpc->{ServerFD});
695 # Sends a message to the server and returns with the reply.
697 # To avoid possible attacks via the TCP socket interface, every client
698 # message is protected by an MD5 digest. The MD5 digest includes four
700 # - a seed that is sent to us when we first connect
701 # - a sequence number that increments for each message
702 # - a shared secret that is stored in $Conf{ServerMesgSecret}
703 # - the message itself.
704 # The message is sent in plain text preceded by the MD5 digest. A
705 # snooper can see the plain-text seed sent by BackupPC and plain-text
706 # message, but cannot construct a valid MD5 digest since the secret in
707 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
708 # since the seed changes on a per-connection and per-message basis.
712 my($bpc, $mesg) = @_;
713 return if ( !defined(my $fh = $bpc->{ServerFD}) );
714 my $md5 = Digest::MD5->new;
715 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
716 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
717 print($fh $md5->b64digest . " $mesg\n");
718 $bpc->{ServerMesgCnt}++;
723 # Do initialization for child processes
729 open(STDERR, ">&STDOUT");
730 select(STDERR); $| = 1;
731 select(STDOUT); $| = 1;
732 $ENV{PATH} = $bpc->{Conf}{MyPath};
736 # Compute the MD5 digest of a file. For efficiency we don't
737 # use the whole file for big files:
738 # - for files <= 256K we use the file size and the whole file.
739 # - for files <= 1M we use the file size, the first 128K and
741 # - for files > 1M, we use the file size, the first 128K and
742 # the 8th 128K (ie: the 128K up to 1MB).
743 # See the documentation for a discussion of the tradeoffs in
744 # how much data we use and how many collisions we get.
746 # Returns the MD5 digest (a hex string) and the file size.
750 my($bpc, $md5, $name) = @_;
751 my($data, $fileSize);
754 $fileSize = (stat($name))[7];
755 return ("", -1) if ( !-f _ );
756 $name = $1 if ( $name =~ /(.*)/ );
757 return ("", 0) if ( $fileSize == 0 );
758 return ("", -1) if ( !open(N, $name) );
761 $md5->add($fileSize);
762 if ( $fileSize > 262144 ) {
764 # read the first and last 131072 bytes of the file,
767 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
768 $md5->add($data) if ( sysread(N, $data, 131072) );
769 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
770 && sysread(N, $data, 131072) );
773 # read the whole file
775 $md5->add($data) if ( sysread(N, $data, $fileSize) );
778 return ($md5->hexdigest, $fileSize);
782 # Compute the MD5 digest of a buffer (string). For efficiency we don't
783 # use the whole string for big strings:
784 # - for files <= 256K we use the file size and the whole file.
785 # - for files <= 1M we use the file size, the first 128K and
787 # - for files > 1M, we use the file size, the first 128K and
788 # the 8th 128K (ie: the 128K up to 1MB).
789 # See the documentation for a discussion of the tradeoffs in
790 # how much data we use and how many collisions we get.
792 # Returns the MD5 digest (a hex string).
796 my($bpc, $md5, $fileSize, $dataRef) = @_;
799 $md5->add($fileSize);
800 if ( $fileSize > 262144 ) {
802 # add the first and last 131072 bytes of the string,
805 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
806 $md5->add(substr($$dataRef, 0, 131072));
807 $md5->add(substr($$dataRef, $seekPosn, 131072));
810 # add the whole string
812 $md5->add($$dataRef);
814 return $md5->hexdigest;
818 # Given an MD5 digest $d and a compress flag, return the full
823 my($bpc, $d, $compress, $poolDir) = @_;
825 return if ( $d !~ m{(.)(.)(.)(.*)} );
826 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
827 if ( !defined($poolDir) );
828 return "$poolDir/$1/$2/$3/$1$2$3$4";
832 # For each file, check if the file exists in $bpc->{TopDir}/pool.
833 # If so, remove the file and make a hardlink to the file in
834 # the pool. Otherwise, if the newFile flag is set, make a
835 # hardlink in the pool to the new file.
837 # Returns 0 if a link should be made to a new file (ie: when the file
838 # is a new file but the newFile flag is 0).
839 # Returns 1 if a link to an existing file is made,
840 # Returns 2 if a link to a new file is made (only if $newFile is set)
841 # Returns negative on error.
845 my($bpc, $name, $d, $newFile, $compress) = @_;
848 return -1 if ( !-f $name );
849 for ( $i = -1 ; ; $i++ ) {
850 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
851 $rawFile .= "_$i" if ( $i >= 0 );
853 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
854 && !compare($name, $rawFile) ) {
856 return -3 if ( !link($rawFile, $name) );
859 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
861 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
862 mkpath($newDir, 0, 0777) if ( !-d $newDir );
863 return -4 if ( !link($name, $rawFile) );
873 my($bpc, $host) = @_;
874 my($s, $pingCmd, $ret);
877 # Return success if the ping cmd is undefined or empty.
879 if ( $bpc->{Conf}{PingCmd} eq "" ) {
880 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
881 . " is empty\n") if ( $bpc->{verbose} );
886 pingPath => $bpc->{Conf}{PingPath},
889 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
892 # Do a first ping in case the PC needs to wakeup
894 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
896 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
897 if ( $bpc->{verbose} );
902 # Do a second ping and get the round-trip time in msec
904 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
906 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
907 if ( $bpc->{verbose} );
910 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
912 $ret /= 1000 if ( lc($2) eq "usec" );
913 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
915 $ret /= 1000 if ( lc($2) eq "usec" );
917 print(STDERR "CheckHostAlive: can't extract round-trip time"
918 . " (not fatal)\n") if ( $bpc->{verbose} );
921 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
925 sub CheckFileSystemUsage
928 my($topDir) = $bpc->{TopDir};
931 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
933 dfPath => $bpc->{Conf}{DfPath},
934 topDir => $bpc->{TopDir},
936 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
937 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
938 return 0 if ( $? || $s !~ /(\d+)%/s );
943 # Given an IP address, return the host name and user name via
948 my($bpc, $host) = @_;
949 my($netBiosHostName, $netBiosUserName);
953 # Skip NetBios check if NmbLookupCmd is emtpy
955 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
956 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
957 . " is empty\n") if ( $bpc->{verbose} );
958 return ($host, undef);
962 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
965 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
966 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
967 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
968 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
969 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
971 if ( !defined($netBiosHostName) ) {
972 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
973 if ( $bpc->{verbose} );
976 $netBiosHostName = lc($netBiosHostName);
977 $netBiosUserName = lc($netBiosUserName);
978 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
979 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
980 return ($netBiosHostName, $netBiosUserName);
984 # Given a NetBios name lookup the IP address via NetBios.
985 # In the case of a host returning multiple interfaces we
986 # return the first IP address that matches the subnet mask.
987 # If none match the subnet mask (or nmblookup doesn't print
988 # the subnet mask) then just the first IP address is returned.
990 sub NetBiosHostIPFind
992 my($bpc, $host) = @_;
993 my($netBiosHostName, $netBiosUserName);
994 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
997 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
999 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
1000 print(STDERR "NetBiosHostIPFind: return $host because"
1001 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
1002 if ( $bpc->{verbose} );
1007 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1010 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
1011 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
1013 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
1015 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
1016 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
1018 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
1019 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
1022 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
1023 if ( defined($ipAddr) ) {
1024 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
1025 . " host $host\n") if ( $bpc->{verbose} );
1028 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
1029 . " host $host\n") if ( $bpc->{verbose} );
1034 sub fileNameEltMangle
1036 my($bpc, $name) = @_;
1038 return "" if ( $name eq "" );
1039 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
1044 # We store files with every name preceded by "f". This
1045 # avoids possible name conflicts with other information
1046 # we store in the same directories (eg: attribute info).
1047 # The process of turning a normal path into one with each
1048 # node prefixed with "f" is called mangling.
1052 my($bpc, $name) = @_;
1054 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
1055 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
1060 # This undoes FileNameMangle
1062 sub fileNameUnmangle
1064 my($bpc, $name) = @_;
1068 $name =~ s{%(..)}{chr(hex($1))}eg;
1073 # Escape shell meta-characters with backslashes.
1074 # This should be applied to each argument seperately, not an
1075 # entire shell command.
1079 my($bpc, $cmd) = @_;
1081 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
1086 # For printing exec commands (which don't use a shell) so they look like
1087 # a valid shell command this function should be called with the exec
1088 # args. The shell command string is returned.
1090 sub execCmd2ShellCmd
1092 my($bpc, @args) = @_;
1095 foreach my $a ( @args ) {
1096 $str .= " " if ( $str ne "" );
1097 $str .= $bpc->shellEscape($a);
1103 # Do a URI-style escape to protect/encode special characters
1108 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1113 # Do a URI-style unescape to restore special characters
1118 $s =~ s{%(..)}{chr(hex($1))}eg;
1123 # Do variable substitution prior to execution of a command.
1125 sub cmdVarSubstitute
1127 my($bpc, $template, $vars) = @_;
1131 # Return without any substitution if the first entry starts with "&",
1132 # indicating this is perl code.
1134 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1137 if ( ref($template) ne "ARRAY" ) {
1139 # Split at white space, except if escaped by \
1141 $template = [split(/(?<!\\)\s+/, $template)];
1143 # Remove the \ that escaped white space.
1145 foreach ( @$template ) {
1150 # Merge variables into @tarClientCmd
1152 foreach my $arg ( @$template ) {
1154 # Replace scalar variables first
1156 $arg =~ s{\$(\w+)(\+?)}{
1157 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1158 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1162 # Now replicate any array arguments; this just works for just one
1163 # array var in each argument.
1165 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1170 foreach my $v ( @{$vars->{$var}} ) {
1171 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1172 push(@cmd, "$pre$v$post");
1182 # Exec or eval a command. $cmd is either a string on an array ref.
1184 # @args are optional arguments for the eval() case; they are not used
1189 my($bpc, $cmd, @args) = @_;
1191 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1192 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1193 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1194 if ( $bpc->{verbose} );
1196 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1199 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1200 print(STDERR "cmdExecOrEval: about to exec ",
1201 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1202 if ( $bpc->{verbose} );
1204 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1206 # force list-form of exec(), ie: no shell even for 1 arg
1208 exec { $cmd->[0] } @$cmd;
1209 print(STDERR "Exec failed for @$cmd\n");
1215 # System or eval a command. $cmd is either a string on an array ref.
1216 # $stdoutCB is a callback for output generated by the command. If it
1217 # is undef then output is returned. If it is a code ref then the function
1218 # is called with each piece of output as an argument. If it is a scalar
1219 # ref the output is appended to this variable.
1221 # @args are optional arguments for the eval() case; they are not used
1224 # Also, $? should be set when the CHILD pipe is closed.
1226 sub cmdSystemOrEvalLong
1228 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1229 my($pid, $out, $allOut);
1233 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1234 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1235 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1236 if ( $bpc->{verbose} );
1238 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1239 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1240 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1241 if ( $bpc->{verbose} );
1242 return $out if ( !defined($stdoutCB) );
1245 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1246 print(STDERR "cmdSystemOrEval: about to system ",
1247 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1248 if ( $bpc->{verbose} );
1249 if ( !defined($pid = open(CHILD, "-|")) ) {
1250 my $err = "Can't fork to run @$cmd\n";
1252 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1253 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1254 return $err if ( !defined($stdoutCB) );
1263 if ( $ignoreStderr ) {
1264 open(STDERR, ">", "/dev/null");
1266 open(STDERR, ">&STDOUT");
1269 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1271 # force list-form of exec(), ie: no shell even for 1 arg
1273 exec { $cmd->[0] } @$cmd;
1274 print(STDERR "Exec of @$cmd failed\n");
1279 # Notify caller of child's pid
1281 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1284 # The parent gathers the output from the child
1287 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1288 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1289 $out .= $_ if ( !defined($stdoutCB) );
1290 $allOut .= $_ if ( $bpc->{verbose} );
1295 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1296 if ( $bpc->{verbose} );
1301 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1302 # and stderr together.
1306 my($bpc, $cmd, $stdoutCB, @args) = @_;
1308 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1312 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1313 # to hashes and $conf->{$shareName} to an array.
1315 sub backupFileConfFix
1317 my($bpc, $conf, $shareName) = @_;
1319 $conf->{$shareName} = [ $conf->{$shareName} ]
1320 if ( ref($conf->{$shareName}) ne "ARRAY" );
1321 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1322 next if ( !defined($conf->{$param}) );
1323 if ( ref($conf->{$param}) eq "HASH" ) {
1325 # A "*" entry means wildcard - it is the default for
1326 # all shares. Replicate the "*" entry for all shares,
1327 # but still allow override of specific entries.
1329 next if ( !defined($conf->{$param}{"*"}) );
1331 map({ $_ => $conf->{$param}{"*"} }
1332 @{$conf->{$shareName}}),
1336 $conf->{$param} = [ $conf->{$param} ]
1337 if ( ref($conf->{$param}) ne "ARRAY" );
1338 $conf->{$param} = { map { $_ => $conf->{$param} }
1339 @{$conf->{$shareName}} };
1345 # This is sort() compare function, used below.
1347 # New client LOG names are LOG.MMYYYY. Old style names are
1348 # LOG, LOG.0, LOG.1 etc. Sort them so new names are
1349 # first, and newest to oldest.
1353 my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1354 my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1356 $na = -1 if ( !defined($na) );
1357 $nb = -1 if ( !defined($nb) );
1359 if ( length($na) >= 5 && length($nb) >= 5 ) {
1361 # Both new style: format is MMYYYY. Bigger dates are
1364 my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1365 my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1367 } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1369 } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1373 # Both old style. Smaller numbers are more recent.
1380 # Returns list of paths to a clients's (or main) LOG files,
1381 # most recent first.
1383 sub sortedPCLogFiles
1385 my($bpc, $host) = @_;
1389 if ( $host ne "" ) {
1390 $dir = "$bpc->{TopDir}/pc/$host";
1392 $dir = "$bpc->{LogDir}";
1394 if ( opendir(DIR, $dir) ) {
1395 foreach my $file ( readdir(DIR) ) {
1396 next if ( !-f "$dir/$file" );
1397 next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1398 push(@files, "$dir/$file");
1402 return sort(compareLOGName @files);