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