File: BackupPC_restore

package info (click to toggle)
backuppc 4.4.0-11
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,752 kB
  • sloc: perl: 37,523; sh: 607; javascript: 176; makefile: 38; ansic: 6
file content (720 lines) | stat: -rwxr-xr-x 21,906 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
#!/usr/bin/perl
#============================================================= -*-perl-*-
#
# BackupPC_restore: Restore files to a client.
#
# DESCRIPTION
#
#   Usage: BackupPC_restore <hostIP> <client> <reqFileName>
#
# AUTHOR
#   Craig Barratt  <cbarratt@users.sourceforge.net>
#
# COPYRIGHT
#   Copyright (C) 2001-2020  Craig Barratt
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#========================================================================
#
# Version 4.4.0, released 20 Jun 2020.
#
# See http://backuppc.sourceforge.net.
#
#========================================================================

use strict;
no utf8;

use lib "__INSTALLDIR__/lib";
use BackupPC::Lib;
use BackupPC::XS;
use BackupPC::Xfer;
use Socket;

use File::Path;
use Getopt::Std;

use vars qw( %RestoreReq );

###########################################################################
# Initialize
###########################################################################

die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );

my $TopDir = $bpc->TopDir();
my $BinDir = $bpc->BinDir();
my %Conf   = $bpc->Conf();
my $NeedPostCmd;

my($hostIP, $host, $client, $reqFileName, %stat);

$bpc->ChildInit();

my %opts;
if ( !getopts("pvm", \%opts) || @ARGV != 3 ) {
    print("usage: $0 [-p] [-v] [-m] <hostIP> <client> <reqFileName>\n");
    exit(1);
}

$hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
$client = $1 if ( $ARGV[1] =~ /(.+)/ );
if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
    print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
    exit(1);
}
$reqFileName = $1;
if (   !$opts{m}
    && !defined($bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort}))
    && (my $status = $bpc->ServerMesg("hostMutex $client 1 BackupPC_restore")) =~ /fail/ ) {
    print(STDERR "$0: $status (use -m option to force running)\n");
    exit(1);
}

$bpc->verbose(1) if ( $opts{v} );

my $startTime = time();

my $Hosts = $bpc->HostInfoRead($client);

my $Dir     = "$TopDir/pc/$client";
my @xferPid = ();
my $tarPid  = -1;

#
# Catch various signals
#
$SIG{INT}  = \&catch_signal;
$SIG{ALRM} = \&catch_signal;
$SIG{TERM} = \&catch_signal;
$SIG{PIPE} = \&catch_signal;
$SIG{STOP} = \&catch_signal;
$SIG{TSTP} = \&catch_signal;
$SIG{TTIN} = \&catch_signal;
my $Pid = $$;

mkpath($Dir, 0, 0777) if ( !-d $Dir );
if ( !-f "$Dir/LOCK" ) {
    open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
}

my($LogFd, $LogPath) = $bpc->openPCLogFile($client);
if ( !defined($LogFd) ) {
    print("Unable to open/create $LogPath; exiting\n");
    exit(1);
}
select($LogFd); $| = 1; select(STDOUT);

#
# Read the request file
#
if ( !(my $ret = do "$Dir/$reqFileName") ) {
    my $err;
    if ( $@ ) {
        $err = "couldn't parse $Dir/$reqFileName: $@";
    } elsif ( !defined($ret) ) {
        $err = "couldn't do $Dir/$reqFileName: $!";
    } else {
        $err = "couldn't run $Dir/$reqFileName";
    }
    $stat{hostError} = $err;
    exit(RestoreCleanup($client));
}

#
# Re-read config file, so we can include the PC-specific config
#
if ( defined(my $error = $bpc->ConfigRead($client)) ) {
    $stat{hostError} = "Can't read PC's config file: $error";
    exit(RestoreCleanup($client));
}
%Conf = $bpc->Conf();

#
# Make sure we eventually timeout if there is no activity from
# the data transport program.
#
alarm($Conf{ClientTimeout});

#
# Build the list of hosts to check
#
my @hostsToCheck = ();
my @validHosts   = ();
if ( ref($Conf{ClientNameAlias}) eq 'ARRAY' ) {
    push(@hostsToCheck, @{$Conf{ClientNameAlias}});
} elsif ( $Conf{ClientNameAlias} ne "" ) {
    push(@hostsToCheck, $Conf{ClientNameAlias});
} else {
    push(@hostsToCheck, $client);
}
if ( $hostIP !~ /^\d+\.\d+\.\d+\.\d+$/ ) {
    foreach my $hostToCheck ( @hostsToCheck ) {
        $hostIP = HostLookupCheck($hostToCheck);
        push(@validHosts, [$hostToCheck, $hostIP]) if ( defined($hostIP) );
    }
} else {
    push(@validHosts, [$client, $hostIP]);
}

