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