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