#
# Find the first entry in @validHosts that we can ping
#
foreach my $h ( @validHosts ) {
    ($host, $hostIP) = @$h;
    my $delay = $bpc->CheckHostAlive($hostIP);
    if ( $delay < 0 ) {
        print($LogFd $bpc->timeStamp, "no ping response from $hostIP ($host)\n");
        $hostIP = undef;
        next;
    } elsif ( $delay > $Conf{PingMaxMsec} ) {
        printf($LogFd "%sping too slow on $hostIP ($host) %.4gmsec\n", $bpc->timeStamp, $delay);
        $hostIP = undef;
        next;
    }
    last;
}
$host = $hostIP if ( !defined($host) );

if ( !defined($hostIP) ) {
    $stat{hostError} = "can't ping $host (client = $client)";
    print("can't ping $host (client = $client); exiting\n");
    exit(RestoreCleanup($client));
}

#
# Make sure it is really the machine we expect
#
if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
    $stat{hostError} = $errMsg;
    exit(RestoreCleanup($client));
}

my $fileExt    = $Conf{CompressLevel} > 0 ? ".z" : "";
my $RestoreLOG = BackupPC::XS::FileZIO::open("$Dir/RestoreLOG$fileExt", 1, $Conf{CompressLevel});
if ( !defined($RestoreLOG) ) {
    $stat{hostError} = "unable to open/create $Dir/RestoreLOG.$fileExt";
    exit(RestoreCleanup($client));
}

my $xferCreateFileCnt = 0;
my $xferCreateByteCnt = 0;
my $xferCreateDirCnt  = 0;
my $xferCreateErrCnt  = 1;    # assume not ok until we learn otherwise
my $xferCreateErr;
my($logMsg, $xfer);

$RestoreLOG->writeTeeStderr(1) if ( $opts{v} );

$stat{xferOK}    = $stat{hostAbort}      = undef;
$stat{hostError} = $stat{lastOutputLine} = undef;
local(*RH, *WH);

#
# Run an optional pre-restore command
#
UserCommandRun("RestorePreUserCmd");
if ( $? && $Conf{UserCmdCheckStatus} ) {
    $stat{hostError} = "RestorePreUserCmd returned error status $?";
    exit(RestoreCleanup($client));
}
$NeedPostCmd = 1;

print("__bpc_progress_state__ restore\n") if ( !$opts{p} );

$xfer = BackupPC::Xfer::create($Conf{XferMethod}, $bpc);
if ( !defined($xfer) ) {
    my $errStr = BackupPC::Xfer::errStr();
    UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
    $stat{hostError} = $errStr;
    exit(RestoreCleanup($client));
}

my $useTar = $xfer->useTar;

if ( $useTar ) {
    #
    # Create a socketpair to connect BackupPC_tarCreate to the transport
    # program (smbclient, tar, etc).
    # WH is the write handle for writing, provided to BackupPC_tarCreate
    # and RH is the other end of the pipe for reading provided to the
    # transport program.
    #
    if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
        shutdown(RH, 1);    # no writing to this socket
        shutdown(WH, 0);    # no reading from this socket
        setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
        setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
    } else {
        #
        # Default to pipe() if socketpair() doesn't work.
        #
        pipe(RH, WH);
    }
}

#
# Run the transport program, which reads from RH and extracts the data.
#
my @Backups  = $bpc->BackupInfoRead($RestoreReq{hostSrc});
my $xferArgs = {
    client          => $client,
    host            => $host,
    hostIP          => $hostIP,
    type            => "restore",
    shareName       => $RestoreReq{shareDest},
    pipeRH          => *RH,
    pipeWH          => *WH,
    XferLOG         => $RestoreLOG,
    XferMethod      => $Conf{XferMethod},
    logLevel        => $Conf{XferLogLevel},
    bkupSrcHost     => $RestoreReq{hostSrc},
    bkupSrcShare    => $RestoreReq{shareSrc},
    bkupSrcNum      => $RestoreReq{num},
    backups         => \@Backups,
    pathHdrSrc      => $RestoreReq{pathHdrSrc},
    pathHdrDest     => $RestoreReq{pathHdrDest},
    fileList        => $RestoreReq{fileList},
    pidHandler      => \&pidHandler,
    noProgressPrint => $opts{p},
};

$xfer->args($xferArgs);

