added common BackupPC::Search::host_backup_nums
[BackupPC.git] / lib / BackupPC / Lib.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Lib package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Lib class and a variety of utility
8 #   functions used by BackupPC.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001-2009  Craig Barratt
15 #
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.
20 #
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.
25 #
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
29 #
30 #========================================================================
31 #
32 # Version 3.2.0, released 31 Jul 2010.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Lib;
39
40 use strict;
41
42 use vars qw(%Conf %Lang);
43 use BackupPC::Storage;
44 use Fcntl ':mode';
45 use Carp;
46 use File::Path;
47 use File::Compare;
48 use Socket;
49 use Cwd;
50 use Digest::MD5;
51 use Config;
52 use Encode qw/from_to encode_utf8/;
53
54 use vars qw( $IODirentOk $IODirentLoaded );
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
56
57 require Exporter;
58 require DynaLoader;
59
60 @ISA = qw(Exporter DynaLoader);
61 @EXPORT_OK = qw( BPC_DT_UNKNOWN
62                  BPC_DT_FIFO
63                  BPC_DT_CHR
64                  BPC_DT_DIR
65                  BPC_DT_BLK
66                  BPC_DT_REG
67                  BPC_DT_LNK
68                  BPC_DT_SOCK
69                );
70 @EXPORT = qw( );
71 %EXPORT_TAGS = ('BPC_DT_ALL' => [@EXPORT, @EXPORT_OK]);
72
73 BEGIN {
74     eval "use IO::Dirent qw( readdirent DT_DIR );";
75     $IODirentLoaded = 1 if ( !$@ );
76 };
77
78 #
79 # The need to match the constants in IO::Dirent
80 #
81 use constant BPC_DT_UNKNOWN =>   0;
82 use constant BPC_DT_FIFO    =>   1;    ## named pipe (fifo)
83 use constant BPC_DT_CHR     =>   2;    ## character special
84 use constant BPC_DT_DIR     =>   4;    ## directory
85 use constant BPC_DT_BLK     =>   6;    ## block special
86 use constant BPC_DT_REG     =>   8;    ## regular
87 use constant BPC_DT_LNK     =>  10;    ## symbolic link
88 use constant BPC_DT_SOCK    =>  12;    ## socket
89
90 sub new
91 {
92     my $class = shift;
93     my($topDir, $installDir, $confDir, $noUserCheck) = @_;
94
95     #
96     # Whether to use filesystem hierarchy standard for file layout.
97     # If set, text config files are below /etc/BackupPC.
98     #
99     my $useFHS = 1;
100     my $paths;
101
102     #
103     # Set defaults for $topDir and $installDir.
104     #
105     $topDir     = '/data/BackupPC' if ( $topDir eq "" );
106     $installDir = '/usr/local/BackupPC'    if ( $installDir eq "" );
107
108         $confDir = '/etc/BackupPC'; # FIXME remove this! XXX
109
110     #
111     # Pick some initial defaults.  For FHS the only critical
112     # path is the ConfDir, since we get everything else out
113     # of the main config file.
114     #
115     if ( $useFHS ) {
116         $paths = {
117             useFHS     => $useFHS,
118             TopDir     => $topDir,
119             InstallDir => $installDir,
120             ConfDir    => $confDir eq "" ? '/data/BackupPC/conf' : $confDir,
121             LogDir     => '/var/log/BackupPC',
122         };
123     } else {
124         $paths = {
125             useFHS     => $useFHS,
126             TopDir     => $topDir,
127             InstallDir => $installDir,
128             ConfDir    => $confDir eq "" ? "$topDir/conf" : $confDir,
129             LogDir     => "$topDir/log",
130         };
131     }
132
133     my $bpc = bless {
134         %$paths,
135         Version => '3.2.0',
136     }, $class;
137
138     $bpc->{storage} = BackupPC::Storage->new($paths);
139
140     #
141     # Clean up %ENV and setup other variables.
142     #
143     delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
144     if ( defined(my $error = $bpc->ConfigRead()) ) {
145         print(STDERR $error, "\n");
146         return;
147     }
148
149     #
150     # Update the paths based on the config file
151     #
152     foreach my $dir ( qw(TopDir ConfDir InstallDir LogDir) ) {
153         next if ( $bpc->{Conf}{$dir} eq "" );
154         $paths->{$dir} = $bpc->{$dir} = $bpc->{Conf}{$dir};
155     }
156     $bpc->{storage}->setPaths($paths);
157     $bpc->{PoolDir}  = "$bpc->{TopDir}/pool";
158     $bpc->{CPoolDir} = "$bpc->{TopDir}/cpool";
159
160     #
161     # Verify we are running as the correct user
162     #
163     if ( !$noUserCheck
164             && $bpc->{Conf}{BackupPCUserVerify}
165             && $> != (my $uid = (getpwnam($bpc->{Conf}{BackupPCUser}))[2]) ) {
166         print(STDERR "$0: Wrong user: my userid is $>, instead of $uid"
167             . " ($bpc->{Conf}{BackupPCUser})\n");
168         print(STDERR "Please su $bpc->{Conf}{BackupPCUser} first\n");
169         return;
170     }
171     return $bpc;
172 }
173
174 sub TopDir
175 {
176     my($bpc) = @_;
177     return $bpc->{TopDir};
178 }
179
180 sub BinDir
181 {
182     my($bpc) = @_;
183     return "$bpc->{InstallDir}/bin";
184 }
185
186 sub LogDir
187 {
188     my($bpc) = @_;
189     return $bpc->{LogDir};
190 }
191
192 sub ConfDir
193 {
194     my($bpc) = @_;
195     return $bpc->{ConfDir};
196 }
197
198 sub LibDir
199 {
200     my($bpc) = @_;
201     return "$bpc->{InstallDir}/lib";
202 }
203
204 sub InstallDir
205 {
206     my($bpc) = @_;
207     return $bpc->{InstallDir};
208 }
209
210 sub useFHS
211 {
212     my($bpc) = @_;
213     return $bpc->{useFHS};
214 }
215
216 sub Version
217 {
218     my($bpc) = @_;
219     return $bpc->{Version};
220 }
221
222 sub Conf
223 {
224     my($bpc) = @_;
225     return %{$bpc->{Conf}};
226 }
227
228 sub Lang
229 {
230     my($bpc) = @_;
231     return $bpc->{Lang};
232 }
233
234 sub adminJob
235 {
236     my($bpc, $num) = @_;
237     return " admin " if ( !$num );
238     return " admin$num ";
239 }
240
241 sub isAdminJob
242 {
243     my($bpc, $str) = @_;
244     return $str =~ /^ admin/;
245 }
246
247 sub trashJob
248 {
249     return " trashClean ";
250 }
251
252 sub ConfValue
253 {
254     my($bpc, $param) = @_;
255
256     return $bpc->{Conf}{$param};
257 }
258
259 sub verbose
260 {
261     my($bpc, $param) = @_;
262
263     $bpc->{verbose} = $param if ( defined($param) );
264     return $bpc->{verbose};
265 }
266
267 sub sigName2num
268 {
269     my($bpc, $sig) = @_;
270
271     if ( !defined($bpc->{SigName2Num}) ) {
272         my $i = 0;
273         foreach my $name ( split(' ', $Config{sig_name}) ) {
274             $bpc->{SigName2Num}{$name} = $i;
275             $i++;
276         }
277     }
278     return $bpc->{SigName2Num}{$sig};
279 }
280
281 #
282 # Generate an ISO 8601 format timeStamp (but without the "T").
283 # See http://www.w3.org/TR/NOTE-datetime and
284 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
285 #
286 sub timeStamp
287 {
288     my($bpc, $t, $noPad) = @_;
289     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
290               = localtime($t || time);
291     return sprintf("%04d-%02d-%02d %02d:%02d:%02d",
292                     $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
293              . ($noPad ? "" : " ");
294 }
295
296 sub BackupInfoRead
297 {
298     my($bpc, $host) = @_;
299
300     return $bpc->{storage}->BackupInfoRead($host);
301 }
302
303 sub BackupInfoWrite
304 {
305     my($bpc, $host, @Backups) = @_;
306
307     return $bpc->{storage}->BackupInfoWrite($host, @Backups);
308 }
309
310 sub RestoreInfoRead
311 {
312     my($bpc, $host) = @_;
313
314     return $bpc->{storage}->RestoreInfoRead($host);
315 }
316
317 sub RestoreInfoWrite
318 {
319     my($bpc, $host, @Restores) = @_;
320
321     return $bpc->{storage}->RestoreInfoWrite($host, @Restores);
322 }
323
324 sub ArchiveInfoRead
325 {
326     my($bpc, $host) = @_;
327
328     return $bpc->{storage}->ArchiveInfoRead($host);
329 }
330
331 sub ArchiveInfoWrite
332 {
333     my($bpc, $host, @Archives) = @_;
334
335     return $bpc->{storage}->ArchiveInfoWrite($host, @Archives);
336 }
337
338 sub ConfigDataRead
339 {
340     my($bpc, $host) = @_;
341
342     return $bpc->{storage}->ConfigDataRead($host);
343 }
344
345 sub ConfigDataWrite
346 {
347     my($bpc, $host, $conf) = @_;
348
349     return $bpc->{storage}->ConfigDataWrite($host, $conf);
350 }
351
352 sub ConfigRead
353 {
354     my($bpc, $host) = @_;
355     my($ret);
356
357     #
358     # Read main config file
359     #
360     my($mesg, $config) = $bpc->{storage}->ConfigDataRead();
361     return $mesg if ( defined($mesg) );
362
363     $bpc->{Conf} = $config;
364
365     #
366     # Read host config file
367     #
368     if ( $host ne "" ) {
369         ($mesg, $config) = $bpc->{storage}->ConfigDataRead($host, $config);
370         return $mesg if ( defined($mesg) );
371         $bpc->{Conf} = $config;
372     }
373
374     #
375     # Load optional perl modules
376     #
377     if ( defined($bpc->{Conf}{PerlModuleLoad}) ) {
378         #
379         # Load any user-specified perl modules.  This is for
380         # optional user-defined extensions.
381         #
382         $bpc->{Conf}{PerlModuleLoad} = [$bpc->{Conf}{PerlModuleLoad}]
383                     if ( ref($bpc->{Conf}{PerlModuleLoad}) ne "ARRAY" );
384         foreach my $module ( @{$bpc->{Conf}{PerlModuleLoad}} ) {
385             eval("use $module;");
386         }
387     }
388
389     #
390     # Load language file
391     #
392     return "No language setting" if ( !defined($bpc->{Conf}{Language}) );
393     my $langFile = "$bpc->{InstallDir}/lib/BackupPC/Lang/$bpc->{Conf}{Language}.pm";
394     if ( !defined($ret = do $langFile) && ($! || $@) ) {
395         $mesg = "Couldn't open language file $langFile: $!" if ( $! );
396         $mesg = "Couldn't execute language file $langFile: $@" if ( $@ );
397         $mesg =~ s/[\n\r]+//;
398         return $mesg;
399     }
400     $bpc->{Lang} = \%Lang;
401
402     #
403     # Make sure IncrLevels is defined
404     #
405     $bpc->{Conf}{IncrLevels} = [1] if ( !defined($bpc->{Conf}{IncrLevels}) );
406
407     return;
408 }
409
410 #
411 # Return the mtime of the config file
412 #
413 sub ConfigMTime
414 {
415     my($bpc) = @_;
416
417     return $bpc->{storage}->ConfigMTime();
418 }
419
420 #
421 # Returns information from the host file in $bpc->{TopDir}/conf/hosts.
422 # With no argument a ref to a hash of hosts is returned.  Each
423 # hash contains fields as specified in the hosts file.  With an
424 # argument a ref to a single hash is returned with information
425 # for just that host.
426 #
427 sub HostInfoRead
428 {
429     my($bpc, $host) = @_;
430
431     return $bpc->{storage}->HostInfoRead($host);
432 }
433
434 sub HostInfoWrite
435 {
436     my($bpc, $host) = @_;
437
438     return $bpc->{storage}->HostInfoWrite($host);
439 }
440
441 #
442 # Return the mtime of the hosts file
443 #
444 sub HostsMTime
445 {
446     my($bpc) = @_;
447
448     return $bpc->{storage}->HostsMTime();
449 }
450
451 #
452 # Read a directory and return the entries in sorted inode order.
453 # This relies on the IO::Dirent module being installed.  If not,
454 # the inode data is empty and the default directory order is
455 # returned.
456 #
457 # The returned data is a list of hashes with entries {name, type, inode, nlink}.
458 # The returned data includes "." and "..".
459 #
460 # $need is a hash of file attributes we need: type, inode, or nlink.
461 # If set, these parameters are added to the returned hash.
462 #
463 # To support browsing pre-3.0.0 backups where the charset encoding
464 # is typically iso-8859-1, the charsetLegacy option can be set in
465 # $need to convert the path from utf8 and convert the names to utf8.
466 #
467 # If IO::Dirent is successful if will get type and inode for free.
468 # Otherwise, a stat is done on each file, which is more expensive.
469 #
470 sub dirRead
471 {
472     my($bpc, $path, $need) = @_;
473     my(@entries, $addInode);
474
475     from_to($path, "utf8", $need->{charsetLegacy})
476                         if ( $need->{charsetLegacy} ne "" );
477     return if ( !opendir(my $fh, $path) );
478     if ( $IODirentLoaded && !$IODirentOk ) {
479         #
480         # Make sure the IO::Dirent really works - some installs
481         # on certain file systems (eg: XFS) don't return a valid type.
482         #
483         if ( opendir(my $fh, $bpc->{TopDir}) ) {
484             my $dt_dir = eval("DT_DIR");
485             foreach my $e ( readdirent($fh) ) {
486                 if ( $e->{name} eq "." && $e->{type} == $dt_dir ) {
487                     $IODirentOk = 1;
488                     last;
489                 }
490             }
491             closedir($fh);
492         }
493         #
494         # if it isn't ok then don't check again.
495         #
496         $IODirentLoaded = 0 if ( !$IODirentOk );
497     }
498     if ( $IODirentOk ) {
499         @entries = sort({ $a->{inode} <=> $b->{inode} } readdirent($fh));
500         map { $_->{type} = 0 + $_->{type} } @entries;   # make type numeric
501     } else {
502         @entries = map { { name => $_} } readdir($fh);
503     }
504     closedir($fh);
505     if ( defined($need) ) {
506         for ( my $i = 0 ; $i < @entries ; $i++ ) {
507             next if ( (!$need->{inode} || defined($entries[$i]{inode}))
508                    && (!$need->{type}  || defined($entries[$i]{type}))
509                    && (!$need->{nlink} || defined($entries[$i]{nlink})) );
510             my @s = stat("$path/$entries[$i]{name}");
511             $entries[$i]{nlink} = $s[3] if ( $need->{nlink} );
512             if ( $need->{inode} && !defined($entries[$i]{inode}) ) {
513                 $addInode = 1;
514                 $entries[$i]{inode} = $s[1];
515             }
516             if ( $need->{type} && !defined($entries[$i]{type}) ) {
517                 my $mode = S_IFMT($s[2]);
518                 $entries[$i]{type} = BPC_DT_FIFO if ( S_ISFIFO($mode) );
519                 $entries[$i]{type} = BPC_DT_CHR  if ( S_ISCHR($mode) );
520                 $entries[$i]{type} = BPC_DT_DIR  if ( S_ISDIR($mode) );
521                 $entries[$i]{type} = BPC_DT_BLK  if ( S_ISBLK($mode) );
522                 $entries[$i]{type} = BPC_DT_REG  if ( S_ISREG($mode) );
523                 $entries[$i]{type} = BPC_DT_LNK  if ( S_ISLNK($mode) );
524                 $entries[$i]{type} = BPC_DT_SOCK if ( S_ISSOCK($mode) );
525             }
526         }
527     }
528     #
529     # Sort the entries if inodes were added (the IO::Dirent case already
530     # sorted above)
531     #
532     @entries = sort({ $a->{inode} <=> $b->{inode} } @entries) if ( $addInode );
533     #
534     # for browing pre-3.0.0 backups, map iso-8859-1 to utf8 if requested
535     #
536     if ( $need->{charsetLegacy} ne "" ) {
537         for ( my $i = 0 ; $i < @entries ; $i++ ) {
538             from_to($entries[$i]{name}, $need->{charsetLegacy}, "utf8");
539         }
540     }
541     return \@entries;
542 }
543
544 #
545 # Same as dirRead, but only returns the names (which will be sorted in
546 # inode order if IO::Dirent is installed)
547 #
548 sub dirReadNames
549 {
550     my($bpc, $path, $need) = @_;
551
552     my $entries = $bpc->dirRead($path, $need);
553     return if ( !defined($entries) );
554     my @names = map { $_->{name} } @$entries;
555     return \@names;
556 }
557
558 sub find
559 {
560     my($bpc, $param, $dir, $dontDoCwd) = @_;
561
562     return if ( !chdir($dir) );
563     my $entries = $bpc->dirRead(".", {inode => 1, type => 1});
564     #print Dumper($entries);
565     foreach my $f ( @$entries ) {
566         next if ( $f->{name} eq ".." || $f->{name} eq "." && $dontDoCwd );
567         $param->{wanted}($f->{name}, "$dir/$f->{name}");
568         next if ( $f->{type} != BPC_DT_DIR || $f->{name} eq "." );
569         chdir($f->{name});
570         $bpc->find($param, "$dir/$f->{name}", 1);
571         return if ( !chdir("..") );
572     }
573 }
574
575 #
576 # Stripped down from File::Path.  In particular we don't print
577 # many warnings and we try three times to delete each directory
578 # and file -- for some reason the original File::Path rmtree
579 # didn't always completely remove a directory tree on a NetApp.
580 #
581 # Warning: this routine changes the cwd.
582 #
583 sub RmTreeQuiet
584 {
585     my($bpc, $pwd, $roots) = @_;
586     my(@files, $root);
587
588     if ( defined($roots) && length($roots) ) {
589       $roots = [$roots] unless ref $roots;
590     } else {
591       print(STDERR "RmTreeQuiet: No root path(s) specified\n");
592     }
593     chdir($pwd);
594     foreach $root (@{$roots}) {
595         $root = $1 if ( $root =~ m{(.*?)/*$} );
596         #
597         # Try first to simply unlink the file: this avoids an
598         # extra stat for every file.  If it fails (which it
599         # will for directories), check if it is a directory and
600         # then recurse.
601         #
602         if ( !unlink($root) ) {
603             if ( -d $root ) {
604                 my $d = $bpc->dirReadNames($root);
605                 if ( !defined($d) ) {
606                     print(STDERR "Can't read $pwd/$root: $!\n");
607                 } else {
608                     @files = grep $_ !~ /^\.{1,2}$/, @$d;
609                     $bpc->RmTreeQuiet("$pwd/$root", \@files);
610                     chdir($pwd);
611                     rmdir($root) || rmdir($root);
612                 }
613             } else {
614                 unlink($root) || unlink($root);
615             }
616         }
617     }
618 }
619
620 #
621 # Move a directory or file away for later deletion
622 #
623 sub RmTreeDefer
624 {
625     my($bpc, $trashDir, $file) = @_;
626     my($i, $f);
627
628     return if ( !-e $file );
629     if ( !-d $trashDir ) {
630         eval { mkpath($trashDir, 0, 0777) };
631         if ( $@ ) {
632             #
633             # There's no good place to send this error - use stderr
634             #
635             print(STDERR "RmTreeDefer: can't create directory $trashDir");
636         }
637     }
638     for ( $i = 0 ; $i < 1000 ; $i++ ) {
639         $f = sprintf("%s/%d_%d_%d", $trashDir, time, $$, $i);
640         next if ( -e $f );
641         return if ( rename($file, $f) );
642     }
643     # shouldn't get here, but might if you tried to call this
644     # across file systems.... just remove the tree right now.
645     if ( $file =~ /(.*)\/([^\/]*)/ ) {
646         my($d) = $1;
647         my($f) = $2;
648         my($cwd) = Cwd::fastcwd();
649         $cwd = $1 if ( $cwd =~ /(.*)/ );
650         $bpc->RmTreeQuiet($d, $f);
651         chdir($cwd) if ( $cwd );
652     }
653 }
654
655 #
656 # Empty the trash directory.  Returns 0 if it did nothing, 1 if it
657 # did something, -1 if it failed to remove all the files.
658 #
659 sub RmTreeTrashEmpty
660 {
661     my($bpc, $trashDir) = @_;
662     my(@files);
663     my($cwd) = Cwd::fastcwd();
664
665     $cwd = $1 if ( $cwd =~ /(.*)/ );
666     return if ( !-d $trashDir );
667     my $d = $bpc->dirReadNames($trashDir) or carp "Can't read $trashDir: $!";
668     @files = grep $_ !~ /^\.{1,2}$/, @$d;
669     return 0 if ( !@files );
670     $bpc->RmTreeQuiet($trashDir, \@files);
671     foreach my $f ( @files ) {
672         return -1 if ( -e $f );
673     }
674     chdir($cwd) if ( $cwd );
675     return 1;
676 }
677
678 #
679 # Open a connection to the server.  Returns an error string on failure.
680 # Returns undef on success.
681 #
682 sub ServerConnect
683 {
684     my($bpc, $host, $port, $justConnect) = @_;
685     local(*FH);
686
687     return if ( defined($bpc->{ServerFD}) );
688     #
689     # First try the unix-domain socket
690     #
691     my $sockFile = "$bpc->{LogDir}/BackupPC.sock";
692     socket(*FH, PF_UNIX, SOCK_STREAM, 0)     || return "unix socket: $!";
693     if ( !connect(*FH, sockaddr_un($sockFile)) ) {
694         my $err = "unix connect: $!";
695         close(*FH);
696         if ( $port > 0 ) {
697             my $proto = getprotobyname('tcp');
698             my $iaddr = inet_aton($host)     || return "unknown host $host";
699             my $paddr = sockaddr_in($port, $iaddr);
700
701             socket(*FH, PF_INET, SOCK_STREAM, $proto)
702                                              || return "inet socket: $!";
703             connect(*FH, $paddr)             || return "inet connect: $!";
704         } else {
705             return $err;
706         }
707     }
708     my($oldFH) = select(*FH); $| = 1; select($oldFH);
709     $bpc->{ServerFD} = *FH;
710     return if ( $justConnect );
711     #
712     # Read the seed that we need for our MD5 message digest.  See
713     # ServerMesg below.
714     #
715     sysread($bpc->{ServerFD}, $bpc->{ServerSeed}, 1024);
716     $bpc->{ServerMesgCnt} = 0;
717     return;
718 }
719
720 #
721 # Check that the server connection is still ok
722 #
723 sub ServerOK
724 {
725     my($bpc) = @_;
726
727     return 0 if ( !defined($bpc->{ServerFD}) );
728     vec(my $FDread, fileno($bpc->{ServerFD}), 1) = 1;
729     my $ein = $FDread;
730     return 0 if ( select(my $rout = $FDread, undef, $ein, 0.0) < 0 );
731     return 1 if ( !vec($rout, fileno($bpc->{ServerFD}), 1) );
732 }
733
734 #
735 # Disconnect from the server
736 #
737 sub ServerDisconnect
738 {
739     my($bpc) = @_;
740     return if ( !defined($bpc->{ServerFD}) );
741     close($bpc->{ServerFD});
742     delete($bpc->{ServerFD});
743 }
744
745 #
746 # Sends a message to the server and returns with the reply.
747 #
748 # To avoid possible attacks via the TCP socket interface, every client
749 # message is protected by an MD5 digest. The MD5 digest includes four
750 # items:
751 #   - a seed that is sent to us when we first connect
752 #   - a sequence number that increments for each message
753 #   - a shared secret that is stored in $Conf{ServerMesgSecret}
754 #   - the message itself.
755 # The message is sent in plain text preceded by the MD5 digest. A
756 # snooper can see the plain-text seed sent by BackupPC and plain-text
757 # message, but cannot construct a valid MD5 digest since the secret in
758 # $Conf{ServerMesgSecret} is unknown. A replay attack is not possible
759 # since the seed changes on a per-connection and per-message basis.
760 #
761 sub ServerMesg
762 {
763     my($bpc, $mesg) = @_;
764     return if ( !defined(my $fh = $bpc->{ServerFD}) );
765     $mesg =~ s/\n/\\n/g;
766     $mesg =~ s/\r/\\r/g;
767     my $md5 = Digest::MD5->new;
768     $mesg = encode_utf8($mesg);
769     $md5->add($bpc->{ServerSeed} . $bpc->{ServerMesgCnt}
770             . $bpc->{Conf}{ServerMesgSecret} . $mesg);
771     print($fh $md5->b64digest . " $mesg\n");
772     $bpc->{ServerMesgCnt}++;
773     return <$fh>;
774 }
775
776 #
777 # Do initialization for child processes
778 #
779 sub ChildInit
780 {
781     my($bpc) = @_;
782     close(STDERR);
783     open(STDERR, ">&STDOUT");
784     select(STDERR); $| = 1;
785     select(STDOUT); $| = 1;
786     $ENV{PATH} = $bpc->{Conf}{MyPath};
787 }
788
789 #
790 # Compute the MD5 digest of a file.  For efficiency we don't
791 # use the whole file for big files:
792 #   - for files <= 256K we use the file size and the whole file.
793 #   - for files <= 1M we use the file size, the first 128K and
794 #     the last 128K.
795 #   - for files > 1M, we use the file size, the first 128K and
796 #     the 8th 128K (ie: the 128K up to 1MB).
797 # See the documentation for a discussion of the tradeoffs in
798 # how much data we use and how many collisions we get.
799 #
800 # Returns the MD5 digest (a hex string) and the file size.
801 #
802 sub File2MD5
803 {
804     my($bpc, $md5, $name) = @_;
805     my($data, $fileSize);
806     local(*N);
807
808     $fileSize = (stat($name))[7];
809     return ("", -1) if ( !-f _ );
810     $name = $1 if ( $name =~ /(.*)/ );
811     return ("", 0) if ( $fileSize == 0 );
812     return ("", -1) if ( !open(N, $name) );
813     binmode(N);
814     $md5->reset();
815     $md5->add($fileSize);
816     if ( $fileSize > 262144 ) {
817         #
818         # read the first and last 131072 bytes of the file,
819         # up to 1MB.
820         #
821         my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
822         $md5->add($data) if ( sysread(N, $data, 131072) );
823         $md5->add($data) if ( sysseek(N, $seekPosn, 0)
824                                 && sysread(N, $data, 131072) );
825     } else {
826         #
827         # read the whole file
828         #
829         $md5->add($data) if ( sysread(N, $data, $fileSize) );
830     }
831     close(N);
832     return ($md5->hexdigest, $fileSize);
833 }
834
835 #
836 # Compute the MD5 digest of a buffer (string).  For efficiency we don't
837 # use the whole string for big strings:
838 #   - for files <= 256K we use the file size and the whole file.
839 #   - for files <= 1M we use the file size, the first 128K and
840 #     the last 128K.
841 #   - for files > 1M, we use the file size, the first 128K and
842 #     the 8th 128K (ie: the 128K up to 1MB).
843 # See the documentation for a discussion of the tradeoffs in
844 # how much data we use and how many collisions we get.
845 #
846 # Returns the MD5 digest (a hex string).
847 #
848 sub Buffer2MD5
849 {
850     my($bpc, $md5, $fileSize, $dataRef) = @_;
851
852     $md5->reset();
853     $md5->add($fileSize);
854     if ( $fileSize > 262144 ) {
855         #
856         # add the first and last 131072 bytes of the string,
857         # up to 1MB.
858         #
859         my $seekPosn = ($fileSize > 1048576 ? 1048576 : $fileSize) - 131072;
860         $md5->add(substr($$dataRef, 0, 131072));
861         $md5->add(substr($$dataRef, $seekPosn, 131072));
862     } else {
863         #
864         # add the whole string
865         #
866         $md5->add($$dataRef);
867     }
868     return $md5->hexdigest;
869 }
870
871 #
872 # Given an MD5 digest $d and a compress flag, return the full
873 # path in the pool.
874 #
875 sub MD52Path
876 {
877     my($bpc, $d, $compress, $poolDir) = @_;
878
879     return if ( $d !~ m{(.)(.)(.)(.*)} );
880     $poolDir = ($compress ? $bpc->{CPoolDir} : $bpc->{PoolDir})
881                     if ( !defined($poolDir) );
882     return "$poolDir/$1/$2/$3/$1$2$3$4";
883 }
884
885 #
886 # For each file, check if the file exists in $bpc->{TopDir}/pool.
887 # If so, remove the file and make a hardlink to the file in
888 # the pool.  Otherwise, if the newFile flag is set, make a
889 # hardlink in the pool to the new file.
890 #
891 # Returns 0 if a link should be made to a new file (ie: when the file
892 #    is a new file but the newFile flag is 0).
893 # Returns 1 if a link to an existing file is made,
894 # Returns 2 if a link to a new file is made (only if $newFile is set)
895 # Returns negative on error.
896 #
897 sub MakeFileLink
898 {
899     my($bpc, $name, $d, $newFile, $compress) = @_;
900     my($i, $rawFile);
901
902     return -1 if ( !-f $name );
903     for ( $i = -1 ; ; $i++ ) {
904         return -2 if ( !defined($rawFile = $bpc->MD52Path($d, $compress)) );
905         $rawFile .= "_$i" if ( $i >= 0 );
906         if ( -f $rawFile ) {
907             if ( (stat(_))[3] < $bpc->{Conf}{HardLinkMax}
908                     && !compare($name, $rawFile) ) {
909                 unlink($name);
910                 return -3 if ( !link($rawFile, $name) );
911                 return 1;
912             }
913         } elsif ( $newFile && -f $name && (stat($name))[3] == 1 ) {
914             my($newDir);
915             ($newDir = $rawFile) =~ s{(.*)/.*}{$1};
916             if ( !-d $newDir ) {
917                 eval { mkpath($newDir, 0, 0777) };
918                 return -5 if ( $@ );
919             }
920             return -4 if ( !link($name, $rawFile) );
921             return 2;
922         } else {
923             return 0;
924         }
925     }
926 }
927
928 #
929 # Tests if we can create a hardlink from a file in directory
930 # $newDir to a file in directory $targetDir.  A temporary
931 # file in $targetDir is created and an attempt to create a
932 # hardlink of the same name in $newDir is made.  The temporary
933 # files are removed.
934 #
935 # Like link(), returns true on success and false on failure.
936 #
937 sub HardlinkTest
938 {
939     my($bpc, $targetDir, $newDir) = @_;
940
941     my($targetFile, $newFile, $fd);
942     for ( my $i = 0 ; ; $i++ ) {
943         $targetFile = "$targetDir/.TestFileLink.$$.$i";
944         $newFile    = "$newDir/.TestFileLink.$$.$i";
945         last if ( !-e $targetFile && !-e $newFile );
946     }
947     return 0 if ( !open($fd, ">", $targetFile) );
948     close($fd);
949     my $ret = link($targetFile, $newFile);
950     unlink($targetFile);
951     unlink($newFile);
952     return $ret;
953 }
954
955 sub CheckHostAlive
956 {
957     my($bpc, $host) = @_;
958     my($s, $pingCmd, $ret);
959
960     #
961     # Return success if the ping cmd is undefined or empty.
962     #
963     if ( $bpc->{Conf}{PingCmd} eq "" ) {
964         print(STDERR "CheckHostAlive: return ok because \$Conf{PingCmd}"
965                    . " is empty\n") if ( $bpc->{verbose} );
966         return 0;
967     }
968
969     my $args = {
970         pingPath => $bpc->{Conf}{PingPath},
971         host     => $host,
972     };
973     $pingCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{PingCmd}, $args);
974
975     #
976     # Do a first ping in case the PC needs to wakeup
977     #
978     $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
979     if ( $? ) {
980         print(STDERR "CheckHostAlive: first ping failed ($?, $!)\n")
981                         if ( $bpc->{verbose} );
982         return -1;
983     }
984
985     #
986     # Do a second ping and get the round-trip time in msec
987     #
988     $s = $bpc->cmdSystemOrEval($pingCmd, undef, $args);
989     if ( $? ) {
990         print(STDERR "CheckHostAlive: second ping failed ($?, $!)\n")
991                         if ( $bpc->{verbose} );
992         return -1;
993     }
994     if ( $s =~ /rtt\s*min\/avg\/max\/mdev\s*=\s*[\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+\s*(ms|usec)/i ) {
995         $ret = $1;
996         $ret /= 1000 if ( lc($2) eq "usec" );
997     } elsif ( $s =~ /time=([\d.]+)\s*(ms|usec)/i ) {
998         $ret = $1;
999         $ret /= 1000 if ( lc($2) eq "usec" );
1000     } else {
1001         print(STDERR "CheckHostAlive: can't extract round-trip time"
1002                    . " (not fatal)\n") if ( $bpc->{verbose} );
1003         $ret = 0;
1004     }
1005     print(STDERR "CheckHostAlive: returning $ret\n") if ( $bpc->{verbose} );
1006     return $ret;
1007 }
1008
1009 sub CheckFileSystemUsage
1010 {
1011     my($bpc) = @_;
1012     my($topDir) = $bpc->{TopDir};
1013     my($s, $dfCmd);
1014
1015     return 0 if ( $bpc->{Conf}{DfCmd} eq "" );
1016     my $args = {
1017         dfPath   => $bpc->{Conf}{DfPath},
1018         topDir   => $bpc->{TopDir},
1019     };
1020     $dfCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{DfCmd}, $args);
1021     $s = $bpc->cmdSystemOrEval($dfCmd, undef, $args);
1022     return 0 if ( $? || $s !~ /(\d+)%/s );
1023     return $1;
1024 }
1025
1026 #
1027 # Given an IP address, return the host name and user name via
1028 # NetBios.
1029 #
1030 sub NetBiosInfoGet
1031 {
1032     my($bpc, $host) = @_;
1033     my($netBiosHostName, $netBiosUserName);
1034     my($s, $nmbCmd);
1035
1036     #
1037     # Skip NetBios check if NmbLookupCmd is emtpy
1038     #
1039     if ( $bpc->{Conf}{NmbLookupCmd} eq "" ) {
1040         print(STDERR "NetBiosInfoGet: return $host because \$Conf{NmbLookupCmd}"
1041                    . " is empty\n") if ( $bpc->{verbose} );
1042         return ($host, undef);
1043     }
1044
1045     my $args = {
1046         nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1047         host          => $host,
1048     };
1049     $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupCmd}, $args);
1050     foreach ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef, $args)) ) {
1051         #
1052         # skip <GROUP> and other non <ACTIVE> entries
1053         #
1054         next if ( /<\w{2}> - <GROUP>/i );
1055         next if ( !/^\s*([\w\s-]+?)\s*<(\w{2})\> - .*<ACTIVE>/i );
1056         $netBiosHostName ||= $1 if ( $2 eq "00" );  # host is first 00
1057         $netBiosUserName   = $1 if ( $2 eq "03" );  # user is last 03
1058     }
1059     if ( !defined($netBiosHostName) ) {
1060         print(STDERR "NetBiosInfoGet: failed: can't parse return string\n")
1061                         if ( $bpc->{verbose} );
1062         return;
1063     }
1064     $netBiosHostName = lc($netBiosHostName);
1065     $netBiosUserName = lc($netBiosUserName);
1066     print(STDERR "NetBiosInfoGet: success, returning host $netBiosHostName,"
1067                . " user $netBiosUserName\n") if ( $bpc->{verbose} );
1068     return ($netBiosHostName, $netBiosUserName);
1069 }
1070
1071 #
1072 # Given a NetBios name lookup the IP address via NetBios.
1073 # In the case of a host returning multiple interfaces we
1074 # return the first IP address that matches the subnet mask.
1075 # If none match the subnet mask (or nmblookup doesn't print
1076 # the subnet mask) then just the first IP address is returned.
1077 #
1078 sub NetBiosHostIPFind
1079 {
1080     my($bpc, $host) = @_;
1081     my($netBiosHostName, $netBiosUserName);
1082     my($s, $nmbCmd, $subnet, $ipAddr, $firstIpAddr);
1083
1084     #
1085     # Skip NetBios lookup if NmbLookupFindHostCmd is emtpy
1086     #
1087     if ( $bpc->{Conf}{NmbLookupFindHostCmd} eq "" ) {
1088         print(STDERR "NetBiosHostIPFind: return $host because"
1089             . " \$Conf{NmbLookupFindHostCmd} is empty\n")
1090                 if ( $bpc->{verbose} );
1091         return $host;
1092     }
1093
1094     my $args = {
1095         nmbLookupPath => $bpc->{Conf}{NmbLookupPath},
1096         host          => $host,
1097     };
1098     $nmbCmd = $bpc->cmdVarSubstitute($bpc->{Conf}{NmbLookupFindHostCmd}, $args);
1099     foreach my $resp ( split(/[\n\r]+/, $bpc->cmdSystemOrEval($nmbCmd, undef,
1100                                                               $args) ) ) {
1101         if ( $resp =~ /querying\s+\Q$host\E\s+on\s+(\d+\.\d+\.\d+\.\d+)/i ) {
1102             $subnet = $1;
1103             $subnet = $1 if ( $subnet =~ /^(.*?)(\.255)+$/ );
1104         } elsif ( $resp =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+\Q$host/ ) {
1105             my $ip = $1;
1106             $firstIpAddr = $ip if ( !defined($firstIpAddr) );
1107             $ipAddr      = $ip if ( !defined($ipAddr) && $ip =~ /^\Q$subnet/ );
1108         }
1109     }
1110     $ipAddr = $firstIpAddr if ( !defined($ipAddr) );
1111     if ( defined($ipAddr) ) {
1112         print(STDERR "NetBiosHostIPFind: found IP address $ipAddr for"
1113                    . " host $host\n") if ( $bpc->{verbose} );
1114         return $ipAddr;
1115     } else {
1116         print(STDERR "NetBiosHostIPFind: couldn't find IP address for"
1117                    . " host $host\n") if ( $bpc->{verbose} );
1118         return;
1119     }
1120 }
1121
1122 sub fileNameEltMangle
1123 {
1124     my($bpc, $name) = @_;
1125
1126     return "" if ( $name eq "" );
1127     $name =~ s{([%/\n\r])}{sprintf("%%%02x", ord($1))}eg;
1128     return "f$name";
1129 }
1130
1131 #
1132 # We store files with every name preceded by "f".  This
1133 # avoids possible name conflicts with other information
1134 # we store in the same directories (eg: attribute info).
1135 # The process of turning a normal path into one with each
1136 # node prefixed with "f" is called mangling.
1137 #
1138 sub fileNameMangle
1139 {
1140     my($bpc, $name) = @_;
1141
1142     $name =~ s{/([^/]+)}{"/" . $bpc->fileNameEltMangle($1)}eg;
1143     $name =~ s{^([^/]+)}{$bpc->fileNameEltMangle($1)}eg;
1144     return $name;
1145 }
1146
1147 #
1148 # This undoes FileNameMangle
1149 #
1150 sub fileNameUnmangle
1151 {
1152     my($bpc, $name) = @_;
1153
1154     $name =~ s{/f}{/}g;
1155     $name =~ s{^f}{};
1156     $name =~ s{%(..)}{chr(hex($1))}eg;
1157     return $name;
1158 }
1159
1160 #
1161 # Escape shell meta-characters with backslashes.
1162 # This should be applied to each argument seperately, not an
1163 # entire shell command.
1164 #
1165 sub shellEscape
1166 {
1167     my($bpc, $cmd) = @_;
1168
1169     $cmd =~ s/([][;&()<>{}|^\n\r\t *\$\\'"`?])/\\$1/g;
1170     return $cmd;
1171 }
1172
1173 #
1174 # For printing exec commands (which don't use a shell) so they look like
1175 # a valid shell command this function should be called with the exec
1176 # args.  The shell command string is returned.
1177 #
1178 sub execCmd2ShellCmd
1179 {
1180     my($bpc, @args) = @_;
1181     my $str;
1182
1183     foreach my $a ( @args ) {
1184         $str .= " " if ( $str ne "" );
1185         $str .= $bpc->shellEscape($a);
1186     }
1187     return $str;
1188 }
1189
1190 #
1191 # Do a URI-style escape to protect/encode special characters
1192 #
1193 sub uriEsc
1194 {
1195     my($bpc, $s) = @_;
1196     $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1197     return $s;
1198 }
1199
1200 #
1201 # Do a URI-style unescape to restore special characters
1202 #
1203 sub uriUnesc
1204 {
1205     my($bpc, $s) = @_;
1206     $s =~ s{%(..)}{chr(hex($1))}eg;
1207     return $s;
1208 }
1209
1210 #
1211 # Do variable substitution prior to execution of a command.
1212 #
1213 sub cmdVarSubstitute
1214 {
1215     my($bpc, $template, $vars) = @_;
1216     my(@cmd);
1217
1218     #
1219     # Return without any substitution if the first entry starts with "&",
1220     # indicating this is perl code.
1221     #
1222     if ( (ref($template) eq "ARRAY" ? $template->[0] : $template) =~ /^\&/ ) {
1223         return $template;
1224     }
1225     if ( ref($template) ne "ARRAY" ) {
1226         #
1227         # Split at white space, except if escaped by \
1228         #
1229         $template = [split(/(?<!\\)\s+/, $template)];
1230         #
1231         # Remove the \ that escaped white space.
1232         #
1233         foreach ( @$template ) {
1234             s{\\(\s)}{$1}g;
1235         }
1236     }
1237     #
1238     # Merge variables into @cmd
1239     #
1240     foreach my $arg ( @$template ) {
1241         #
1242         # Replace $VAR with ${VAR} so that both types of variable
1243         # substitution are supported
1244         #
1245         $arg =~ s[\$(\w+)]{\${$1}}g;
1246         #
1247         # Replace scalar variables first
1248         #
1249         $arg =~ s[\${(\w+)}(\+?)]{
1250             exists($vars->{$1}) && ref($vars->{$1}) ne "ARRAY"
1251                 ? ($2 eq "+" ? $bpc->shellEscape($vars->{$1}) : $vars->{$1})
1252                 : "\${$1}$2"
1253         }eg;
1254         #
1255         # Now replicate any array arguments; this just works for just one
1256         # array var in each argument.
1257         #
1258         if ( $arg =~ m[(.*)\${(\w+)}(\+?)(.*)] && ref($vars->{$2}) eq "ARRAY" ) {
1259             my $pre  = $1;
1260             my $var  = $2;
1261             my $esc  = $3;
1262             my $post = $4;
1263             foreach my $v ( @{$vars->{$var}} ) {
1264                 $v = $bpc->shellEscape($v) if ( $esc eq "+" );
1265                 push(@cmd, "$pre$v$post");
1266             }
1267         } else {
1268             push(@cmd, $arg);
1269         }
1270     }
1271     return \@cmd;
1272 }
1273
1274 #
1275 # Exec or eval a command.  $cmd is either a string on an array ref.
1276 #
1277 # @args are optional arguments for the eval() case; they are not used
1278 # for exec().
1279 #
1280 sub cmdExecOrEval
1281 {
1282     my($bpc, $cmd, @args) = @_;
1283     
1284     if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1285         $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1286         print(STDERR "cmdExecOrEval: about to eval perl code $cmd\n")
1287                         if ( $bpc->{verbose} );
1288         eval($cmd);
1289         print(STDERR "Perl code fragment for exec shouldn't return!!\n");
1290         exit(1);
1291     } else {
1292         $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1293         print(STDERR "cmdExecOrEval: about to exec ",
1294               $bpc->execCmd2ShellCmd(@$cmd), "\n")
1295                         if ( $bpc->{verbose} );
1296         alarm(0);
1297         $cmd = [map { m/(.*)/ } @$cmd];         # untaint
1298         #
1299         # force list-form of exec(), ie: no shell even for 1 arg
1300         #
1301         exec { $cmd->[0] } @$cmd;
1302         print(STDERR "Exec failed for @$cmd\n");
1303         exit(1);
1304     }
1305 }
1306
1307 #
1308 # System or eval a command.  $cmd is either a string on an array ref.
1309 # $stdoutCB is a callback for output generated by the command.  If it
1310 # is undef then output is returned.  If it is a code ref then the function
1311 # is called with each piece of output as an argument.  If it is a scalar
1312 # ref the output is appended to this variable.
1313 #
1314 # @args are optional arguments for the eval() case; they are not used
1315 # for system().
1316 #
1317 # Also, $? should be set when the CHILD pipe is closed.
1318 #
1319 sub cmdSystemOrEvalLong
1320 {
1321     my($bpc, $cmd, $stdoutCB, $ignoreStderr, $pidHandlerCB, @args) = @_;
1322     my($pid, $out, $allOut);
1323     local(*CHILD);
1324     
1325     $? = 0;
1326     if ( (ref($cmd) eq "ARRAY" ? $cmd->[0] : $cmd) =~ /^\&/ ) {
1327         $cmd = join(" ", $cmd) if ( ref($cmd) eq "ARRAY" );
1328         print(STDERR "cmdSystemOrEval: about to eval perl code $cmd\n")
1329                         if ( $bpc->{verbose} );
1330         $out = eval($cmd);
1331         $$stdoutCB .= $out if ( ref($stdoutCB) eq 'SCALAR' );
1332         &$stdoutCB($out)   if ( ref($stdoutCB) eq 'CODE' );
1333         print(STDERR "cmdSystemOrEval: finished: got output $out\n")
1334                         if ( $bpc->{verbose} );
1335         return $out        if ( !defined($stdoutCB) );
1336         return;
1337     } else {
1338         $cmd = [split(/\s+/, $cmd)] if ( ref($cmd) ne "ARRAY" );
1339         print(STDERR "cmdSystemOrEval: about to system ",
1340               $bpc->execCmd2ShellCmd(@$cmd), "\n")
1341                         if ( $bpc->{verbose} );
1342         if ( !defined($pid = open(CHILD, "-|")) ) {
1343             my $err = "Can't fork to run @$cmd\n";
1344             $? = 1;
1345             $$stdoutCB .= $err if ( ref($stdoutCB) eq 'SCALAR' );
1346             &$stdoutCB($err)   if ( ref($stdoutCB) eq 'CODE' );
1347             return $err        if ( !defined($stdoutCB) );
1348             return;
1349         }
1350         binmode(CHILD);
1351         if ( !$pid ) {
1352             #
1353             # This is the child
1354             #
1355             close(STDERR);
1356             if ( $ignoreStderr ) {
1357                 open(STDERR, ">", "/dev/null");
1358             } else {
1359                 open(STDERR, ">&STDOUT");
1360             }
1361             alarm(0);
1362             $cmd = [map { m/(.*)/ } @$cmd];             # untaint
1363             #
1364             # force list-form of exec(), ie: no shell even for 1 arg
1365             #
1366             exec { $cmd->[0] } @$cmd;
1367             print(STDERR "Exec of @$cmd failed\n");
1368             exit(1);
1369         }
1370
1371         #
1372         # Notify caller of child's pid
1373         #
1374         &$pidHandlerCB($pid) if ( ref($pidHandlerCB) eq "CODE" );
1375
1376         #
1377         # The parent gathers the output from the child
1378         #
1379         while ( <CHILD> ) {
1380             $$stdoutCB .= $_ if ( ref($stdoutCB) eq 'SCALAR' );
1381             &$stdoutCB($_)   if ( ref($stdoutCB) eq 'CODE' );
1382             $out .= $_       if ( !defined($stdoutCB) );
1383             $allOut .= $_    if ( $bpc->{verbose} );
1384         }
1385         $? = 0;
1386         close(CHILD);
1387     }
1388     print(STDERR "cmdSystemOrEval: finished: got output $allOut\n")
1389                         if ( $bpc->{verbose} );
1390     return $out;
1391 }
1392
1393 #
1394 # The shorter version that sets $ignoreStderr = 0, ie: merges stdout
1395 # and stderr together.
1396 #
1397 sub cmdSystemOrEval
1398 {
1399     my($bpc, $cmd, $stdoutCB, @args) = @_;
1400
1401     return $bpc->cmdSystemOrEvalLong($cmd, $stdoutCB, 0, undef, @args);
1402 }
1403
1404 #
1405 # Promotes $conf->{BackupFilesOnly}, $conf->{BackupFilesExclude}
1406 # to hashes and $conf->{$shareName} to an array.
1407 #
1408 sub backupFileConfFix
1409 {
1410     my($bpc, $conf, $shareName) = @_;
1411
1412     $conf->{$shareName} = [ $conf->{$shareName} ]
1413                     if ( ref($conf->{$shareName}) ne "ARRAY" );
1414     foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
1415         next if ( !defined($conf->{$param}) );
1416         if ( ref($conf->{$param}) eq "HASH" ) {
1417             #
1418             # A "*" entry means wildcard - it is the default for
1419             # all shares.  Replicate the "*" entry for all shares,
1420             # but still allow override of specific entries.
1421             #
1422             next if ( !defined($conf->{$param}{"*"}) );
1423             $conf->{$param} = {
1424                                     map({ $_ => $conf->{$param}{"*"} }
1425                                             @{$conf->{$shareName}}),
1426                                     %{$conf->{$param}}
1427                               };
1428         } else {
1429             $conf->{$param} = [ $conf->{$param} ]
1430                                     if ( ref($conf->{$param}) ne "ARRAY" );
1431             $conf->{$param} = { map { $_ => $conf->{$param} }
1432                                     @{$conf->{$shareName}} };
1433         }
1434     }
1435 }
1436
1437 #
1438 # This is sort() compare function, used below.
1439 #
1440 # New client LOG names are LOG.MMYYYY.  Old style names are
1441 # LOG, LOG.0, LOG.1 etc.  Sort them so new names are
1442 # first, and newest to oldest.
1443 #
1444 sub compareLOGName
1445 {
1446     my $na = $1 if ( $a =~ /LOG\.(\d+)(\.z)?$/ );
1447     my $nb = $1 if ( $b =~ /LOG\.(\d+)(\.z)?$/ );
1448
1449     $na = -1 if ( !defined($na) );
1450     $nb = -1 if ( !defined($nb) );
1451
1452     if ( length($na) >= 5 && length($nb) >= 5 ) {
1453         #
1454         # Both new style: format is MMYYYY.  Bigger dates are
1455         # more recent.
1456         #
1457         my $ma = $2 * 12 + $1 if ( $na =~ /(\d+)(\d{4})/ );
1458         my $mb = $2 * 12 + $1 if ( $nb =~ /(\d+)(\d{4})/ );
1459         return $mb - $ma;
1460     } elsif ( length($na) >= 5 && length($nb) < 5 ) {
1461         return -1;
1462     } elsif ( length($na) < 5 && length($nb) >= 5 ) {
1463         return 1;
1464     } else {
1465         #
1466         # Both old style.  Smaller numbers are more recent.
1467         #
1468         return $na - $nb;
1469     }
1470 }
1471
1472 #
1473 # Returns list of paths to a clients's (or main) LOG files,
1474 # most recent first.
1475 #
1476 sub sortedPCLogFiles
1477 {
1478     my($bpc, $host) = @_;
1479
1480     my(@files, $dir);
1481
1482     if ( $host ne "" ) {
1483         $dir = "$bpc->{TopDir}/pc/$host";
1484     } else {
1485         $dir = "$bpc->{LogDir}";
1486     }
1487     if ( opendir(DIR, $dir) ) {
1488         foreach my $file ( readdir(DIR) ) {
1489             next if ( !-f "$dir/$file" );
1490             next if ( $file ne "LOG" && $file !~ /^LOG\.\d/ );
1491             push(@files, "$dir/$file");
1492         }
1493         closedir(DIR);
1494     }
1495     return sort compareLOGName @files;
1496 }
1497
1498 #
1499 # converts a glob-style pattern into a perl regular expression.
1500 #
1501 sub glob2re
1502 {
1503     my ( $bpc, $glob ) = @_;
1504     my ( $char, $subst );
1505
1506     # $escapeChars escapes characters with no special glob meaning but
1507     # have meaning in regexps.
1508     my $escapeChars = [ '.', '/', ];
1509
1510     # $charMap is where we implement the special meaning of glob
1511     # patterns and translate them to regexps.
1512     my $charMap = {
1513                     '?' => '[^/]',
1514                     '*' => '[^/]*', };
1515
1516     # multiple forward slashes are equivalent to one slash.  We should
1517     # never have to use this.
1518     $glob =~ s/\/+/\//;
1519
1520     foreach $char (@$escapeChars) {
1521         $glob =~ s/\Q$char\E/\\$char/g;
1522     }
1523
1524     while ( ( $char, $subst ) = each(%$charMap) ) {
1525         $glob =~ s/(?<!\\)\Q$char\E/$subst/g;
1526     }
1527
1528     return $glob;
1529 }
1530
1531 1;