* Added Simplified Chinese CGI translation from Youlin Feng.
[BackupPC.git] / bin / BackupPC_restore
1 #!/bin/perl
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_restore: Restore files to a client.
5 #
6 # DESCRIPTION
7 #
8 #   Usage: BackupPC_restore <hostIP> <client> <reqFileName>
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 use strict;
39 no  utf8;
40 use lib "/usr/local/BackupPC/lib";
41 use BackupPC::Lib;
42 use BackupPC::FileZIO;
43 use BackupPC::Xfer::Smb;
44 use BackupPC::Xfer::Tar;
45 use BackupPC::Xfer::Rsync;
46 use BackupPC::Xfer::BackupPCd;
47 use Socket;
48
49 use File::Path;
50 use Getopt::Std;
51
52 use vars qw( %RestoreReq );
53
54 ###########################################################################
55 # Initialize
56 ###########################################################################
57
58 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
59 my $TopDir = $bpc->TopDir();
60 my $BinDir = $bpc->BinDir();
61 my %Conf   = $bpc->Conf();
62 my $NeedPostCmd;
63
64 my($hostIP, $host, $client, $reqFileName, %stat);
65
66 $bpc->ChildInit();
67
68 if ( @ARGV != 3 ) {
69     print("usage: $0 <hostIP> <client> <reqFileName>\n");
70     exit(1);
71 }
72 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
73 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
74 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
75     print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
76     exit(1);
77 }
78 $reqFileName = $1;
79
80 my $startTime = time();
81
82 my $Hosts = $bpc->HostInfoRead($client);
83
84 my $Dir     = "$TopDir/pc/$client";
85 my @xferPid = ();
86 my $tarPid  = -1;
87
88 #
89 # Catch various signals
90 #
91 $SIG{INT}  = \&catch_signal;
92 $SIG{ALRM} = \&catch_signal;
93 $SIG{TERM} = \&catch_signal;
94 $SIG{PIPE} = \&catch_signal;
95 $SIG{STOP} = \&catch_signal;
96 $SIG{TSTP} = \&catch_signal;
97 $SIG{TTIN} = \&catch_signal;
98 my $Pid = $$;
99
100 mkpath($Dir, 0, 0777) if ( !-d $Dir );
101 if ( !-f "$Dir/LOCK" ) {
102     open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
103 }
104
105 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
106 my $logPath = sprintf("$Dir/LOG.%02d%04d", $mon + 1, $year + 1900);
107
108 if ( !-f $logPath ) {
109     #
110     # Compress and prune old log files
111     #
112     my $lastLog = $Conf{MaxOldPerPCLogFiles} - 1;
113     foreach my $file ( $bpc->sortedPCLogFiles($client) ) {
114         if ( $lastLog <= 0 ) {
115             unlink($file);
116             next;
117         }
118         $lastLog--;
119         next if ( $file =~ /\.z$/ || !$Conf{CompressLevel} );
120         BackupPC::FileZIO->compressCopy($file,
121                                         "$file.z",
122                                         undef,
123                                         $Conf{CompressLevel}, 1);
124     }
125 }
126 open(LOG, ">>", $logPath);
127 select(LOG); $| = 1; select(STDOUT);
128
129 #
130 # Read the request file
131 #
132 if ( !(my $ret = do "$Dir/$reqFileName") ) {
133     my $err;
134     if ( $@ ) {
135         $err = "couldn't parse $Dir/$reqFileName: $@";
136     } elsif ( !defined($ret) ) {
137         $err = "couldn't do $Dir/$reqFileName: $!";
138     } else {
139         $err = "couldn't run $Dir/$reqFileName";
140     }
141     $stat{hostError} = $err;
142     exit(RestoreCleanup($client));
143 }
144
145 #
146 # Re-read config file, so we can include the PC-specific config
147 #
148 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
149     $stat{hostError} = "Can't read PC's config file: $error";
150     exit(RestoreCleanup($client));
151 }
152 %Conf = $bpc->Conf();
153
154 #
155 # Make sure we eventually timeout if there is no activity from
156 # the data transport program.
157 #
158 alarm($Conf{ClientTimeout});
159
160 #
161 # See if the host name is aliased
162 #
163 if ( $Conf{ClientNameAlias} ne "" ) {
164     $host = $Conf{ClientNameAlias};
165 } else {
166     $host = $client;
167 }
168
169 #
170 # Find its IP address
171 #
172 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
173     if ( !defined(gethostbyname($host)) ) {
174         #
175         # Ok, NS doesn't know about it.  Maybe it is a NetBios name
176         # instead.
177         #
178         if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
179             $stat{hostError} = "Can't find host $host";
180             exit(RestoreCleanup($client));
181         }
182     } else {
183         $hostIP = $host;
184     }
185 }
186
187 #
188 # Check if $host is alive
189 #
190 my $delay = $bpc->CheckHostAlive($hostIP);
191 if ( $delay < 0 ) {
192     $stat{hostError} = "no ping response from $host ($hostIP)";
193     exit(RestoreCleanup($client));
194 } elsif ( $delay > $Conf{PingMaxMsec} ) {
195     $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
196                     $delay, $Conf{PingMaxMsec});
197     exit(RestoreCleanup($client));
198 }
199
200 #
201 # Make sure it is really the machine we expect
202 #
203 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
204     $stat{hostError} = $errMsg;
205     exit(RestoreCleanup($client));
206 }
207
208 #
209 # Setup file extension for compression and open RestoreLOG output file
210 #
211 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
212     $stat{hostError} = "Compress:Zlib not found";
213     exit(RestoreCleanup($client));
214 }
215 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
216 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
217                                      $Conf{CompressLevel});
218 my $tarCreateFileCnt = 0;
219 my $tarCreateByteCnt = 0;
220 my $tarCreateDirCnt  = 0;
221 my $tarCreateErrCnt  = 1;       # assume not ok until we learn otherwise
222 my $tarCreateErr;
223 my($logMsg, $xfer);
224
225 $stat{xferOK} = $stat{hostAbort} = undef;
226 $stat{hostError} = $stat{lastOutputLine} = undef;
227 local(*RH, *WH);
228
229 #
230 # Run an optional pre-restore command
231 #
232 UserCommandRun("RestorePreUserCmd");
233 if ( $? && $Conf{UserCmdCheckStatus} ) {
234     $stat{hostError} = "RestorePreUserCmd returned error status $?";
235     exit(RestoreCleanup($client));
236 }
237 $NeedPostCmd = 1;
238
239 if ( $Conf{XferMethod} eq "tar" ) {
240     #
241     # Use tar (eg: tar/ssh) as the transport program.
242     #
243     $xfer = BackupPC::Xfer::Tar->new($bpc);
244 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
245     #
246     # Use rsync as the transport program.
247     #
248     if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
249         my $errStr = BackupPC::Xfer::Rsync->errStr;
250         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
251         $stat{hostError} = $errStr;
252         exit(RestoreCleanup($client));
253     }
254 } elsif ( $Conf{XferMethod} eq "backuppcd" ) {
255     #
256     # Use backuppcd as the transport program.
257     #
258     if ( !defined($xfer = BackupPC::Xfer::BackupPCd->new($bpc)) ) {
259         my $errStr = BackupPC::Xfer::BackupPCd->errStr;
260         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
261         $stat{hostError} = $errStr;
262         exit(RestoreCleanup($client));
263     }
264 } else {
265     #
266     # Default is to use smbclient (smb) as the transport program.
267     #
268     $xfer = BackupPC::Xfer::Smb->new($bpc);
269 }
270 my $useTar = $xfer->useTar;
271
272 if ( $useTar ) {
273     #
274     # Create a socketpair to connect BackupPC_tarCreate to the transport
275     # program (smbclient, tar, etc).
276     # WH is the write handle for writing, provided to BackupPC_tarCreate
277     # and RH is the other end of the pipe for reading provided to the
278     # transport program.
279     #
280     if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
281         shutdown(RH, 1);    # no writing to this socket
282         shutdown(WH, 0);    # no reading from this socket
283         setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
284         setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
285     } else {
286         #
287         # Default to pipe() if socketpair() doesn't work.
288         #
289         pipe(RH, WH);
290     }
291 }
292
293 #
294 # Run the transport program, which reads from RH and extracts the data.
295 #
296 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
297 my $xferArgs = {
298     client       => $client,
299     host         => $host,
300     hostIP       => $hostIP,
301     type         => "restore",
302     shareName    => $RestoreReq{shareDest},
303     pipeRH       => *RH,
304     pipeWH       => *WH,
305     XferLOG      => $RestoreLOG,
306     XferMethod   => $Conf{XferMethod},
307     logLevel     => $Conf{XferLogLevel},
308     bkupSrcHost  => $RestoreReq{hostSrc},
309     bkupSrcShare => $RestoreReq{shareSrc},
310     bkupSrcNum   => $RestoreReq{num},
311     backups      => \@Backups,
312     pathHdrSrc   => $RestoreReq{pathHdrSrc},
313     pathHdrDest  => $RestoreReq{pathHdrDest},
314     fileList     => $RestoreReq{fileList},
315     pidHandler   => \&pidHandler,
316 };
317
318 $xfer->args($xferArgs);
319
320 if ( !defined($logMsg = $xfer->start()) ) {
321     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
322     $stat{hostError} = "xfer start failed: ", $xfer->errStr;
323     exit(RestoreCleanup($client));
324 }
325
326 if ( $useTar ) {
327     #
328     # Now do the restore by running BackupPC_tarCreate
329     #
330     # The parent must close the read handle since the transport program
331     # is using it.
332     #
333     close(RH);
334
335     #
336     # fork a child for BackupPC_tarCreate.  TAR is a file handle
337     # on which we (the parent) read the stderr from BackupPC_tarCreate.
338     #
339     my @tarPathOpts;
340     if ( defined($RestoreReq{pathHdrDest})
341                 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
342         @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
343                         "-p", $RestoreReq{pathHdrDest}
344                 );
345     }
346     my @tarArgs = (
347              "-h", $RestoreReq{hostSrc},
348              "-n", $RestoreReq{num},
349              "-s", $RestoreReq{shareSrc},
350              "-t",
351              @tarPathOpts,
352              @{$RestoreReq{fileList}},
353     );
354     my $runMsg = "Running: "
355                . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
356                . "\n";
357     $RestoreLOG->write(\$runMsg);
358     if ( !defined($tarPid = open(TAR, "-|")) ) {
359         close(WH);
360         # FIX: need to cleanup xfer
361         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
362         $stat{hostError} = "Can't fork to run tar";
363         exit(RestoreCleanup($client));
364     }
365     binmode(TAR);
366     if ( !$tarPid ) {
367         #
368         # This is the tarCreate child.  Clone STDERR to STDOUT,
369         # STDOUT to WH, and then exec BackupPC_tarCreate.
370         #
371         setpgrp 0,0;
372         close(STDERR);
373         open(STDERR, ">&STDOUT");
374         close(STDOUT);
375         open(STDOUT, ">&WH");
376         alarm(0);
377         exec("$BinDir/BackupPC_tarCreate", @tarArgs);
378         print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
379         # FIX: need to cleanup xfer
380         exit(0);
381     }
382     #
383     # The parent must close the write handle since BackupPC_tarCreate
384     # is using it.
385     #
386     close(WH);
387
388     @xferPid = $xfer->xferPid;
389
390     print(LOG $bpc->timeStamp, $logMsg, "\n");
391     print("started_restore\n");
392
393     pidHandler(@xferPid);
394
395     #
396     # Parse the output of the transfer program and BackupPC_tarCreate
397     # while they run.  Since we are reading from two or more children
398     # we use a select.
399     #
400     my($FDread, $tarOut, $mesg);
401     vec($FDread, fileno(TAR), 1) = 1;
402     $xfer->setSelectMask(\$FDread);
403
404     SCAN: while ( 1 ) {
405         my $ein = $FDread;
406         last if ( $FDread =~ /^\0*$/ );
407         alarm($Conf{ClientTimeout});
408         select(my $rout = $FDread, undef, $ein, undef);
409         if ( vec($rout, fileno(TAR), 1) ) {
410             if ( sysread(TAR, $mesg, 8192) <= 0 ) {
411                 vec($FDread, fileno(TAR), 1) = 0;
412                 if ( !close(TAR) ) {
413                     $tarCreateErrCnt  = 1;
414                     $tarCreateErr = "BackupPC_tarCreate failed";
415                 }
416             } else {
417                 $tarOut .= $mesg;
418             }
419         }
420         while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
421             $_ = $1;
422             $tarOut = $2;
423             $RestoreLOG->write(\"tarCreate: $_\n");
424             if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
425                 $tarCreateFileCnt = $1;
426                 $tarCreateByteCnt = $2;
427                 $tarCreateDirCnt  = $3;
428                 $tarCreateErrCnt  = $5;
429             }
430         }
431         last if ( !$xfer->readOutput(\$FDread, $rout) );
432         while ( my $str = $xfer->logMsgGet ) {
433             print(LOG $bpc->timeStamp, "xfer: $str\n");
434         }
435         if ( $xfer->getStats->{fileCnt} == 1 ) {
436             #
437             # Make sure it is still the machine we expect.  We do this while
438             # the transfer is running to avoid a potential race condition if
439             # the ip address was reassigned by dhcp just before we started
440             # the transfer.
441             #
442             if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
443                 $stat{hostError} = $errMsg;
444                 last SCAN;
445             }
446         }
447     }
448 } else {
449     #
450     # otherwise the xfer module does everything for us
451     #
452     print(LOG $bpc->timeStamp, $logMsg . "\n");
453     print("started_restore\n");
454     ($tarCreateFileCnt, $tarCreateByteCnt,
455         $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
456 }
457 alarm(0);
458
459 #
460 # Merge the xfer status (need to accumulate counts)
461 #
462 my $newStat = $xfer->getStats;
463 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
464     next if ( !defined($newStat->{$k}) );
465     if ( $k =~ /Cnt$/ ) {
466         $stat{$k} += $newStat->{$k};
467         delete($newStat->{$k});
468         next;
469     }
470     if ( !defined($stat{$k}) ) {
471         $stat{$k} = $newStat->{$k};
472         delete($newStat->{$k});
473         next;
474     }
475 }
476
477 exit(RestoreCleanup($client));
478
479 ###########################################################################
480 # Subroutines
481 ###########################################################################
482
483 sub CorrectHostCheck
484 {
485     my($hostIP, $host) = @_;
486     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
487                 || $Conf{NmbLookupCmd} eq "" );
488     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
489     return "host $host has mismatching netbios name $netBiosHost"
490             if ( $netBiosHost ne $host );
491     return;
492 }
493
494 sub catch_signal
495 {
496     my $signame = shift;
497
498     #
499     # Children quit quietly on ALRM
500     #
501     exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
502
503     #
504     # Ignore signals in children
505     #
506     return if ( $Pid != $$ );
507
508     #
509     # Note: needs to be tested for each kind of XferMethod
510     #
511     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
512     $SIG{$signame} = 'IGNORE';
513     $RestoreLOG->write(\"exiting after signal $signame\n");
514     $stat{xferOK} = 0;
515     if ( $signame eq "INT" ) {
516         $stat{hostError} = "aborted by user (signal=$signame)";
517     } else {
518         $stat{hostError} = "aborted by signal=$signame";
519     }
520     exit(RestoreCleanup($client));
521 }
522
523 #
524 # Cleanup and update the restore status
525 #
526 sub RestoreCleanup
527 {
528     my($client) = @_;
529
530     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
531                         || $tarCreateErr );
532
533     if ( !$stat{xferOK} ) {
534         #
535         # kill off the tranfer program, first nicely then forcefully
536         #
537         if ( @xferPid ) {
538             kill($bpc->sigName2num("INT"), @xferPid);
539             sleep(1);
540             kill($bpc->sigName2num("KILL"), @xferPid);
541         }
542         #
543         # kill off the tar process, first nicely then forcefully
544         #
545         if ( $tarPid > 0 ) {
546             kill($bpc->sigName2num("INT"), $tarPid);
547             sleep(1);
548             kill($bpc->sigName2num("KILL"), $tarPid);
549         }
550     }
551
552     my $lastNum  = -1;
553     my @Restores;
554
555     #
556     # Do one last check to make sure it is still the machine we expect.
557     #
558     if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
559         $stat{hostError} = $errMsg;
560         $stat{xferOK} = 0;
561     }
562     @Restores = $bpc->RestoreInfoRead($client);
563     for ( my $i = 0 ; $i < @Restores ; $i++ ) {
564         $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
565     }
566     $lastNum++;
567
568     #
569     # Run an optional post-restore command
570     #
571     if ( $NeedPostCmd ) {
572         UserCommandRun("RestorePostUserCmd");
573         if ( $? && $Conf{UserCmdCheckStatus} ) {
574             $stat{hostError} = "RestorePostUserCmd returned error status $?";
575             $stat{xferOK} = 0;
576         }
577     }
578
579     rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
580     rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
581     my $endTime = time();
582
583     #
584     # If the restore failed, clean up
585     #
586     if ( !$stat{xferOK} ) {
587         #
588         # wait a short while and see if the system is still alive
589         #
590         $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
591         $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
592         sleep(2);
593         if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
594             $stat{hostAbort} = 1;
595         }
596         if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
597             $stat{hostError} = "lost network connection during restore";
598         }
599         $RestoreLOG->write(\"restore failed: $stat{hostError}\n")
600                                             if ( defined($RestoreLOG) );
601     }
602
603     $RestoreLOG->close() if ( defined($RestoreLOG) );
604
605     #
606     # Add the new restore information to the restore file
607     #
608     @Restores = $bpc->RestoreInfoRead($client);
609     my $i = @Restores;
610     $Restores[$i]{num}           = $lastNum;
611     $Restores[$i]{startTime}     = $startTime;
612     $Restores[$i]{endTime}       = $endTime;
613     $Restores[$i]{result}        = $stat{xferOK} ? "ok" : "failed";
614     $Restores[$i]{errorMsg}      = $stat{hostError};
615     $Restores[$i]{nFiles}        = $tarCreateFileCnt;
616     $Restores[$i]{size}          = $tarCreateByteCnt;
617     $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
618     $Restores[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
619
620     while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
621         my $num = $Restores[0]{num};
622         unlink("$Dir/RestoreLOG.$num.z");
623         unlink("$Dir/RestoreLOG.$num");
624         unlink("$Dir/RestoreInfo.$num");
625         shift(@Restores);
626     }
627     $bpc->RestoreInfoWrite($client, @Restores);
628
629     if ( !$stat{xferOK} ) {
630         print(LOG $bpc->timeStamp, "restore failed ($stat{hostError})\n");
631         print("restore failed: $stat{hostError}\n");
632         return 1;
633     } else {
634         $stat{xferErrCnt} ||= 0;
635         print(LOG $bpc->timeStamp, "restore $lastNum complete"
636                 . " ($tarCreateFileCnt files, $tarCreateByteCnt bytes,"
637                 . " $tarCreateDirCnt dirs, $stat{xferErrCnt} xferErrs)\n");
638         print("restore complete\n");
639         return;
640     }
641 }
642
643 #
644 # The Xfer method might tell us from time to time about processes
645 # it forks.  We tell BackupPC about this (for status displays) and
646 # keep track of the pids in case we cancel the backup
647 #
648 sub pidHandler
649 {
650     @xferPid = @_;
651     @xferPid = grep(/./, @xferPid);
652     return if ( !@xferPid && $tarPid < 0 );
653     my @pids = @xferPid;
654     push(@pids, $tarPid) if ( $tarPid > 0 );
655     my $str = join(",", @pids);
656     $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
657     print("xferPids $str\n");
658 }
659
660 #
661 # Run an optional pre- or post-dump command
662 #
663 sub UserCommandRun
664 {
665     my($cmdType) = @_;
666
667     return if ( !defined($Conf{$cmdType}) );
668     my $vars = {
669         xfer         => $xfer,
670         client       => $client,
671         host         => $host,
672         hostIP       => $hostIP,
673         share        => $RestoreReq{shareDest},
674         XferMethod   => $Conf{XferMethod},
675         sshPath      => $Conf{SshPath},
676         LOG          => *LOG,
677         user         => $Hosts->{$client}{user},
678         moreUsers    => $Hosts->{$client}{moreUsers},
679         XferLOG      => $RestoreLOG,
680         stat         => \%stat,
681         xferOK       => $stat{xferOK} || 0,
682         hostError    => $stat{hostError},
683         type         => "restore",
684         bkupSrcHost  => $RestoreReq{hostSrc},
685         bkupSrcShare => $RestoreReq{shareSrc},
686         bkupSrcNum   => $RestoreReq{num},
687         backups      => \@Backups,
688         pathHdrSrc   => $RestoreReq{pathHdrSrc},
689         pathHdrDest  => $RestoreReq{pathHdrDest},
690         fileList     => $RestoreReq{fileList},
691         cmdType      => $cmdType,
692     };
693     my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
694     $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
695     #
696     # Run the user's command, dumping the stdout/stderr into the
697     # Xfer log file.  Also supply the optional $vars and %Conf in
698     # case the command is really perl code instead of a shell
699     # command.
700     #
701     $bpc->cmdSystemOrEval($cmd,
702             sub {
703                 $RestoreLOG->write(\$_[0]);
704             },
705             $vars, \%Conf);
706 }