if ( !defined($logMsg = $xfer->start()) ) {
    UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
    $stat{hostError} = "xfer start failed: ", $xfer->errStr;
    exit(RestoreCleanup($client));
}

if ( $useTar ) {
    #
    # Now do the restore by running BackupPC_tarCreate
    #
    # The parent must close the read handle since the transport program
    # is using it.
    #
    close(RH);

    #
    # fork a child for BackupPC_tarCreate.  TAR is a file handle
    # on which we (the parent) read the stderr from BackupPC_tarCreate.
    #
    my @tarPathOpts;
    if ( defined($RestoreReq{pathHdrDest})
        && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
        @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc}, "-p", $RestoreReq{pathHdrDest});
    }
    my @tarArgs = (
        "-h", $RestoreReq{hostSrc}, "-n", $RestoreReq{num}, "-s", $RestoreReq{shareSrc}, "-t",
        @tarPathOpts, @{$RestoreReq{fileList}},
    );
    my $runMsg = "Running: " . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs) . "\n";
    $RestoreLOG->write(\$runMsg);
    if ( !defined($tarPid = open(TAR, "-|")) ) {
        close(WH);

        # FIX: need to cleanup xfer
        UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
        $stat{hostError} = "Can't fork to run tar";
        exit(RestoreCleanup($client));
    }
    binmode(TAR);
    if ( !$tarPid ) {
        #
        # This is the tarCreate child.  Clone STDERR to STDOUT,
        # STDOUT to WH, and then exec BackupPC_tarCreate.
        #
        setpgrp 0, 0;
        close(STDERR);
        open(STDERR, ">&STDOUT");
        close(STDOUT);
        open(STDOUT, ">&WH");
        alarm(0);
        exec("$BinDir/BackupPC_tarCreate", @tarArgs);
        print($LogFd $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
        print(STDERR "$0: can't exec $BinDir/BackupPC_tarCreate\n") if ( $opts{v} );

        # FIX: need to cleanup xfer
        exit(0);
    }
    #
    # The parent must close the write handle since BackupPC_tarCreate
    # is using it.
    #
    close(WH);

    @xferPid = $xfer->xferPid;

    print($LogFd $bpc->timeStamp, $logMsg, "\n");
    print(STDERR $logMsg, "\n") if ( $opts{v} );
    print("started_restore\n");

    pidHandler(@xferPid);

    #
    # Parse the output of the transfer program and BackupPC_tarCreate
    # while they run.  Since we are reading from two or more children
    # we use a select.
    #
    my($FDread, $tarOut, $mesg);
    vec($FDread, fileno(TAR), 1) = 1;
    $xfer->setSelectMask(\$FDread);

  SCAN: while ( 1 ) {
        my $ein = $FDread;
        last if ( $FDread =~ /^\0*$/ );
        alarm($Conf{ClientTimeout});
        select(my $rout = $FDread, undef, $ein, undef);
        if ( vec($rout, fileno(TAR), 1) ) {
            if ( sysread(TAR, $mesg, 8192) <= 0 ) {
                vec($FDread, fileno(TAR), 1) = 0;
                if ( !close(TAR) ) {
                    $xferCreateErrCnt = 1;
                    $xferCreateErr    = "BackupPC_tarCreate failed";
                }
            } else {
                $tarOut .= $mesg;
            }
        }
        while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
            $_      = $1;
            $tarOut = $2;
            $RestoreLOG->write(\"tarCreate: $_\n");
            if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
                $xferCreateFileCnt = $1;
                $xferCreateByteCnt = $2;
                $xferCreateDirCnt  = $3;
                $xferCreateErrCnt  = $5;
            }
        }
        last if ( !$xfer->readOutput(\$FDread, $rout) );
        while ( my $str = $xfer->logMsgGet ) {
            print($LogFd $bpc->timeStamp, "xfer: $str\n");
            print(STDERR "xfer: $str\n") if ( $opts{v} );
        }
        if ( $xfer->getStats->{fileCnt} == 1 ) {
            #
            # Make sure it is still the machine we expect.  We do this while
            # the transfer is running to avoid a potential race condition if
            # the ip address was reassigned by dhcp just before we started
            # the transfer.
            #
            if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
                $stat{hostError} = $errMsg;
                last SCAN;
            }
        }
    }
} else {
    #
    # otherwise the xfer module does everything for us
    #
    print($LogFd $bpc->timeStamp, $logMsg . "\n");
    print(STDERR $logMsg,         "\n") if ( $opts{v} );
    print("started_restore\n");
    ($xferCreateFileCnt, $xferCreateByteCnt, $xferCreateErrCnt, $xferCreateErr) = $xfer->run();
}
alarm(0);

