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