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.0beta3, released 3 Dec 2006.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
38 package BackupPC::Lib;
42 use vars qw(%Conf %Lang);
43 use BackupPC::Storage;
57 my($topDir, $installDir, $confDir, $noUserCheck) = @_;
60 # Whether to use filesystem hierarchy standard for file layout.
61 # If set, text config files are below /etc/BackupPC.
67 # Set defaults for $topDir and $installDir.
69 $topDir = '/tera0/backup/BackupPC' if ( $topDir eq "" );
70 $installDir = '/usr/local/BackupPC' if ( $installDir eq "" );
73 # Pick some initial defaults. For FHS the only critical
74 # path is the ConfDir, since we get everything else out
75 # of the main config file.
81 InstallDir => $installDir,
82 ConfDir => $confDir eq "" ? '/etc/BackupPC' : $confDir,
83 LogDir => '/var/log/BackupPC',
89 InstallDir => $installDir,
90 ConfDir => $confDir eq "" ? "$topDir/conf" : $confDir,
91 LogDir => "$topDir/log",
97 Version => '3.0.0beta3',
100 $bpc->{storage} = BackupPC::Storage->new($paths);
103 # Clean up %ENV and setup other variables.
105 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
106 $bpc->{PoolDir} = "$bpc->{TopDir}/pool";
107 $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
108 if ( defined(my $error = $bpc->ConfigRead()) ) {
109 print(STDERR $error, "\n");
114 # Update the paths based on the config file
116 foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
117 next if ( $bpc->{Conf}{$dir} eq "" );
118 $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
120 $bpc->{storage}->setPaths($paths);
123 # Verify we are running as the correct user
126 && $bpc->{Conf}{BackupPCUserVerify}
127 && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
128 print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
129 . " ($bpc->{Conf}{BackupPCUser})\n");
130 print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
139 return $bpc->{TopDir};
145 return "$bpc->{InstallDir}/bin";
151 return $bpc->{LogDir};
157 return $bpc->{ConfDir};
163 return "$bpc->{InstallDir}/lib";
169 return $bpc->{InstallDir};
175 return $bpc->{useFHS};
181 return $bpc->{Version};
187 return %{$bpc->{Conf}};
199 return " admin " if ( !$num );
200 return " admin$num ";
206 return $str =~ /^ admin/;
211 return " trashClean ";
216 my($bpc, $param) = @_;
218 return $bpc->{Conf}{$param};
223 my($bpc, $param) = @_;
225 $bpc->{verbose} = $param if ( defined($param) );
226 return $bpc->{verbose};
233 if ( !defined($bpc->{SigName2Num}) ) {
235 foreach my $name ( split(' ', $Config{sig_name}) ) {
236 $bpc->{SigName2Num}{$name} = $i;
240 return $bpc->{SigName2Num}{$sig};
244 # Generate an ISO 8601 format timeStamp (but without the "T").
245 # See http://www.w3.org/TR/NOTE-datetime and
246 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
250 my($bpc, $t, $noPad) = @_;
251 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
252 = localtime($t || time);
253 return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
254 $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
255 . ($noPad ? "" : " ");
260 my($bpc, $host) = @_;
262 return $bpc->{storage}->BackupInfoRead($host);
267 my($bpc, $host, @Backups) = @_;
269 return $bpc->{storage}->BackupInfoWrite($host, @Backups);
274 my($bpc, $host) = @_;
276 return $bpc->{storage}->RestoreInfoRead($host);
281 my($bpc, $host, @Restores) = @_;
283 return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
288 my($bpc, $host) = @_;
290 return $bpc->{storage}->ArchiveInfoRead($host);
295 my($bpc, $host, @Archives) = @_;
297 return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
302 my($bpc, $host) = @_;
304 return $bpc->{storage}->ConfigDataRead($host);
309 my($bpc, $host, $conf) = @_;
311 return $bpc->{storage}->ConfigDataWrite($host, $conf);
316 my($bpc, $host) = @_;
320 # Read main config file
322 my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
323 return $mesg if ( defined($mesg) );
325 $bpc->{Conf} = $config;
328 # Read host config file
331 ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
332 return $mesg if ( defined($mesg) );
333 $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
337 # Load optional perl modules
339 if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
341 # Load any user-specified perl modules. This is for
342 # optional user-defined extensions.
344 $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
345 if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
346 foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
347 eval("use $module;");
354 return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
355 my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
356 if ( !defined($ret = do $langFile) && ($! || $@) ) {
357 $mesg = "Couldn't open language file $langFile: $!" if ( $! );
358 $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
359 $mesg =~ s/[\n\r]+//;
362 $bpc->{Lang} = \%Lang;
367 # Return the mtime of the config file
373 return $bpc->{storage}->ConfigMTime();
377 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
378 # With no argument a ref to a hash of hosts is returned. Each
379 # hash contains fields as specified in the hosts file. With an
380 # argument a ref to a single hash is returned with information
381 # for just that host.
385 my($bpc, $host) = @_;
387 return $bpc->{storage}->HostInfoRead($host);
392 my($bpc, $host) = @_;
394 return $bpc->{storage}->HostInfoWrite($host);
398 # Return the mtime of the hosts file
404 return $bpc->{storage}->HostsMTime();
408 # Stripped down from File::Path. In particular we don't print
409 # many warnings and we try three times to delete each directory
410 # and file -- for some reason the original File::Path rmtree
411 # didn't always completely remove a directory tree on the NetApp.
413 # Warning: this routine changes the cwd.
417 my($bpc, $pwd, $roots) = @_;
420 if ( defined($roots) && length($roots) ) {
421 $roots = [$roots] unless ref $roots;
423 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
426 foreach $root (@{$roots}) {
427 $root = $1 if ( $root =~ m{(.*?)/*$} );
429 # Try first to simply unlink the file: this avoids an
430 # extra stat for every file. If it fails (which it
431 # will for directories), check if it is a directory and
434 if ( !unlink($root) ) {
436 my $d = DirHandle->new($root);
437 if ( !defined($d) ) {
438 print(STDERR "Can't read $pwd/$root: $!\n");
442 @files = grep $_!~/^\.{1,2}$/, @files;
443 $bpc->RmTreeQuiet("$pwd/$root", \@files);
445 rmdir($root) || rmdir($root);
448 unlink($root) || unlink($root);
455 # Move a directory or file away for later deletion
459 my($bpc, $trashDir, $file) = @_;
462 return if ( !-e $file );
463 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
464 for ( $i = 0 ; $i < 1000 ; $i++ ) {
465 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
467 return if ( rename($file, $f) );
469 # shouldn't get here, but might if you tried to call this
470 # across file systems.... just remove the tree right now.
471 if ( $file =~ /(.*)\/([^\/]*)/ ) {
474 my($cwd) = Cwd::fastcwd();
475 $cwd = $1 if ( $cwd =~ /(.*)/ );
476 $bpc->RmTreeQuiet($d, $f);
477 chdir($cwd) if ( $cwd );
482 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
483 # did something, -1 if it failed to remove all the files.
487 my($bpc, $trashDir) = @_;
489 my($cwd) = Cwd::fastcwd();
491 $cwd = $1 if ( $cwd =~ /(.*)/ );
492 return if ( !-d $trashDir );
493 my $d = DirHandle->new($trashDir) or carp "Can't read $trashDir: $!";
496 @files = grep $_!~/^\.{1,2}$/, @files;
497 return 0 if ( !@files );
498 $bpc->RmTreeQuiet($trashDir, \@files);
499 foreach my $f ( @files ) {
500 return -1 if ( -e $f );
502 chdir($cwd) if ( $cwd );
507 # Open a connection to the server. Returns an error string on failure.
508 # Returns undef on success.
512 my($bpc, $host, $port, $justConnect) = @_;
515 return if ( defined($bpc->{ServerFD}) );
517 # First try the unix-domain socket
519 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
520 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
521 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
522 my $err = "unix connect: $!";
525 my $proto = getprotobyname('tcp');
526 my $iaddr = inet_aton($host) || return "unknown host $host";
527 my $paddr = sockaddr_in($port, $iaddr);
529 socket(*FH, PF_INET, SOCK_STREAM, $proto)
530 || return "inet socket: $!";
531 connect(*FH, $paddr) || return "inet connect: $!";
536 my($oldFH) = select(*FH); $| = 1; select($oldFH);
537 $bpc->{ServerFD} = *FH;
538 return if ( $justConnect );
540 # Read the seed that we need for our MD5 message digest. See
543 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
544 $bpc->{ServerMesgCnt} = 0;
549 # Check that the server connection is still ok
555 return 0 if ( !defined($bpc->{ServerFD}) );
556 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
558 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
559 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
563 # Disconnect from the server
568 return if ( !defined($bpc->{ServerFD}) );
569 close($bpc->{ServerFD});
570 delete($bpc->{ServerFD});
574 # Sends a message to the server and returns with the reply.
576 # To avoid possible attacks via the TCP socket interface, every client
577 # message is protected by an MD5 digest. The MD5 digest includes four
579 # - a seed that is sent to us when we first connect
580 # - a sequence number that increments for each message
581 # - a shared secret that is stored in $Conf{ServerMesgSecret}
582 # - the message itself.
583 # The message is sent in plain text preceded by the MD5 digest. A
584 # snooper can see the plain-text seed sent by BackupPC and plain-text
585 # message, but cannot construct a valid MD5 digest since the secret in
586 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
587 # since the seed changes on a per-connection and per-message basis.
591 my($bpc, $mesg) = @_;
592 return if ( !defined(my $fh = $bpc->{ServerFD}) );
593 my $md5 = Digest::MD5->new;
594 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
595 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
596 print($fh $md5->b64digest . " $mesg\n");
597 $bpc->{ServerMesgCnt}++;
602 # Do initialization for child processes
608 open(STDERR, ">&STDOUT");
609 select(STDERR); $| = 1;
610 select(STDOUT); $| = 1;
611 $ENV{PATH} = $bpc->{Conf}{MyPath};
615 # Compute the MD5 digest of a file. For efficiency we don't
616 # use the whole file for big files:
617 # - for files <= 256K we use the file size and the whole file.
618 # - for files <= 1M we use the file size, the first 128K and
620 # - for files > 1M, we use the file size, the first 128K and
621 # the 8th 128K (ie: the 128K up to 1MB).
622 # See the documentation for a discussion of the tradeoffs in
623 # how much data we use and how many collisions we get.
625 # Returns the MD5 digest (a hex string) and the file size.
629 my($bpc, $md5, $name) = @_;
630 my($data, $fileSize);
633 $fileSize = (stat($name))[7];
634 return ("", -1) if ( !-f _ );
635 $name = $1 if ( $name =~ /(.*)/ );
636 return ("", 0) if ( $fileSize == 0 );
637 return ("", -1) if ( !open(N, $name) );
640 $md5->add($fileSize);
641 if ( $fileSize > 262144 ) {
643 # read the first and last 131072 bytes of the file,
646 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
647 $md5->add($data) if ( sysread(N, $data, 131072) );
648 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
649 && sysread(N, $data, 131072) );
652 # read the whole file
654 $md5->add($data) if ( sysread(N, $data, $fileSize) );
657 return ($md5->hexdigest, $fileSize);
661 # Compute the MD5 digest of a buffer (string). For efficiency we don't
662 # use the whole string for big strings:
663 # - for files <= 256K we use the file size and the whole file.
664 # - for files <= 1M we use the file size, the first 128K and
666 # - for files > 1M, we use the file size, the first 128K and
667 # the 8th 128K (ie: the 128K up to 1MB).
668 # See the documentation for a discussion of the tradeoffs in
669 # how much data we use and how many collisions we get.
671 # Returns the MD5 digest (a hex string).
675 my($bpc, $md5, $fileSize, $dataRef) = @_;
678 $md5->add($fileSize);
679 if ( $fileSize > 262144 ) {
681 # add the first and last 131072 bytes of the string,
684 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
685 $md5->add(substr($$dataRef, 0, 131072));
686 $md5->add(substr($$dataRef, $seekPosn, 131072));
689 # add the whole string
691 $md5->add($$dataRef);
693 return $md5->hexdigest;
697 # Given an MD5 digest $d and a compress flag, return the full
702 my($bpc, $d, $compress, $poolDir) = @_;
704 return if ( $d !~ m{(.)(.)(.)(.*)} );
705 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
706 if ( !defined($poolDir) );
707 return "$poolDir/$1/$2/$3/$1$2$3$4";
711 # For each file, check if the file exists in $bpc->{TopDir}/pool.
712 # If so, remove the file and make a hardlink to the file in
713 # the pool. Otherwise, if the newFile flag is set, make a
714 # hardlink in the pool to the new file.
716 # Returns 0 if a link should be made to a new file (ie: when the file
717 # is a new file but the newFile flag is 0).
718 # Returns 1 if a link to an existing file is made,
719 # Returns 2 if a link to a new file is made (only if $newFile is set)
720 # Returns negative on error.
724 my($bpc, $name, $d, $newFile, $compress) = @_;
727 return -1 if ( !-f $name );
728 for ( $i = -1 ; ; $i++ ) {
729 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
730 $rawFile .= "_$i" if ( $i >= 0 );
732 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
733 && !compare($name, $rawFile) ) {
735 return -3 if ( !link($rawFile, $name) );
738 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
740 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
741 mkpath($newDir, 0, 0777) if ( !-d $newDir );
742 return -4 if ( !link($name, $rawFile) );
752 my($bpc, $host) = @_;
753 my($s, $pingCmd, $ret);
756 # Return success if the ping cmd is undefined or empty.
758 if ( $bpc->{Conf}{PingCmd} eq "" ) {
759 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
760 . " is empty\n") if ( $bpc->{verbose} );
765 pingPath => $bpc->{Conf}{PingPath},
768 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
771 # Do a first ping in case the PC needs to wakeup
773 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
775 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
776 if ( $bpc->{verbose} );
781 # Do a second ping and get the round-trip time in msec
783 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
785 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
786 if ( $bpc->{verbose} );
789 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
791 $ret /= 1000 if ( lc($2) eq "usec" );
792 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
794 $ret /= 1000 if ( lc($2) eq "usec" );
796 print(STDERR "CheckHostAlive: can't extract round-trip time"
797 . " (not fatal)\n") if ( $bpc->{verbose} );
800 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
804 sub CheckFileSystemUsage
807 my($topDir) = $bpc->{TopDir};
810 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
812 dfPath => $bpc->{Conf}{DfPath},
813 topDir => $bpc->{TopDir},
815 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
816 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
817 return 0 if ( $? || $s !~ /(\d+)%/s );
822 # Given an IP address, return the host name and user name via
827 my($bpc, $host) = @_;
828 my($netBiosHostName, $netBiosUserName);
832 # Skip NetBios check if NmbLookupCmd is emtpy
834 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
835 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
836 . " is empty\n") if ( $bpc->{verbose} );
837 return ($host, undef);
841 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
844 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
845 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
846 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
847 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
848 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
850 if ( !defined($netBiosHostName) ) {
851 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
852 if ( $bpc->{verbose} );
855 $netBiosHostName = lc($netBiosHostName);
856 $netBiosUserName = lc($netBiosUserName);
857 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
858 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
859 return ($netBiosHostName, $netBiosUserName);
863 # Given a NetBios name lookup the IP address via NetBios.
864 # In the case of a host returning multiple interfaces we
865 # return the first IP address that matches the subnet mask.
866 # If none match the subnet mask (or nmblookup doesn't print
867 # the subnet mask) then just the first IP address is returned.
869 sub NetBiosHostIPFind
871 my($bpc, $host) = @_;
872 my($netBiosHostName, $netBiosUserName);
873 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
876 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
878 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
879 print(STDERR "NetBiosHostIPFind: return $host because"
880 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
881 if ( $bpc->{verbose} );
886 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
889 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
890 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
892 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
894 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
895 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
897 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
898 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
901 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
902 if ( defined($ipAddr) ) {
903 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
904 . " host $host\n") if ( $bpc->{verbose} );
907 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
908 . " host $host\n") if ( $bpc->{verbose} );
913 sub fileNameEltMangle
915 my($bpc, $name) = @_;
917 return "" if ( $name eq "" );
918 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
923 # We store files with every name preceded by "f". This
924 # avoids possible name conflicts with other information
925 # we store in the same directories (eg: attribute info).
926 # The process of turning a normal path into one with each
927 # node prefixed with "f" is called mangling.
931 my($bpc, $name) = @_;
933 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
934 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
939 # This undoes FileNameMangle
943 my($bpc, $name) = @_;
947 $name =~ s{%(..)}{chr(hex($1))}eg;
952 # Escape shell meta-characters with backslashes.
953 # This should be applied to each argument seperately, not an
954 # entire shell command.
960 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
965 # For printing exec commands (which don't use a shell) so they look like
966 # a valid shell command this function should be called with the exec
967 # args. The shell command string is returned.
971 my($bpc, @args) = @_;
974 foreach my $a ( @args ) {
975 $str .= " " if ( $str ne "" );
976 $str .= $bpc->shellEscape($a);
982 # Do a URI-style escape to protect/encode special characters
987 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
992 # Do a URI-style unescape to restore special characters
997 $s =~ s{%(..)}{chr(hex($1))}eg;
1002 # Do variable substitution prior to execution of a command.
1004 sub cmdVarSubstitute
1006 my($bpc, $template, $vars) = @_;
1010 # Return without any substitution if the first entry starts with "&",
1011 # indicating this is perl code.
1013 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1016 if ( ref($template) ne "ARRAY" ) {
1018 # Split at white space, except if escaped by \
1020 $template = [split(/(?<!\\)\s+/, $template)];
1022 # Remove the \ that escaped white space.
1024 foreach ( @$template ) {
1029 # Merge variables into @tarClientCmd
1031 foreach my $arg ( @$template ) {
1033 # Replace scalar variables first
1035 $arg =~ s{\$(\w+)(\+?)}{
1036 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1037 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1041 # Now replicate any array arguments; this just works for just one
1042 # array var in each argument.
1044 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1049 foreach my $v ( @{$vars->{$var}} ) {
1050 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1051 push(@cmd, "$pre$v$post");
1061 # Exec or eval a command. $cmd is either a string on an array ref.
1063 # @args are optional arguments for the eval() case; they are not used
1068 my($bpc, $cmd, @args) = @_;
1070 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1071 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1072 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1073 if ( $bpc->{verbose} );
1075 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1078 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1079 print(STDERR "cmdExecOrEval: about to exec ",
1080 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1081 if ( $bpc->{verbose} );
1083 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1085 # force list-form of exec(), ie: no shell even for 1 arg
1087 exec { $cmd->[0] } @$cmd;
1088 print(STDERR "Exec failed for @$cmd\n");
1094 # System or eval a command. $cmd is either a string on an array ref.
1095 # $stdoutCB is a callback for output generated by the command. If it
1096 # is undef then output is returned. If it is a code ref then the function
1097 # is called with each piece of output as an argument. If it is a scalar
1098 # ref the output is appended to this variable.
1100 # @args are optional arguments for the eval() case; they are not used
1103 # Also, $? should be set when the CHILD pipe is closed.
1105 sub cmdSystemOrEvalLong
1107 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1108 my($pid, $out, $allOut);
1112 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1113 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1114 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1115 if ( $bpc->{verbose} );
1117 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1118 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1119 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1120 if ( $bpc->{verbose} );
1121 return $out if ( !defined($stdoutCB) );
1124 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1125 print(STDERR "cmdSystemOrEval: about to system ",
1126 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1127 if ( $bpc->{verbose} );
1128 if ( !defined($pid = open(CHILD, "-|")) ) {
1129 my $err = "Can't fork to run @$cmd\n";
1131 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1132 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1133 return $err if ( !defined($stdoutCB) );
1142 if ( $ignoreStderr ) {
1143 open(STDERR, ">", "/dev/null");
1145 open(STDERR, ">&STDOUT");
1148 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1150 # force list-form of exec(), ie: no shell even for 1 arg
1152 exec { $cmd->[0] } @$cmd;
1153 print(STDERR "Exec of @$cmd failed\n");
1158 # Notify caller of child's pid
1160 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1163 # The parent gathers the output from the child
1166 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1167 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1168 $out .= $_ if ( !defined($stdoutCB) );
1169 $allOut .= $_ if ( $bpc->{verbose} );
1174 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1175 if ( $bpc->{verbose} );
1180 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1181 # and stderr together.
1185 my($bpc, $cmd, $stdoutCB, @args) = @_;
1187 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1191 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1192 # to hashes and $conf->{$shareName} to an array.
1194 sub backupFileConfFix
1196 my($bpc, $conf, $shareName) = @_;
1198 $conf->{$shareName} = [ $conf->{$shareName} ]
1199 if ( ref($conf->{$shareName}) ne "ARRAY" );
1200 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1201 next if ( !defined($conf->{$param}) );
1202 if ( ref($conf->{$param}) eq "HASH" ) {
1204 # A "*" entry means wildcard - it is the default for
1205 # all shares. Replicate the "*" entry for all shares,
1206 # but still allow override of specific entries.
1208 next if ( !defined($conf->{$param}{"*"}) );
1210 map({ $_ => $conf->{$param}{"*"} }
1211 @{$conf->{$shareName}}),
1215 $conf->{$param} = [ $conf->{$param} ]
1216 if ( ref($conf->{$param}) ne "ARRAY" );
1217 $conf->{$param} = { map { $_ => $conf->{$param} }
1218 @{$conf->{$shareName}} };
1224 # This is sort() compare function, used below.
1226 # New client LOG names are LOG.MMYYYY. Old style names are
1227 # LOG, LOG.0, LOG.1 etc. Sort them so new names are
1228 # first, and newest to oldest.
1232 my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1233 my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1235 $na = -1 if ( !defined($na) );
1236 $nb = -1 if ( !defined($nb) );
1238 if ( length($na) >= 5 && length($nb) >= 5 ) {
1240 # Both new style: format is MMYYYY. Bigger dates are
1243 my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1244 my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1246 } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1248 } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1252 # Both old style. Smaller numbers are more recent.
1259 # Returns list of paths to a clients's (or main) LOG files,
1260 # most recent first.
1262 sub sortedPCLogFiles
1264 my($bpc, $host) = @_;
1268 if ( $host ne "" ) {
1269 $dir = "$bpc->{TopDir}/pc/$host";
1271 $dir = "$bpc->{LogDir}";
1273 if ( opendir(DIR, $dir) ) {
1274 foreach my $file ( readdir(DIR) ) {
1275 next if ( !-f "$dir/$file" );
1276 next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1277 push(@files, "$dir/$file");
1281 return sort(compareLOGName @files);