#
# Merge the xfer status (need to accumulate counts)
#
my $newStat = $xfer->getStats;
foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
    next if ( !defined($newStat->{$k}) );
    if ( $k =~ /Cnt$/ ) {
        $stat{$k} += $newStat->{$k};
        delete($newStat->{$k});
        next;
    }
    if ( !defined($stat{$k}) ) {
        $stat{$k} = $newStat->{$k};
        delete($newStat->{$k});
        next;
    }
}

exit(RestoreCleanup($client));

###########################################################################
# Subroutines
###########################################################################

sub CorrectHostCheck
{
    my($hostIP, $host) = @_;
    return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} || $Conf{NmbLookupCmd} eq "" );
    if ( ref($Conf{ClientNameAlias}) eq 'ARRAY' ) {
        return if ( grep /^$hostIP$/, @{$Conf{ClientNameAlias}} );
    }
    my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
    return "host $host has mismatching netbios name $netBiosHost"
      if ( lc($netBiosHost) ne lc(substr($host, 0, 15)) );
    return;
}

#
# Returns $host if $bpc->getHostAddrInfo() knows about it.
# Otherwise tries to find the hostIP via NetBios, and returns
# the hostIP if successful.
#
# Returns undef if both $bpc->getHostAddrInfo() and NetBios fail
#
sub HostLookupCheck
{
    my($host) = @_;
    my $hostIP;

    return $host if ( defined($bpc->getHostAddrInfo($host)) );
    #
    # Ok, NS doesn't know about it.  Maybe it is a NetBios name
    # instead.
    #
    print("Name server doesn't know about $host; trying NetBios\n") if ( $opts{v} );
    if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
        print($LogFd $bpc->timeStamp, "Can't find host $host via NS and netbios\n");
        print("host $host not found\n");
    }
    return $hostIP;
}

sub catch_signal
{
    my $signame = shift;

    #
    # Children quit quietly on ALRM
    #
    exit(1) if ( $Pid != $$ && $signame eq "ALRM" );

    #
    # Ignore signals in children
    #
    return if ( $Pid != $$ );

    #
    # Note: needs to be tested for each kind of XferMethod
    #
    print($LogFd $bpc->timeStamp, "cleaning up after signal $signame\n");
    print(STDERR "$0: cleaning up after signal $signame\n") if ( $opts{v} );
    $SIG{$signame} = 'IGNORE';
    $RestoreLOG->write(\"exiting after signal $signame\n");
    $stat{xferOK} = 0;
    if ( $signame eq "INT" ) {
        $stat{hostError} = "aborted by user (signal=$signame)";
    } else {
        $stat{hostError} = "aborted by signal=$signame";
    }
    exit(RestoreCleanup($client));
}

