Imported Upstream version 3.3.0
[debian/amanda] / server-src / amidxtaped.pl
1 #! @PERL@
2 # Copyright (c) 2010 Zmanda, Inc.  All Rights Reserved.
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License version 2 as published
6 # by the Free Software Foundation.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
19
20 use lib '@amperldir@';
21 use strict;
22 use warnings;
23
24 ##
25 # Interactivity class
26
27 package main::Interactivity;
28 use base 'Amanda::Interactivity';
29 use Amanda::Util qw( weaken_ref );
30 use Amanda::MainLoop;
31 use Amanda::Feature;
32 use Amanda::Debug qw( debug );
33 use Amanda::Config qw( :getconf );
34 use Amanda::Recovery::Scan qw( $DEFAULT_CHANGER );
35
36 sub new {
37     my $class = shift;
38     my %params = @_;
39
40     my $self = {
41         clientservice => $params{'clientservice'},
42     };
43
44     # (weak ref here to eliminate reference loop)
45     weaken_ref($self->{'clientservice'});
46
47     return bless ($self, $class);
48 }
49
50 sub abort() {
51     my $self = shift;
52
53     debug("ignoring spurious Amanda::Recovery::Scan abort call");
54 }
55
56 sub user_request {
57     my $self = shift;
58     my %params = @_;
59     my $buffer = "";
60
61     my $steps = define_steps
62         cb_ref => \$params{'request_cb'};
63
64     step send_message => sub {
65         if ($params{'err'}) {
66             $self->{'clientservice'}->sendmessage("$params{err}");
67         }
68
69         $steps->{'check_fe_feedme'}->();
70     };
71
72     step check_fe_feedme => sub {
73         # note that fe_amrecover_FEEDME implies fe_amrecover_splits
74         if (!$self->{'clientservice'}->{'their_features'}->has(
75                                     $Amanda::Feature::fe_amrecover_FEEDME)) {
76             return $params{'request_cb'}->("remote cannot prompt for volumes", undef);
77         }
78         $steps->{'send_feedme'}->();
79     };
80
81     step send_feedme => sub {
82         $self->{'clientservice'}->sendctlline("FEEDME $params{label}\r\n", $steps->{'read_response'});
83     };
84
85     step read_response => sub {
86         my ($err, $written) = @_;
87         return $params{'request_cb'}->($err, undef) if $err;
88
89         $self->{'clientservice'}->getline_async(
90                 $self->{'clientservice'}->{'ctl_stream'}, $steps->{'got_response'});
91     };
92
93     step got_response => sub {
94         my ($err, $line) = @_;
95         return $params{'request_cb'}->($err, undef) if $err;
96
97         if ($line eq "OK\r\n") {
98             return $params{'request_cb'}->(undef, undef); # carry on as you were
99         } elsif ($line =~ /^TAPE (.*)\r\n$/) {
100             my $tape = $1;
101             if ($tape eq getconf($CNF_AMRECOVER_CHANGER)) {
102                 $tape = $Amanda::Recovery::Scan::DEFAULT_CHANGER;
103             }
104             return $params{'request_cb'}->(undef, $tape); # use this device
105         } else {
106             return $params{'request_cb'}->("got invalid response from remote", undef);
107         }
108     };
109 };
110
111 ##
112 # ClientService class
113
114 package main::ClientService;
115 use base 'Amanda::ClientService';
116
117 use Sys::Hostname;
118
119 use Amanda::Debug qw( debug info warning );
120 use Amanda::MainLoop qw( :GIOCondition );
121 use Amanda::Util qw( :constants );
122 use Amanda::Feature;
123 use Amanda::Config qw( :init :getconf );
124 use Amanda::Changer;
125 use Amanda::Recovery::Scan;
126 use Amanda::Xfer qw( :constants );
127 use Amanda::Cmdline;
128 use Amanda::Recovery::Clerk;
129 use Amanda::Recovery::Planner;
130 use Amanda::Recovery::Scan;
131 use Amanda::DB::Catalog;
132 use Amanda::Disklist;
133 use Amanda::Logfile qw( match_disk match_host );
134
135 # Note that this class performs its control IO synchronously.  This is adequate
136 # for this service, as it never receives unsolicited input from the remote
137 # system.
138
139 sub run {
140     my $self = shift;
141
142     $self->{'my_features'} = Amanda::Feature::Set->mine();
143     $self->{'their_features'} = Amanda::Feature::Set->old();
144     $self->{'all_filter'} = {};
145
146     $self->setup_streams();
147 }
148
149 sub setup_streams {
150     my $self = shift;
151
152     # get started checking security for inetd or processing the REQ/REP
153     # for amandad
154     if ($self->from_inetd()) {
155         if (!$self->check_inetd_security('main')) {
156             $main::exit_status = 1;
157             return $self->quit();
158         }
159         $self->{'ctl_stream'} = 'main';
160         $self->{'data_stream'} = undef; # no data stream yet
161     } else {
162         my $req = $self->get_req();
163
164         # make some sanity checks
165         my $errors = [];
166         if (defined $req->{'options'}{'auth'} and defined $self->amandad_auth()
167                 and $req->{'options'}{'auth'} ne $self->amandad_auth()) {
168             my $reqauth = $req->{'options'}{'auth'};
169             my $amauth = $self->amandad_auth();
170             push @$errors, "recover program requested auth '$reqauth', " .
171                            "but amandad is using auth '$amauth'";
172             $main::exit_status = 1;
173         }
174
175         # and pull out the features, if given
176         if (defined($req->{'features'})) {
177             $self->{'their_features'} = $req->{'features'};
178         }
179
180         $self->send_rep(['CTL' => 'rw', 'DATA' => 'w'], $errors);
181         return $self->quit() if (@$errors);
182
183         $self->{'ctl_stream'} = 'CTL';
184         $self->{'data_stream'} = 'DATA';
185     }
186
187     $self->read_command();
188 }
189
190 sub read_command {
191     my $self = shift;
192     my $ctl_stream = $self->{'ctl_stream'};
193     my $command = $self->{'command'} = {};
194
195     my @known_commands = qw(
196         HOST DISK DATESTAMP LABEL DEVICE FSF HEADER
197         FEATURES CONFIG );
198     while (1) {
199         $_ = $self->getline($ctl_stream);
200         $_ =~ s/\r?\n$//g;
201
202         last if /^END$/;
203         last if /^[0-9]+$/;
204
205         if (/^([A-Z]+)(=(.*))?$/) {
206             my ($cmd, $val) = ($1, $3);
207             if (!grep { $_ eq $cmd } @known_commands) {
208                 $self->sendmessage("invalid command '$cmd'");
209                 return $self->quit();
210             }
211             if (exists $command->{$cmd}) {
212                 warning("got duplicate command key '$cmd' from remote");
213             } else {
214                 $command->{$cmd} = $val || 1;
215             }
216         }
217
218         # features are handled specially.  This is pretty weird!
219         if (/^FEATURES=/) {
220             my $featreply;
221             my $featurestr = $self->{'my_features'}->as_string();
222             if ($self->from_amandad) {
223                 $featreply = "FEATURES=$featurestr\r\n";
224             } else {
225                 $featreply = $featurestr;
226             }
227
228             $self->senddata($ctl_stream, $featreply);
229         }
230     }
231
232     # process some info from the command
233     if ($command->{'FEATURES'}) {
234         $self->{'their_features'} = Amanda::Feature::Set->from_string($command->{'FEATURES'});
235     }
236
237     # load the configuration
238     if (!$command->{'CONFIG'}) {
239         die "no CONFIG line given";
240     }
241     config_init($CONFIG_INIT_EXPLICIT_NAME, $command->{'CONFIG'});
242     my ($cfgerr_level, @cfgerr_errors) = config_errors();
243     if ($cfgerr_level >= $CFGERR_ERRORS) {
244         die "configuration errors; aborting connection";
245     }
246     Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER_PREFERRED);
247
248     # and the disklist
249     my $diskfile = Amanda::Config::config_dir_relative(getconf($CNF_DISKFILE));
250     $cfgerr_level = Amanda::Disklist::read_disklist('filename' => $diskfile);
251     if ($cfgerr_level >= $CFGERR_ERRORS) {
252         die "Errors processing disklist";
253     }
254
255     $self->setup_data_stream();
256 }
257
258 sub setup_data_stream {
259     my $self = shift;
260
261     # if we're using amandad, then this is ready to roll - it's only inetd mode
262     # that we need to fix
263     if ($self->from_inetd()) {
264         if ($self->{'their_features'}->has($Amanda::Feature::fe_recover_splits)) {
265             # remote side is expecting CONNECT
266             my $port = $self->connection_listen('DATA', 0);
267             $self->senddata($self->{'ctl_stream'}, "CONNECT $port\n");
268             $self->connection_accept('DATA', 30, sub { $self->got_connection(@_); });
269         } else {
270             $self->{'ctl_stream'} = undef; # don't use this for ctl anymore
271             $self->{'data_stream'} = 'main';
272             $self->make_plan();
273         }
274     } else {
275         $self->make_plan();
276     }
277 }
278
279 sub got_connection {
280     my $self = shift;
281     my ($err) = @_;
282
283     if ($err) {
284         $self->sendmessage("$err");
285         return $self->quit();
286     }
287
288     if (!$self->check_inetd_security('DATA')) {
289         $main::exit_status = 1;
290         return $self->quit();
291     }
292     $self->{'data_stream'} = 'DATA';
293
294     $self->make_plan();
295 }
296
297 sub make_plan {
298     my $self = shift;
299
300     # put together a dumpspec
301     my $spec;
302     if (exists $self->{'command'}{'HOST'}
303      || exists $self->{'command'}{'DISK'}
304      || exists $self->{'command'}{'DATESTAMP'}) {
305         my $disk = $self->{'command'}{'DISK'};
306         if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_correct_disk_quoting)) {
307             debug("ignoring specified DISK, as it may be badly quoted");
308             $disk = undef;
309         }
310         $spec = Amanda::Cmdline::dumpspec_t->new(
311             $self->{'command'}{'HOST'},
312             $disk,
313             $self->{'command'}{'DATESTAMP'},
314             undef,  # amidxtaped protocol does not provide a level (!?)
315             undef); # amidxtaped protocol does not provide a write timestamp
316     }
317
318     # figure out if this is a holding-disk recovery
319     my $is_holding = 0;
320     if (!exists $self->{'command'}{'LABEL'} and exists $self->{'command'}{'DEVICE'}) {
321         $is_holding = 1;
322     }
323
324     my $chg;
325     if ($is_holding) {
326         # for holding, give the clerk a null; it won't touch it
327         $chg = Amanda::Changer->new("chg-null:");
328     } else {
329         # if not doing a holding-disk recovery, then we will need a changer.
330         # If we're using the "default" changer, instantiate that.  There are
331         # several ways the user can specify the default changer:
332         my $use_default = 0;
333         if (!exists $self->{'command'}{'DEVICE'}) {
334             $use_default = 1;
335         } elsif ($self->{'command'}{'DEVICE'} eq getconf($CNF_AMRECOVER_CHANGER)) {
336             $use_default = 1;
337         }
338
339         my $tlf = Amanda::Config::config_dir_relative(getconf($CNF_TAPELIST));
340         my $tl = Amanda::Tapelist->new($tlf);
341         if ($use_default) {
342             $chg = Amanda::Changer->new(undef, tapelist => $tl);
343         } else {
344             $chg = Amanda::Changer->new($self->{'command'}{'DEVICE'}, tapelist => $tl);
345         }
346
347         # if we got a bogus changer, log it to the debug log, but allow the
348         # scan algorithm to find a good one later.
349         if ($chg->isa("Amanda::Changer::Error")) {
350             warning("$chg");
351             $chg = Amanda::Changer->new("chg-null:");
352         }
353     }
354     $self->{'chg'} = $chg;
355
356     my $interactivity = main::Interactivity->new(clientservice => $self);
357
358     my $scan = Amanda::Recovery::Scan->new(
359                         chg => $chg,
360                         interactivity => $interactivity);
361     $self->{'scan'} = $scan;
362
363     # XXX temporary
364     $scan->{'scan_conf'}->{'driveinuse'} = Amanda::Recovery::Scan::SCAN_ASK;
365     $scan->{'scan_conf'}->{'volinuse'} = Amanda::Recovery::Scan::SCAN_ASK;
366     $scan->{'scan_conf'}->{'notfound'} = Amanda::Recovery::Scan::SCAN_ASK;
367
368     $self->{'clerk'} = Amanda::Recovery::Clerk->new(
369         # note that we don't have any use for clerk_notif's, so we don't pass
370         # a feedback object
371         scan => $scan);
372
373     if ($is_holding) {
374         # if this is a holding recovery, then the plan is pretty easy.  The holding
375         # file is given to us in the aptly-named DEVICE command key, with a :0 suffix
376         my $holding_file_tapespec = $self->{'command'}{'DEVICE'};
377         my $holding_file = $self->tapespec_to_holding($holding_file_tapespec);
378
379         return Amanda::Recovery::Planner::make_plan(
380             holding_file => $holding_file,
381             $spec? (dumpspec => $spec) : (),
382             plan_cb => sub { $self->plan_cb(@_); });
383     } else {
384         my $filelist = Amanda::Util::unmarshal_tapespec($self->{'command'}{'LABEL'});
385
386         # if LABEL was just a label, then FSF should contain the filenum we want to
387         # start with.
388         if ($filelist->[1][0] == 0) {
389             if (exists $self->{'command'}{'FSF'}) {
390                 $filelist->[1][0] = 0+$self->{'command'}{'FSF'};
391                 # note that if this is a split dump, make_plan will helpfully find the
392                 # remaining parts and include them in the restore.  Pretty spiffy.
393             } else {
394                 # we have only a label and (hopefully) a dumpspec, so let's see if the
395                 # catalog can find a dump for us.
396                 $filelist = $self->try_to_find_dump(
397                         $self->{'command'}{'LABEL'},
398                         $spec);
399                 if (!$filelist) {
400                     return $self->quit();
401                 }
402             }
403         }
404
405         return Amanda::Recovery::Planner::make_plan(
406             filelist => $filelist,
407             $spec? (dumpspec => $spec) : (),
408             plan_cb => sub { $self->plan_cb(@_); });
409     }
410 }
411
412 sub plan_cb {
413     my $self = shift;
414     my ($err, $plan) = @_;
415
416     if ($err) {
417         $self->sendmessage("$err");
418         return $self->quit();
419     }
420
421     if (@{$plan->{'dumps'}} > 1) {
422         $self->sendmessage("multiple matching dumps; cannot recover");
423         return $self->quit();
424     }
425
426     # check that the request-limit for this DLE allows this recovery.  because
427     # of the bass-ackward way that amrecover specifies the dump to us, we can't
428     # check the results until *after* the plan was created.
429     my $dump = $plan->{'dumps'}->[0];
430     my $dle = Amanda::Disklist::get_disk($dump->{'hostname'}, $dump->{'diskname'});
431     my $recovery_limit;
432     if ($dle && dumptype_seen($dle->{'config'}, $DUMPTYPE_RECOVERY_LIMIT)) {
433         debug("using DLE recovery limit");
434         $recovery_limit = dumptype_getconf($dle->{'config'}, $DUMPTYPE_RECOVERY_LIMIT);
435     } elsif (getconf_seen($CNF_RECOVERY_LIMIT)) {
436         debug("using global recovery limit as default");
437         $recovery_limit = getconf($CNF_RECOVERY_LIMIT);
438     }
439     my $peer = $ENV{'AMANDA_AUTHENTICATED_PEER'};
440     if (defined $recovery_limit) { # undef -> no recovery limit
441         if (!$peer) {
442             warning("a recovery limit is specified for this DLE, but no authenticated ".
443                     "peer name is available; rejecting request.");
444             $self->sendmessage("No matching dumps found");
445             return $self->quit();
446         }
447         my $matched = 0;
448         for my $rl (@$recovery_limit) {
449             if ($rl eq $Amanda::Config::LIMIT_SAMEHOST) {
450                 # handle same-host with a case-insensitive string compare, not match_host
451                 if (lc($peer) eq lc($dump->{'hostname'})) {
452                     $matched = 1;
453                     last;
454                 }
455             } elsif ($rl eq $Amanda::Config::LIMIT_SERVER) {
456                 # handle server with a case-insensitive string compare, not match_host
457                 my $myhostname = hostname;
458                 debug("myhostname: $myhostname");
459                 if (lc($peer) eq lc($myhostname)) {
460                     $matched = 1;
461                     last;
462                 }
463             } else {
464                 # otherwise use match_host to allow match expressions
465                 if (match_host($rl, $peer)) {
466                     $matched = 1;
467                     last;
468                 }
469             }
470         }
471         if (!$matched) {
472             warning("authenticated peer '$peer' did not match recovery-limit ".
473                     "config; rejecting request");
474             $self->sendmessage("No matching dumps found");
475             return $self->quit();
476         }
477     }
478
479     if (!$self->{'their_features'}->has($Amanda::Feature::fe_recover_splits)) {
480         # if we have greater than one volume, we may need to prompt for a new
481         # volume in mid-recovery.  Sadly, we have no way to inform the client of
482         # this.  In hopes that this will "just work", we just issue a warning.
483         my @vols = $plan->get_volume_list();
484         warning("client does not support split dumps; restore may fail if " .
485                 "interaction is necessary");
486     }
487
488     # now set up the transfer
489     $self->{'dump'} = $plan->{'dumps'}[0];
490     $self->{'clerk'}->get_xfer_src(
491         dump => $self->{'dump'},
492         xfer_src_cb => sub { $self->xfer_src_cb(@_); });
493 }
494
495 sub xfer_src_cb {
496     my $self = shift;
497     my ($errors, $header, $xfer_src, $directtcp_supported) = @_;
498
499     if ($errors) {
500         for (@$errors) {
501             $self->sendmessage("$_");
502         }
503         return $self->quit();
504     }
505
506     $self->{'xfer_src'} = $xfer_src;
507     $self->{'xfer_src_supports_directtcp'} = $directtcp_supported;
508     $self->{'header'} = $header;
509
510     debug("recovering from " . $header->summary());
511
512     # set up any filters that need to be applied, decryption first
513     my @filters;
514     if ($header->{'encrypted'}) {
515         if ($header->{'srv_encrypt'}) {
516             push @filters,
517                 Amanda::Xfer::Filter::Process->new(
518                     [ $header->{'srv_encrypt'}, $header->{'srv_decrypt_opt'} ], 0);
519             $header->{'encrypted'} = 0;
520             $header->{'srv_encrypt'} = '';
521             $header->{'srv_decrypt_opt'} = '';
522             $header->{'clnt_encrypt'} = '';
523             $header->{'clnt_decrypt_opt'} = '';
524             $header->{'encrypt_suffix'} = 'N';
525         } elsif ($header->{'clnt_encrypt'}) {
526             if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_receive_unfiltered)) {
527                 push @filters,
528                     Amanda::Xfer::Filter::Process->new(
529                         [ $header->{'clnt_encrypt'},
530                           $header->{'clnt_decrypt_opt'} ], 0);
531                 $header->{'encrypted'} = 0;
532                 $header->{'srv_encrypt'} = '';
533                 $header->{'srv_decrypt_opt'} = '';
534                 $header->{'clnt_encrypt'} = '';
535                 $header->{'clnt_decrypt_opt'} = '';
536                 $header->{'encrypt_suffix'} = 'N';
537             } else {
538                 debug("Not decrypting client encrypted stream");
539             }
540         } else {
541             $self->sendmessage("could not decrypt encrypted dump: no program specified");
542             return $self->quit();
543         }
544
545     }
546
547     if ($header->{'compressed'}) {
548         # need to uncompress this file
549         debug("..with decompression applied");
550         my $dle = $header->get_dle();
551
552         if ($header->{'srvcompprog'}) {
553             # TODO: this assumes that srvcompprog takes "-d" to decrypt
554             push @filters,
555                 Amanda::Xfer::Filter::Process->new(
556                     [ $header->{'srvcompprog'}, "-d" ], 0);
557             # adjust the header
558             $header->{'compressed'} = 0;
559             $header->{'uncompress_cmd'} = '';
560             $header->{'srvcompprog'} = '';
561         } elsif ($header->{'clntcompprog'}) {
562             if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_receive_unfiltered)) {
563                 # TODO: this assumes that clntcompprog takes "-d" to decrypt
564                 push @filters,
565                     Amanda::Xfer::Filter::Process->new(
566                         [ $header->{'clntcompprog'}, "-d" ], 0);
567                 # adjust the header
568                 $header->{'compressed'} = 0;
569                 $header->{'uncompress_cmd'} = '';
570                 $header->{'clntcompprog'} = '';
571             }
572         } else {
573             if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_receive_unfiltered) ||
574                 $dle->{'compress'} == $Amanda::Config::COMP_SERVER_FAST ||
575                 $dle->{'compress'} == $Amanda::Config::COMP_SERVER_BEST) {
576                 push @filters,
577                     Amanda::Xfer::Filter::Process->new(
578                         [ $Amanda::Constants::UNCOMPRESS_PATH,
579                           $Amanda::Constants::UNCOMPRESS_OPT ], 0);
580                 # adjust the header
581                 $header->{'compressed'} = 0;
582                 $header->{'uncompress_cmd'} = '';
583             }
584         }
585
586     }
587     $self->{'xfer_filters'} = [ @filters ];
588
589     # only send the header if requested
590     if ($self->{'command'}{'HEADER'}) {
591         $self->send_header();
592     } else {
593         $self->expect_datapath();
594     }
595 }
596
597 sub send_header {
598     my $self = shift;
599
600     my $header = $self->{'header'};
601
602     # filter out some things the remote might not be able to process
603     if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_dle_in_header)) {
604         $header->{'dle_str'} = undef;
605     }
606     if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_origsize_in_header)) {
607         $header->{'orig_size'} = 0;
608     }
609
610     # even with fe_amrecover_splits, amrecover doesn't like F_SPLIT_DUMPFILE.
611     $header->{'type'} = $Amanda::Header::F_DUMPFILE;
612
613     my $hdr_str = $header->to_string(32768, 32768);
614     Amanda::Util::full_write($self->wfd($self->{'data_stream'}), $hdr_str, length($hdr_str))
615         or die "writing to $self->{data_stream}: $!";
616
617     $self->expect_datapath();
618 }
619
620 sub expect_datapath {
621     my $self = shift;
622
623     $self->{'datapath'} = 'none';
624
625     # short-circuit this if amrecover doesn't support datapaths
626     if (!$self->{'their_features'}->has($Amanda::Feature::fe_amidxtaped_datapath)) {
627         return $self->start_xfer();
628     }
629
630     my $line = $self->getline($self->{'ctl_stream'});
631     if ($line eq "ABORT\r\n") {
632         return Amanda::MainLoop::quit();
633     }
634     my ($dpspec) = ($line =~ /^AVAIL-DATAPATH (.*)\r\n$/);
635     die "bad AVAIL-DATAPATH line" unless $dpspec;
636     my @avail_dps = split / /, $dpspec;
637
638     if (grep /^DIRECT-TCP$/, @avail_dps) {
639         # remote can handle a directtcp transfer .. can we?
640         if ($self->{'xfer_src_supports_directtcp'}) {
641             $self->{'datapath'} = 'directtcp';
642         } else {
643             $self->{'datapath'} = 'amanda';
644         }
645     } else {
646         # remote can at least handle AMANDA
647         die "remote cannot handle AMANDA datapath??"
648             unless grep /^AMANDA$/, @avail_dps;
649         $self->{'datapath'} = 'amanda';
650     }
651
652     $self->start_xfer();
653 }
654
655 sub start_xfer {
656     my $self = shift;
657
658     # create the appropriate destination based on our datapath
659     my $xfer_dest;
660     if ($self->{'datapath'} eq 'directtcp') {
661         $xfer_dest = Amanda::Xfer::Dest::DirectTCPListen->new();
662     } else {
663         $xfer_dest = Amanda::Xfer::Dest::Fd->new(
664                 $self->wfd($self->{'data_stream'})),
665     }
666
667     if ($self->{'datapath'} eq 'amanda') {
668         $self->sendctlline("USE-DATAPATH AMANDA\r\n");
669         my $dpline = $self->getline($self->{'ctl_stream'});
670         if ($dpline ne "DATAPATH-OK\r\n") {
671             die "expected DATAPATH-OK";
672         }
673     }
674
675     # start reading all filter stderr
676     foreach my $filter (@{$self->{'xfer_filters'}}) {
677         my $fd = $filter->get_stderr_fd();
678         $fd.="";
679         $fd = int($fd);
680         my $src = Amanda::MainLoop::fd_source($fd,
681                                               $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
682         my $buffer = "";
683         $self->{'all_filter'}{$src} = 1;
684         $src->set_callback( sub {
685             my $b;
686             my $n_read = POSIX::read($fd, $b, 1);
687             if (!defined $n_read) {
688                 return;
689             } elsif ($n_read == 0) {
690                 delete $self->{'all_filter'}->{$src};
691                 $src->remove();
692                 POSIX::close($fd);
693                 if (!%{$self->{'all_filter'}} and $self->{'fetch_done'}) {
694                     Amanda::MainLoop::quit();
695                 }
696             } else {
697                 $buffer .= $b;
698                 if ($b eq "\n") {
699                     my $line = $buffer;
700                     #print STDERR "filter stderr: $line";
701                     chomp $line;
702                     $self->sendmessage("filter stderr: $line");
703                     debug("filter stderr: $line");
704                     $buffer = "";
705                 }
706             }
707         });
708     }
709
710     # create and start the transfer
711     $self->{'xfer'} = Amanda::Xfer->new([
712         $self->{'xfer_src'},
713         @{$self->{'xfer_filters'}},
714         $xfer_dest,
715     ]);
716     my $size = 0;
717     $size = $self->{'dump'}->{'bytes'} if exists $self->{'dump'}->{'bytes'};
718     $self->{'xfer'}->start(sub { $self->handle_xmsg(@_); }, 0, $size);
719     debug("started xfer; datapath=$self->{datapath}");
720
721     # send the data-path response, if we have a datapath
722     if ($self->{'datapath'} eq 'directtcp') {
723         my $addrs = $xfer_dest->get_addrs();
724         $addrs = [ map { $_->[0] . ":" . $_->[1] } @$addrs ];
725         $addrs = join(" ", @$addrs);
726         $self->sendctlline("USE-DATAPATH DIRECT-TCP $addrs\r\n");
727         my $dpline = $self->getline($self->{'ctl_stream'});
728         if ($dpline ne "DATAPATH-OK\r\n") {
729             die "expected DATAPATH-OK";
730         }
731     }
732
733     # and let the clerk know
734     $self->{'clerk'}->start_recovery(
735         xfer => $self->{'xfer'},
736         recovery_cb => sub { $self->recovery_cb(@_); });
737 }
738
739 sub handle_xmsg {
740     my $self = shift;
741     my ($src, $msg, $xfer) = @_;
742
743     $self->{'clerk'}->handle_xmsg($src, $msg, $xfer);
744     if ($msg->{'elt'} != $self->{'xfer_src'}) {
745         if ($msg->{'type'} == $XMSG_ERROR) {
746             $self->sendmessage("$msg->{message}");
747         }
748     }
749 }
750
751 sub recovery_cb {
752     my $self = shift;
753     my %params = @_;
754
755     debug("recovery complete");
756     if (@{$params{'errors'}}) {
757         for (@{$params{'errors'}}) {
758             $self->sendmessage("$_");
759         }
760         return $self->quit();
761     }
762
763     # note that the amidxtaped protocol has no way to indicate successful
764     # completion of a transfer
765     if ($params{'result'} ne 'DONE') {
766         warning("NOTE: transfer failed, but amrecover does not know that");
767     }
768
769     $self->finish();
770 }
771
772 sub finish {
773     my $self = shift;
774
775     # close the data fd for writing to signal EOF
776     $self->close($self->{'data_stream'}, 'w');
777
778     $self->quit();
779 }
780
781 sub quit {
782     my $self = shift;
783
784     if ($self->{'clerk'}) {
785         $self->{'clerk'}->quit(finished_cb => sub {
786             my ($err) = @_;
787             $self->{'chg'}->quit() if defined $self->{'chg'};
788             if ($err) {
789                 # it's *way* too late to report this to amrecover now!
790                 warning("while quitting clerk: $err");
791             }
792             $self->quit1();
793         });
794     } else {
795         $self->{'scan'}->quit() if defined $self->{'scan'};
796         $self->{'chg'}->quit() if defined $self->{'chg'};
797         $self->quit1();
798     }
799
800 }
801
802 sub quit1 {
803     my $self = shift;
804
805     $self->{'fetch_done'} = 1;
806     if (!%{$self->{'all_filter'}}) {
807         Amanda::MainLoop::quit();
808     }
809 }
810
811 ## utilities
812
813 sub check_inetd_security {
814     my $self = shift;
815     my ($stream) = @_;
816
817     my $firstline = $self->getline($stream);
818     if ($firstline !~ /^SECURITY (.*)\n/) {
819         warning("did not get security line");
820         print "ERROR did not get security line\r\n";
821         return 0;
822     }
823
824     my $errmsg = $self->check_bsd_security($stream, $1);
825     if ($errmsg) {
826         print "ERROR $errmsg\r\n";
827         return 0;
828     }
829
830     return 1;
831 }
832
833 sub get_req {
834     my $self = shift;
835
836     my $req_str = '';
837     while (1) {
838         my $buf = Amanda::Util::full_read($self->rfd('main'), 1024);
839         last unless $buf;
840         $req_str .= $buf;
841     }
842     # we've read main to EOF, so close it
843     $self->close('main', 'r');
844
845     return $self->{'req'} = $self->parse_req($req_str);
846 }
847
848 sub send_rep {
849     my $self = shift;
850     my ($streams, $errors) = @_;
851     my $rep = '';
852
853     # first, if there were errors in the REQ, report them
854     if (@$errors) {
855         for my $err (@$errors) {
856             $rep .= "ERROR $err\n";
857         }
858     } else {
859         my $connline = $self->connect_streams(@$streams);
860         $rep .= "$connline\n";
861     }
862     # rep needs a empty-line terminator, I think
863     $rep .= "\n";
864
865     # write the whole rep packet, and close main to signal the end of the packet
866     $self->senddata('main', $rep);
867     $self->close('main', 'w');
868 }
869
870 # helper function to get a line, including the trailing '\n', from a stream.  This
871 # reads a character at a time to ensure that no extra characters are consumed.  This
872 # could certainly be more efficient! (TODO)
873 sub getline {
874     my $self = shift;
875     my ($stream) = @_;
876     my $fd = $self->rfd($stream);
877     my $line = '';
878
879     while (1) {
880         my $c;
881         POSIX::read($fd, $c, 1)
882             or last;
883         $line .= $c;
884         last if $c eq "\n";
885     }
886
887     my $chopped = $line;
888     $chopped =~ s/[\r\n]*$//g;
889     debug("CTL << $chopped");
890
891     return $line;
892 }
893
894 # like getline, but async; TODO:
895 #  - make all uses of getline async
896 #  - use buffering to read more than one character at a time
897 sub getline_async {
898     my $self = shift;
899     my ($stream, $async_read_cb) = @_;
900     my $fd = $self->rfd($stream);
901
902     my $data_in;
903     my $buf = '';
904
905     $data_in = sub {
906         my ($err, $data) = @_;
907
908         return $async_read_cb->($err, undef) if $err;
909
910         $buf .= $data;
911         if ($buf =~ /\r\n$/) {
912             my $chopped = $buf;
913             $chopped =~ s/[\r\n]*$//g;
914             debug("CTL << $chopped");
915
916             $async_read_cb->(undef, $buf);
917         } else {
918             Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
919         }
920     };
921     Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
922 }
923
924 # helper function to write a data to a stream.  This does not add newline characters.
925 # If the callback is given, this is async (TODO: all calls should be async)
926 sub senddata {
927     my $self = shift;
928     my ($stream, $data, $async_write_cb) = @_;
929     my $fd = $self->wfd($stream);
930
931     if (defined $async_write_cb) {
932         return Amanda::MainLoop::async_write(
933                 fd => $fd,
934                 data => $data,
935                 async_write_cb => $async_write_cb);
936     } else {
937         Amanda::Util::full_write($fd, $data, length($data))
938             or die "writing to $stream: $!";
939     }
940 }
941
942 # send a line on the control stream, or just log it if the ctl stream is gone;
943 # async callback is just like for senddata
944 sub sendctlline {
945     my $self = shift;
946     my ($msg, $async_write_cb) = @_;
947
948     my $chopped = $msg;
949     $chopped =~ s/[\r\n]*$//g;
950
951     if ($self->{'ctl_stream'}) {
952         debug("CTL >> $chopped");
953         return $self->senddata($self->{'ctl_stream'}, $msg, $async_write_cb);
954     } else {
955         debug("not sending CTL message as CTL is closed >> $chopped");
956         if (defined $async_write_cb) {
957             $async_write_cb->(undef, length($msg));
958         }
959     }
960 }
961
962 # send a MESSAGE on the CTL stream, but only if the remote has
963 # fe_amrecover_message
964 sub sendmessage {
965     my $self = shift;
966     my ($msg) = @_;
967
968     if ($self->{'their_features'}->has($Amanda::Feature::fe_amrecover_message)) {
969         $self->sendctlline("MESSAGE $msg\r\n");
970     } else {
971         warning("remote does not understand MESSAGE; not sent: MESSAGE $msg");
972     }
973 }
974
975 # covert a tapespec to a holding filename
976 sub tapespec_to_holding {
977     my $self = shift;
978     my ($tapespec) = @_;
979
980     my $filelist = Amanda::Util::unmarshal_tapespec($tapespec);
981
982     # $filelist should have the form [ $holding_file => [ 0 ] ]
983     die "invalid holding tapespec" unless @$filelist == 2;
984     die "invalid holding tapespec" unless @{$filelist->[1]} == 1;
985     die "invalid holding tapespec" unless $filelist->[1][0] == 0;
986
987     return $filelist->[0];
988 }
989
990 # amrecover didn't give us much to go on, but see if we can find a dump that
991 # will make it happy.
992 sub try_to_find_dump {
993     my $self = shift;
994     my ($label, $spec) = @_;
995
996     # search the catalog; get_dumps cannot search by labels, so we have to use
997     # get_parts instead
998     my @parts = Amanda::DB::Catalog::get_parts(
999         label => $label,
1000         dumpspecs => [ $spec ]);
1001
1002     if (!@parts) {
1003         $self->sendmessage("could not find any matching dumps on volume '$label'");
1004         return undef;
1005     }
1006
1007     # (note that if there is more than one dump in @parts, the planner will
1008     # catch it later)
1009
1010     # sort the parts by their order on each volume.  This sorts the volumes
1011     # lexically by label, but the planner will straighten it out.
1012     @parts = Amanda::DB::Catalog::sort_dumps([ "label", "filenum" ], @parts);
1013
1014     # loop over the parts for the dump and make a filelist.
1015     my $last_label = '';
1016     my $last_filenums = undef;
1017     my $filelist = [];
1018     for my $part (@parts) {
1019         next unless defined $part; # skip part number 0
1020         if ($part->{'label'} ne $last_label) {
1021             $last_label = $part->{'label'};
1022             $last_filenums = [];
1023             push @$filelist, $last_label, $last_filenums;
1024         }
1025         push @$last_filenums, $part->{'filenum'};
1026     }
1027
1028     return $filelist;
1029 }
1030
1031 ##
1032 # main driver
1033
1034 package main;
1035 use Amanda::Debug qw( debug );
1036 use Amanda::Util qw( :constants );
1037 use Amanda::Config qw( :init );
1038
1039 our $exit_status = 0;
1040
1041 sub main {
1042     Amanda::Util::setup_application("amidxtaped", "server", $CONTEXT_DAEMON);
1043     config_init(0, undef);
1044     Amanda::Debug::debug_dup_stderr_to_debug();
1045
1046     my $cs = main::ClientService->new();
1047     Amanda::MainLoop::call_later(sub { $cs->run(); });
1048     Amanda::MainLoop::run();
1049
1050     debug("exiting with $exit_status");
1051     Amanda::Util::finish_application();
1052 }
1053
1054 main();
1055 exit($exit_status);