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