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.0alpha, released 23 Jan 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.0alpha',
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 "Wrong user: my userid is $>, instead of $uid"
129 . " ($bpc->{Conf}{BackupPCUser})\n");
138 return $bpc->{TopDir};
144 return "$bpc->{InstallDir}/bin";
150 return $bpc->{LogDir};
156 return $bpc->{ConfDir};
162 return "$bpc->{InstallDir}/lib";
168 return $bpc->{InstallDir};
174 return $bpc->{useFHS};
180 return $bpc->{Version};
186 return %{$bpc->{Conf}};
198 return " admin " if ( !$num );
199 return " admin$num ";
205 return $str =~ /^ admin/;
210 return " trashClean ";
215 my($bpc, $param) = @_;
217 return $bpc->{Conf}{$param};
222 my($bpc, $param) = @_;
224 $bpc->{verbose} = $param if ( defined($param) );
225 return $bpc->{verbose};
232 if ( !defined($bpc->{SigName2Num}) ) {
234 foreach my $name ( split(' ', $Config{sig_name}) ) {
235 $bpc->{SigName2Num}{$name} = $i;
239 return $bpc->{SigName2Num}{$sig};
243 # Generate an ISO 8601 format timeStamp (but without the "T").
244 # See http://www.w3.org/TR/NOTE-datetime and
245 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
249 my($bpc, $t, $noPad) = @_;
250 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
251 = localtime($t || time);
252 return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
253 $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
254 . ($noPad ? "" : " ");
259 my($bpc, $host) = @_;
261 return $bpc->{storage}->BackupInfoRead($host);
266 my($bpc, $host, @Backups) = @_;
268 return $bpc->{storage}->BackupInfoWrite($host, @Backups);
273 my($bpc, $host) = @_;
275 return $bpc->{storage}->RestoreInfoRead($host);
280 my($bpc, $host, @Restores) = @_;
282 return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
287 my($bpc, $host) = @_;
289 return $bpc->{storage}->ArchiveInfoRead($host);
294 my($bpc, $host, @Archives) = @_;
296 return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
301 my($bpc, $host) = @_;
303 return $bpc->{storage}->ConfigDataRead($host);
308 my($bpc, $host, $conf) = @_;
310 return $bpc->{storage}->ConfigDataWrite($host, $conf);
315 my($bpc, $host) = @_;
319 # Read main config file
321 my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
322 return $mesg if ( defined($mesg) );
324 $bpc->{Conf} = $config;
327 # Read host config file
330 ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host);
331 return $mesg if ( defined($mesg) );
332 $bpc->{Conf} = { %{$bpc->{Conf}}, %$config };
336 # Load optional perl modules
338 if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
340 # Load any user-specified perl modules. This is for
341 # optional user-defined extensions.
343 $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
344 if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
345 foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
346 eval("use $module;");
353 return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
354 my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
355 if ( !defined($ret = do $langFile) && ($! || $@) ) {
356 $mesg = "Couldn't open language file $langFile: $!" if ( $! );
357 $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
358 $mesg =~ s/[\n\r]+//;
361 $bpc->{Lang} = \%Lang;
366 # Return the mtime of the config file
372 return $bpc->{storage}->ConfigMTime();
376 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
377 # With no argument a ref to a hash of hosts is returned. Each
378 # hash contains fields as specified in the hosts file. With an
379 # argument a ref to a single hash is returned with information
380 # for just that host.
384 my($bpc, $host) = @_;
386 return $bpc->{storage}->HostInfoRead($host);
391 my($bpc, $host) = @_;
393 return $bpc->{storage}->HostInfoWrite($host);
397 # Return the mtime of the hosts file
403 return $bpc->{storage}->HostsMTime();
407 # Stripped down from File::Path. In particular we don't print
408 # many warnings and we try three times to delete each directory
409 # and file -- for some reason the original File::Path rmtree
410 # didn't always completely remove a directory tree on the NetApp.
412 # Warning: this routine changes the cwd.
416 my($bpc, $pwd, $roots) = @_;
419 if ( defined($roots) && length($roots) ) {
420 $roots = [$roots] unless ref $roots;
422 print(STDERR "RmTreeQuiet: No root path(s) specified\n");
425 foreach $root (@{$roots}) {
426 $root = $1 if ( $root =~ m{(.*?)/*$} );
428 # Try first to simply unlink the file: this avoids an
429 # extra stat for every file. If it fails (which it
430 # will for directories), check if it is a directory and
433 if ( !unlink($root) ) {
435 my $d = DirHandle->new($root);
436 if ( !defined($d) ) {
437 print(STDERR "Can't read $pwd/$root: $!\n");
441 @files = grep $_!~/^\.{1,2}$/, @files;
442 $bpc->RmTreeQuiet("$pwd/$root", \@files);
444 rmdir($root) || rmdir($root);
447 unlink($root) || unlink($root);
454 # Move a directory or file away for later deletion
458 my($bpc, $trashDir, $file) = @_;
461 return if ( !-e $file );
462 mkpath($trashDir, 0, 0777) if ( !-d $trashDir );
463 for ( $i = 0 ; $i < 1000 ; $i++ ) {
464 $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
466 return if ( rename($file, $f) );
468 # shouldn't get here, but might if you tried to call this
469 # across file systems.... just remove the tree right now.
470 if ( $file =~ /(.*)\/([^\/]*)/ ) {
473 my($cwd) = Cwd::fastcwd();
474 $cwd = $1 if ( $cwd =~ /(.*)/ );
475 $bpc->RmTreeQuiet($d, $f);
476 chdir($cwd) if ( $cwd );
481 # Empty the trash directory. Returns 0 if it did nothing, 1 if it
482 # did something, -1 if it failed to remove all the files.
486 my($bpc, $trashDir) = @_;
488 my($cwd) = Cwd::fastcwd();
490 $cwd = $1 if ( $cwd =~ /(.*)/ );
491 return if ( !-d $trashDir );
492 my $d = DirHandle->new($trashDir) or carp "Can't read $trashDir: $!";
495 @files = grep $_!~/^\.{1,2}$/, @files;
496 return 0 if ( !@files );
497 $bpc->RmTreeQuiet($trashDir, \@files);
498 foreach my $f ( @files ) {
499 return -1 if ( -e $f );
501 chdir($cwd) if ( $cwd );
506 # Open a connection to the server. Returns an error string on failure.
507 # Returns undef on success.
511 my($bpc, $host, $port, $justConnect) = @_;
514 return if ( defined($bpc->{ServerFD}) );
516 # First try the unix-domain socket
518 my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
519 socket(*FH, PF_UNIX, SOCK_STREAM, 0) || return "unix socket: $!";
520 if ( !connect(*FH, sockaddr_un($sockFile)) ) {
521 my $err = "unix connect: $!";
524 my $proto = getprotobyname('tcp');
525 my $iaddr = inet_aton($host) || return "unknown host $host";
526 my $paddr = sockaddr_in($port, $iaddr);
528 socket(*FH, PF_INET, SOCK_STREAM, $proto)
529 || return "inet socket: $!";
530 connect(*FH, $paddr) || return "inet connect: $!";
535 my($oldFH) = select(*FH); $| = 1; select($oldFH);
536 $bpc->{ServerFD} = *FH;
537 return if ( $justConnect );
539 # Read the seed that we need for our MD5 message digest. See
542 sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
543 $bpc->{ServerMesgCnt} = 0;
548 # Check that the server connection is still ok
554 return 0 if ( !defined($bpc->{ServerFD}) );
555 vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
557 return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
558 return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
562 # Disconnect from the server
567 return if ( !defined($bpc->{ServerFD}) );
568 close($bpc->{ServerFD});
569 delete($bpc->{ServerFD});
573 # Sends a message to the server and returns with the reply.
575 # To avoid possible attacks via the TCP socket interface, every client
576 # message is protected by an MD5 digest. The MD5 digest includes four
578 # - a seed that is sent to us when we first connect
579 # - a sequence number that increments for each message
580 # - a shared secret that is stored in $Conf{ServerMesgSecret}
581 # - the message itself.
582 # The message is sent in plain text preceded by the MD5 digest. A
583 # snooper can see the plain-text seed sent by BackupPC and plain-text
584 # message, but cannot construct a valid MD5 digest since the secret in
585 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
586 # since the seed changes on a per-connection and per-message basis.
590 my($bpc, $mesg) = @_;
591 return if ( !defined(my $fh = $bpc->{ServerFD}) );
592 my $md5 = Digest::MD5->new;
593 $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
594 . $bpc->{Conf}{ServerMesgSecret} . $mesg);
595 print($fh $md5->b64digest . " $mesg\n");
596 $bpc->{ServerMesgCnt}++;
601 # Do initialization for child processes
607 open(STDERR, ">&STDOUT");
608 select(STDERR); $| = 1;
609 select(STDOUT); $| = 1;
610 $ENV{PATH} = $bpc->{Conf}{MyPath};
614 # Compute the MD5 digest of a file. For efficiency we don't
615 # use the whole file for big files:
616 # - for files <= 256K we use the file size and the whole file.
617 # - for files <= 1M we use the file size, the first 128K and
619 # - for files > 1M, we use the file size, the first 128K and
620 # the 8th 128K (ie: the 128K up to 1MB).
621 # See the documentation for a discussion of the tradeoffs in
622 # how much data we use and how many collisions we get.
624 # Returns the MD5 digest (a hex string) and the file size.
628 my($bpc, $md5, $name) = @_;
629 my($data, $fileSize);
632 $fileSize = (stat($name))[7];
633 return ("", -1) if ( !-f _ );
634 $name = $1 if ( $name =~ /(.*)/ );
635 return ("", 0) if ( $fileSize == 0 );
636 return ("", -1) if ( !open(N, $name) );
639 $md5->add($fileSize);
640 if ( $fileSize > 262144 ) {
642 # read the first and last 131072 bytes of the file,
645 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
646 $md5->add($data) if ( sysread(N, $data, 131072) );
647 $md5->add($data) if ( sysseek(N, $seekPosn, 0)
648 && sysread(N, $data, 131072) );
651 # read the whole file
653 $md5->add($data) if ( sysread(N, $data, $fileSize) );
656 return ($md5->hexdigest, $fileSize);
660 # Compute the MD5 digest of a buffer (string). For efficiency we don't
661 # use the whole string for big strings:
662 # - for files <= 256K we use the file size and the whole file.
663 # - for files <= 1M we use the file size, the first 128K and
665 # - for files > 1M, we use the file size, the first 128K and
666 # the 8th 128K (ie: the 128K up to 1MB).
667 # See the documentation for a discussion of the tradeoffs in
668 # how much data we use and how many collisions we get.
670 # Returns the MD5 digest (a hex string).
674 my($bpc, $md5, $fileSize, $dataRef) = @_;
677 $md5->add($fileSize);
678 if ( $fileSize > 262144 ) {
680 # add the first and last 131072 bytes of the string,
683 my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
684 $md5->add(substr($$dataRef, 0, 131072));
685 $md5->add(substr($$dataRef, $seekPosn, 131072));
688 # add the whole string
690 $md5->add($$dataRef);
692 return $md5->hexdigest;
696 # Given an MD5 digest $d and a compress flag, return the full
701 my($bpc, $d, $compress, $poolDir) = @_;
703 return if ( $d !~ m{(.)(.)(.)(.*)} );
704 $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
705 if ( !defined($poolDir) );
706 return "$poolDir/$1/$2/$3/$1$2$3$4";
710 # For each file, check if the file exists in $bpc->{TopDir}/pool.
711 # If so, remove the file and make a hardlink to the file in
712 # the pool. Otherwise, if the newFile flag is set, make a
713 # hardlink in the pool to the new file.
715 # Returns 0 if a link should be made to a new file (ie: when the file
716 # is a new file but the newFile flag is 0).
717 # Returns 1 if a link to an existing file is made,
718 # Returns 2 if a link to a new file is made (only if $newFile is set)
719 # Returns negative on error.
723 my($bpc, $name, $d, $newFile, $compress) = @_;
726 return -1 if ( !-f $name );
727 for ( $i = -1 ; ; $i++ ) {
728 return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
729 $rawFile .= "_$i" if ( $i >= 0 );
731 if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
732 && !compare($name, $rawFile) ) {
734 return -3 if ( !link($rawFile, $name) );
737 } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
739 ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
740 mkpath($newDir, 0, 0777) if ( !-d $newDir );
741 return -4 if ( !link($name, $rawFile) );
751 my($bpc, $host) = @_;
752 my($s, $pingCmd, $ret);
755 # Return success if the ping cmd is undefined or empty.
757 if ( $bpc->{Conf}{PingCmd} eq "" ) {
758 print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
759 . " is empty\n") if ( $bpc->{verbose} );
764 pingPath => $bpc->{Conf}{PingPath},
767 $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
770 # Do a first ping in case the PC needs to wakeup
772 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
774 print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
775 if ( $bpc->{verbose} );
780 # Do a second ping and get the round-trip time in msec
782 $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
784 print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
785 if ( $bpc->{verbose} );
788 if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
790 $ret /= 1000 if ( lc($2) eq "usec" );
791 } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
793 $ret /= 1000 if ( lc($2) eq "usec" );
795 print(STDERR "CheckHostAlive: can't extract round-trip time"
796 . " (not fatal)\n") if ( $bpc->{verbose} );
799 print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
803 sub CheckFileSystemUsage
806 my($topDir) = $bpc->{TopDir};
809 return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
811 dfPath => $bpc->{Conf}{DfPath},
812 topDir => $bpc->{TopDir},
814 $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
815 $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
816 return 0 if ( $? || $s !~ /(\d+)%/s );
821 # Given an IP address, return the host name and user name via
826 my($bpc, $host) = @_;
827 my($netBiosHostName, $netBiosUserName);
831 # Skip NetBios check if NmbLookupCmd is emtpy
833 if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
834 print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
835 . " is empty\n") if ( $bpc->{verbose} );
836 return ($host, undef);
840 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
843 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
844 foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
845 next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
846 $netBiosHostName ||= $1 if ( $2 eq "00" ); # host is first 00
847 $netBiosUserName = $1 if ( $2 eq "03" ); # user is last 03
849 if ( !defined($netBiosHostName) ) {
850 print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
851 if ( $bpc->{verbose} );
854 $netBiosHostName = lc($netBiosHostName);
855 $netBiosUserName = lc($netBiosUserName);
856 print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
857 . " user $netBiosUserName\n") if ( $bpc->{verbose} );
858 return ($netBiosHostName, $netBiosUserName);
862 # Given a NetBios name lookup the IP address via NetBios.
863 # In the case of a host returning multiple interfaces we
864 # return the first IP address that matches the subnet mask.
865 # If none match the subnet mask (or nmblookup doesn't print
866 # the subnet mask) then just the first IP address is returned.
868 sub NetBiosHostIPFind
870 my($bpc, $host) = @_;
871 my($netBiosHostName, $netBiosUserName);
872 my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
875 # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
877 if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
878 print(STDERR "NetBiosHostIPFind: return $host because"
879 . " \$Conf{NmbLookupFindHostCmd} is empty\n")
880 if ( $bpc->{verbose} );
885 nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
888 $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
889 foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
891 if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
893 $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
894 } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
896 $firstIpAddr = $ip if ( !defined($firstIpAddr) );
897 $ipAddr = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
900 $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
901 if ( defined($ipAddr) ) {
902 print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
903 . " host $host\n") if ( $bpc->{verbose} );
906 print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
907 . " host $host\n") if ( $bpc->{verbose} );
912 sub fileNameEltMangle
914 my($bpc, $name) = @_;
916 return "" if ( $name eq "" );
917 $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
922 # We store files with every name preceded by "f". This
923 # avoids possible name conflicts with other information
924 # we store in the same directories (eg: attribute info).
925 # The process of turning a normal path into one with each
926 # node prefixed with "f" is called mangling.
930 my($bpc, $name) = @_;
932 $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
933 $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
938 # This undoes FileNameMangle
942 my($bpc, $name) = @_;
946 $name =~ s{%(..)}{chr(hex($1))}eg;
951 # Escape shell meta-characters with backslashes.
952 # This should be applied to each argument seperately, not an
953 # entire shell command.
959 $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
964 # For printing exec commands (which don't use a shell) so they look like
965 # a valid shell command this function should be called with the exec
966 # args. The shell command string is returned.
970 my($bpc, @args) = @_;
973 foreach my $a ( @args ) {
974 $str .= " " if ( $str ne "" );
975 $str .= $bpc->shellEscape($a);
981 # Do a URI-style escape to protect/encode special characters
986 $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
991 # Do a URI-style unescape to restore special characters
996 $s =~ s{%(..)}{chr(hex($1))}eg;
1001 # Do variable substitution prior to execution of a command.
1003 sub cmdVarSubstitute
1005 my($bpc, $template, $vars) = @_;
1009 # Return without any substitution if the first entry starts with "&",
1010 # indicating this is perl code.
1012 if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1015 if ( ref($template) ne "ARRAY" ) {
1017 # Split at white space, except if escaped by \
1019 $template = [split(/(?<!\\)\s+/, $template)];
1021 # Remove the \ that escaped white space.
1023 foreach ( @$template ) {
1028 # Merge variables into @tarClientCmd
1030 foreach my $arg ( @$template ) {
1032 # Replace scalar variables first
1034 $arg =~ s{\$(\w+)(\+?)}{
1035 exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1036 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1040 # Now replicate any array arguments; this just works for just one
1041 # array var in each argument.
1043 if ( $arg =~ m{(.*)\$(\w+)(\+?)(.*)} && ref($vars->{$2}) eq "ARRAY" ) {
1048 foreach my $v ( @{$vars->{$var}} ) {
1049 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1050 push(@cmd, "$pre$v$post");
1060 # Exec or eval a command. $cmd is either a string on an array ref.
1062 # @args are optional arguments for the eval() case; they are not used
1067 my($bpc, $cmd, @args) = @_;
1069 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1070 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1071 print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1072 if ( $bpc->{verbose} );
1074 print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1077 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1078 print(STDERR "cmdExecOrEval: about to exec ",
1079 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1080 if ( $bpc->{verbose} );
1082 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1084 # force list-form of exec(), ie: no shell even for 1 arg
1086 exec { $cmd->[0] } @$cmd;
1087 print(STDERR "Exec failed for @$cmd\n");
1093 # System or eval a command. $cmd is either a string on an array ref.
1094 # $stdoutCB is a callback for output generated by the command. If it
1095 # is undef then output is returned. If it is a code ref then the function
1096 # is called with each piece of output as an argument. If it is a scalar
1097 # ref the output is appended to this variable.
1099 # @args are optional arguments for the eval() case; they are not used
1102 # Also, $? should be set when the CHILD pipe is closed.
1104 sub cmdSystemOrEvalLong
1106 my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1107 my($pid, $out, $allOut);
1110 if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1111 $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1112 print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1113 if ( $bpc->{verbose} );
1115 $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1116 &$stdoutCB($out) if ( ref($stdoutCB) eq 'CODE' );
1117 print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1118 if ( $bpc->{verbose} );
1119 return $out if ( !defined($stdoutCB) );
1122 $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1123 print(STDERR "cmdSystemOrEval: about to system ",
1124 $bpc->execCmd2ShellCmd(@$cmd), "\n")
1125 if ( $bpc->{verbose} );
1126 if ( !defined($pid = open(CHILD, "-|")) ) {
1127 my $err = "Can't fork to run @$cmd\n";
1129 $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1130 &$stdoutCB($err) if ( ref($stdoutCB) eq 'CODE' );
1131 return $err if ( !defined($stdoutCB) );
1140 if ( $ignoreStderr ) {
1141 open(STDERR, ">", "/dev/null");
1143 open(STDERR, ">&STDOUT");
1146 $cmd = [map { m/(.*)/ } @$cmd]; # untaint
1148 # force list-form of exec(), ie: no shell even for 1 arg
1150 exec { $cmd->[0] } @$cmd;
1151 print(STDERR "Exec of @$cmd failed\n");
1156 # Notify caller of child's pid
1158 &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1161 # The parent gathers the output from the child
1164 $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1165 &$stdoutCB($_) if ( ref($stdoutCB) eq 'CODE' );
1166 $out .= $_ if ( !defined($stdoutCB) );
1167 $allOut .= $_ if ( $bpc->{verbose} );
1172 print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1173 if ( $bpc->{verbose} );
1178 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1179 # and stderr together.
1183 my($bpc, $cmd, $stdoutCB, @args) = @_;
1185 return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1189 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1190 # to hashes and $conf->{$shareName} to an array.
1192 sub backupFileConfFix
1194 my($bpc, $conf, $shareName) = @_;
1196 $conf->{$shareName} = [ $conf->{$shareName} ]
1197 if ( ref($conf->{$shareName}) ne "ARRAY" );
1198 foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1199 next if ( !defined($conf->{$param}) );
1200 if ( ref($conf->{$param}) eq "HASH" ) {
1202 # A "*" entry means wildcard - it is the default for
1203 # all shares. Replicate the "*" entry for all shares,
1204 # but still allow override of specific entries.
1206 next if ( !defined($conf->{$param}{"*"}) );
1208 map({ $_ => $conf->{$param}{"*"} }
1209 @{$conf->{$shareName}}),
1213 $conf->{$param} = [ $conf->{$param} ]
1214 if ( ref($conf->{$param}) ne "ARRAY" );
1215 $conf->{$param} = { map { $_ => $conf->{$param} }
1216 @{$conf->{$shareName}} };