#
# Cleanup and update the restore status
#
sub RestoreCleanup
{
    my($client) = @_;

    $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} || $xferCreateErr );

    if ( !$stat{xferOK} ) {
        #
        # kill off the transfer program, first nicely then forcefully
        #
        if ( @xferPid ) {
            kill($bpc->sigName2num("INT"), @xferPid);
            sleep(1);
            kill($bpc->sigName2num("KILL"), @xferPid);
        }
        #
        # kill off the tar process, first nicely then forcefully
        #
        if ( $tarPid > 0 ) {
            kill($bpc->sigName2num("INT"), $tarPid);
            sleep(1);
            kill($bpc->sigName2num("KILL"), $tarPid);
        }
    }

    my $lastNum = -1;
    my @Restores;

    #
    # Do one last check to make sure it is still the machine we expect.
    #
    if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
        $stat{hostError} = $errMsg;
        $stat{xferOK}    = 0;
    }
    @Restores = $bpc->RestoreInfoRead($client);
    for ( my $i = 0 ; $i < @Restores ; $i++ ) {
        $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
    }
    $lastNum++;

    #
    # Run an optional post-restore command
    #
    if ( $NeedPostCmd ) {
        UserCommandRun("RestorePostUserCmd");
        if ( $? && $Conf{UserCmdCheckStatus} ) {
            $stat{hostError} = "RestorePostUserCmd returned error status $?";
            $stat{xferOK}    = 0;
        }
    }

    rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
    rename("$Dir/$reqFileName",       "$Dir/RestoreInfo.$lastNum");
    my $endTime = time();

    #
    # If the restore failed, clean up
    #
    if ( !$stat{xferOK} ) {
        #
        # wait a short while and see if the system is still alive
        #
        $stat{hostError} ||= $xferCreateErr if ( $xferCreateErr ne "" );
        $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
        sleep(2);
        if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
            $stat{hostAbort} = 1;
        }
        if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
            $stat{hostError} = "lost network connection during restore";
        }
        $RestoreLOG->write(\"restore failed: $stat{hostError}\n")
          if ( defined($RestoreLOG) );
    }

    $RestoreLOG->close() if ( defined($RestoreLOG) );

    #
    # Add the new restore information to the restore file
    #
    @Restores = $bpc->RestoreInfoRead($client);
    my $i = @Restores;
    $Restores[$i]{num}           = $lastNum;
    $Restores[$i]{startTime}     = $startTime;
    $Restores[$i]{endTime}       = $endTime;
    $Restores[$i]{result}        = $stat{xferOK} ? "ok" : "failed";
    $Restores[$i]{errorMsg}      = $stat{hostError};
    $Restores[$i]{nFiles}        = $xferCreateFileCnt;
    $Restores[$i]{size}          = $xferCreateByteCnt;
    $Restores[$i]{tarCreateErrs} = $xferCreateErrCnt;
    $Restores[$i]{xferErrs}      = $stat{xferErrCnt} || 0;

    while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
        my $num = $Restores[0]{num};
        unlink("$Dir/RestoreLOG.$num.z");
        unlink("$Dir/RestoreLOG.$num");
        unlink("$Dir/RestoreInfo.$num");
        shift(@Restores);
    }
    $bpc->RestoreInfoWrite($client, @Restores);

    if ( !$stat{xferOK} ) {
        print($LogFd $bpc->timeStamp, "restore failed ($stat{hostError})\n");
        print("restore failed: $stat{hostError}\n");
        return 1;
    } else {
        $stat{xferErrCnt} ||= 0;
        print($LogFd $bpc->timeStamp,
                "restore $lastNum complete"
              . " ($xferCreateFileCnt files, $xferCreateByteCnt bytes,"
              . " $xferCreateDirCnt dirs, $stat{xferErrCnt} xferErrs)\n"
        );
        print("restore complete\n");
        return;
    }
}

#
# The Xfer method might tell us from time to time about processes
# it forks.  We tell BackupPC about this (for status displays) and
# keep track of the pids in case we cancel the backup
#
sub pidHandler
{
    @xferPid = @_;
    @xferPid = grep(/./, @xferPid);
    return if ( !@xferPid && $tarPid < 0 );
    my @pids = @xferPid;
    push(@pids, $tarPid) if ( $tarPid > 0 );
    my $str = join(",", @pids);
    $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
    print("xferPids $str\n");
}

#
# Run an optional pre- or post-dump command
#
sub UserCommandRun
{
    my($cmdType) = @_;

    return if ( !defined($Conf{$cmdType}) );
    my $vars = {
        xfer         => $xfer,
        client       => $client,
        host         => $host,
        hostIP       => $hostIP,
        share        => $RestoreReq{shareDest},
        XferMethod   => $Conf{XferMethod},
        sshPath      => $Conf{SshPath},
        LOG          => $LogFd,
        user         => $Hosts->{$client}{user},
        moreUsers    => $Hosts->{$client}{moreUsers},
        XferLOG      => $RestoreLOG,
        stat         => \%stat,
        xferOK       => $stat{xferOK} || 0,
        hostError    => $stat{hostError},
        type         => "restore",
        bkupSrcHost  => $RestoreReq{hostSrc},
        bkupSrcShare => $RestoreReq{shareSrc},
        bkupSrcNum   => $RestoreReq{num},
        backups      => \@Backups,
        pathHdrSrc   => $RestoreReq{pathHdrSrc},
        pathHdrDest  => $RestoreReq{pathHdrDest},
        fileList     => $RestoreReq{fileList},
        cmdType      => $cmdType,
    };
    if ( $cmdType eq "RestorePostUserCmd" ) {
        print("__bpc_progress_state__ post-cmd\n") if ( !$opts{p} );
    } else {
        print("__bpc_progress_state__ pre-cmd\n") if ( !$opts{p} );
    }
    my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
    $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
    #
    # Run the user's command, dumping the stdout/stderr into the
    # Xfer log file.  Also supply the optional $vars and %Conf in
    # case the command is really perl code instead of a shell
    # command.
    #
    $bpc->cmdSystemOrEval(
        $cmd,
        sub {
            if ( $RestoreLOG && length($_[0]) ) {
                $RestoreLOG->write(\$_[0]);
            } elsif ( $LogFd && length($_[0]) ) {
                print($LogFd $bpc->timeStamp, "Output from $cmdType: ", $_[0]);
            }
        },
        $vars,
        \%Conf
    );
}