2 # Copyright (c) 2010 Zmanda, Inc. All Rights Reserved.
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.
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
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
17 # Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
20 use lib '@amperldir@';
27 package main::Interactivity;
28 use base 'Amanda::Interactivity';
29 use Amanda::Util qw( weaken_ref );
32 use Amanda::Debug qw( debug );
33 use Amanda::Config qw( :getconf );
34 use Amanda::Recovery::Scan qw( $DEFAULT_CHANGER );
41 clientservice => $params{'clientservice'},
44 # (weak ref here to eliminate reference loop)
45 weaken_ref($self->{'clientservice'});
47 return bless ($self, $class);
53 debug("ignoring spurious Amanda::Recovery::Scan abort call");
61 my $steps = define_steps
62 cb_ref => \$params{'request_cb'};
64 step send_message => sub {
66 $self->{'clientservice'}->sendmessage("$params{err}");
69 $steps->{'check_fe_feedme'}->();
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);
78 $steps->{'send_feedme'}->();
81 step send_feedme => sub {
82 $self->{'clientservice'}->sendctlline("FEEDME $params{label}\r\n", $steps->{'read_response'});
85 step read_response => sub {
86 my ($err, $written) = @_;
87 return $params{'request_cb'}->($err, undef) if $err;
89 $self->{'clientservice'}->getline_async(
90 $self->{'clientservice'}->{'ctl_stream'}, $steps->{'got_response'});
93 step got_response => sub {
94 my ($err, $line) = @_;
95 return $params{'request_cb'}->($err, undef) if $err;
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$/) {
101 if ($tape eq getconf($CNF_AMRECOVER_CHANGER)) {
102 $tape = $Amanda::Recovery::Scan::DEFAULT_CHANGER;
104 return $params{'request_cb'}->(undef, $tape); # use this device
106 return $params{'request_cb'}->("got invalid response from remote", undef);
112 # ClientService class
114 package main::ClientService;
115 use base 'Amanda::ClientService';
119 use Amanda::Debug qw( debug info warning );
120 use Amanda::MainLoop qw( :GIOCondition );
121 use Amanda::Util qw( :constants match_disk match_host );
123 use Amanda::Config qw( :init :getconf );
125 use Amanda::Recovery::Scan;
126 use Amanda::Xfer qw( :constants );
128 use Amanda::Recovery::Clerk;
129 use Amanda::Recovery::Planner;
130 use Amanda::Recovery::Scan;
131 use Amanda::DB::Catalog;
132 use Amanda::Disklist;
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
141 $self->{'my_features'} = Amanda::Feature::Set->mine();
142 $self->{'their_features'} = Amanda::Feature::Set->old();
143 $self->{'all_filter'} = {};
145 $self->setup_streams();
151 # get started checking security for inetd or processing the REQ/REP
153 if ($self->from_inetd()) {
154 if (!$self->check_inetd_security('main')) {
155 $main::exit_status = 1;
156 return $self->quit();
158 $self->{'ctl_stream'} = 'main';
159 $self->{'data_stream'} = undef; # no data stream yet
161 my $req = $self->get_req();
163 # make some sanity checks
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;
174 # and pull out the features, if given
175 if (defined($req->{'features'})) {
176 $self->{'their_features'} = $req->{'features'};
179 $self->send_rep(['CTL' => 'rw', 'DATA' => 'w'], $errors);
180 return $self->quit() if (@$errors);
182 $self->{'ctl_stream'} = 'CTL';
183 $self->{'data_stream'} = 'DATA';
186 $self->read_command();
191 my $ctl_stream = $self->{'ctl_stream'};
192 my $command = $self->{'command'} = {};
194 my @known_commands = qw(
195 HOST DISK DATESTAMP LABEL DEVICE FSF HEADER
198 $_ = $self->getline($ctl_stream);
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();
210 if (exists $command->{$cmd}) {
211 warning("got duplicate command key '$cmd' from remote");
213 $command->{$cmd} = $val || 1;
217 # features are handled specially. This is pretty weird!
220 my $featurestr = $self->{'my_features'}->as_string();
221 if ($self->from_amandad) {
222 $featreply = "FEATURES=$featurestr\r\n";
224 $featreply = $featurestr;
227 $self->senddata($ctl_stream, $featreply);
231 # process some info from the command
232 if ($command->{'FEATURES'}) {
233 $self->{'their_features'} = Amanda::Feature::Set->from_string($command->{'FEATURES'});
236 # load the configuration
237 if (!$command->{'CONFIG'}) {
238 die "no CONFIG line given";
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";
245 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER_PREFERRED);
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";
254 $self->setup_data_stream();
257 sub setup_data_stream {
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(@_); });
269 $self->{'ctl_stream'} = undef; # don't use this for ctl anymore
270 $self->{'data_stream'} = 'main';
283 $self->sendmessage("$err");
284 return $self->quit();
287 if (!$self->check_inetd_security('DATA')) {
288 $main::exit_status = 1;
289 return $self->quit();
291 $self->{'data_stream'} = 'DATA';
299 # put together a dumpspec
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");
309 $spec = Amanda::Cmdline::dumpspec_t->new(
310 $self->{'command'}{'HOST'},
312 $self->{'command'}{'DATESTAMP'},
313 undef, # amidxtaped protocol does not provide a level (!?)
314 undef); # amidxtaped protocol does not provide a write timestamp
317 # figure out if this is a holding-disk recovery
319 if (!exists $self->{'command'}{'LABEL'} and exists $self->{'command'}{'DEVICE'}) {
325 # for holding, give the clerk a null; it won't touch it
326 $chg = Amanda::Changer->new("chg-null:");
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:
332 if (!exists $self->{'command'}{'DEVICE'}) {
334 } elsif ($self->{'command'}{'DEVICE'} eq getconf($CNF_AMRECOVER_CHANGER)) {
338 my $tlf = Amanda::Config::config_dir_relative(getconf($CNF_TAPELIST));
339 my $tl = Amanda::Tapelist->new($tlf);
341 $chg = Amanda::Changer->new(undef, tapelist => $tl);
343 $chg = Amanda::Changer->new($self->{'command'}{'DEVICE'}, tapelist => $tl);
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")) {
350 $chg = Amanda::Changer->new("chg-null:");
353 $self->{'chg'} = $chg;
355 my $interactivity = main::Interactivity->new(clientservice => $self);
357 my $scan = Amanda::Recovery::Scan->new(
359 interactivity => $interactivity);
360 $self->{'scan'} = $scan;
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;
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
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);
378 return Amanda::Recovery::Planner::make_plan(
379 holding_file => $holding_file,
380 $spec? (dumpspec => $spec) : (),
381 plan_cb => sub { $self->plan_cb(@_); });
383 my $filelist = Amanda::Util::unmarshal_tapespec($self->{'command'}{'LABEL'});
385 # if LABEL was just a label, then FSF should contain the filenum we want to
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.
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'},
399 return $self->quit();
404 return Amanda::Recovery::Planner::make_plan(
405 filelist => $filelist,
406 $spec? (dumpspec => $spec) : (),
407 plan_cb => sub { $self->plan_cb(@_); });
413 my ($err, $plan) = @_;
416 $self->sendmessage("$err");
417 return $self->quit();
420 if (@{$plan->{'dumps'}} > 1) {
421 $self->sendmessage("multiple matching dumps; cannot recover");
422 return $self->quit();
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'});
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);
438 my $peer = $ENV{'AMANDA_AUTHENTICATED_PEER'};
439 if (defined $recovery_limit) { # undef -> no recovery limit
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();
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'})) {
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)) {
463 # otherwise use match_host to allow match expressions
464 if (match_host($rl, $peer)) {
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();
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");
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(@_); });
496 my ($errors, $header, $xfer_src, $directtcp_supported) = @_;
500 $self->sendmessage("$_");
502 return $self->quit();
505 $self->{'xfer_src'} = $xfer_src;
506 $self->{'xfer_src_supports_directtcp'} = $directtcp_supported;
507 $self->{'header'} = $header;
509 debug("recovering from " . $header->summary());
511 # set up any filters that need to be applied, decryption first
513 if ($header->{'encrypted'}) {
514 if ($header->{'srv_encrypt'}) {
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)) {
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';
537 debug("Not decrypting client encrypted stream");
540 $self->sendmessage("could not decrypt encrypted dump: no program specified");
541 return $self->quit();
546 if ($header->{'compressed'}) {
547 # need to uncompress this file
548 debug("..with decompression applied");
549 my $dle = $header->get_dle();
551 if ($header->{'srvcompprog'}) {
552 # TODO: this assumes that srvcompprog takes "-d" to decrypt
554 Amanda::Xfer::Filter::Process->new(
555 [ $header->{'srvcompprog'}, "-d" ], 0);
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
564 Amanda::Xfer::Filter::Process->new(
565 [ $header->{'clntcompprog'}, "-d" ], 0);
567 $header->{'compressed'} = 0;
568 $header->{'uncompress_cmd'} = '';
569 $header->{'clntcompprog'} = '';
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) {
576 Amanda::Xfer::Filter::Process->new(
577 [ $Amanda::Constants::UNCOMPRESS_PATH,
578 $Amanda::Constants::UNCOMPRESS_OPT ], 0);
580 $header->{'compressed'} = 0;
581 $header->{'uncompress_cmd'} = '';
586 $self->{'xfer_filters'} = [ @filters ];
588 # only send the header if requested
589 if ($self->{'command'}{'HEADER'}) {
590 $self->send_header();
592 $self->expect_datapath();
599 my $header = $self->{'header'};
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;
605 $header->{'dle_str'} =
606 Amanda::Disklist::clean_dle_str_for_client($header->{'dle_str'},
607 Amanda::Feature::am_features($self->{'their_features'}));
609 if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_origsize_in_header)) {
610 $header->{'orig_size'} = 0;
613 # even with fe_amrecover_splits, amrecover doesn't like F_SPLIT_DUMPFILE.
614 $header->{'type'} = $Amanda::Header::F_DUMPFILE;
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}: $!";
620 $self->expect_datapath();
623 sub expect_datapath {
626 $self->{'datapath'} = 'none';
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();
633 my $line = $self->getline($self->{'ctl_stream'});
634 if ($line eq "ABORT\r\n") {
635 return Amanda::MainLoop::quit();
637 my ($dpspec) = ($line =~ /^AVAIL-DATAPATH (.*)\r\n$/);
638 die "bad AVAIL-DATAPATH line" unless $dpspec;
639 my @avail_dps = split / /, $dpspec;
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';
646 $self->{'datapath'} = 'amanda';
649 # remote can at least handle AMANDA
650 die "remote cannot handle AMANDA datapath??"
651 unless grep /^AMANDA$/, @avail_dps;
652 $self->{'datapath'} = 'amanda';
661 # create the appropriate destination based on our datapath
663 if ($self->{'datapath'} eq 'directtcp') {
664 $xfer_dest = Amanda::Xfer::Dest::DirectTCPListen->new();
666 $xfer_dest = Amanda::Xfer::Dest::Fd->new(
667 $self->wfd($self->{'data_stream'})),
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";
678 # start reading all filter stderr
679 foreach my $filter (@{$self->{'xfer_filters'}}) {
680 my $fd = $filter->get_stderr_fd();
683 my $src = Amanda::MainLoop::fd_source($fd,
684 $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
686 $self->{'all_filter'}{$src} = 1;
687 $src->set_callback( sub {
689 my $n_read = POSIX::read($fd, $b, 1);
690 if (!defined $n_read) {
692 } elsif ($n_read == 0) {
693 delete $self->{'all_filter'}->{$src};
696 if (!%{$self->{'all_filter'}} and $self->{'fetch_done'}) {
697 Amanda::MainLoop::quit();
703 #print STDERR "filter stderr: $line";
705 $self->sendmessage("filter stderr: $line");
706 debug("filter stderr: $line");
713 # create and start the transfer
714 $self->{'xfer'} = Amanda::Xfer->new([
716 @{$self->{'xfer_filters'}},
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}");
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";
736 # and let the clerk know
737 $self->{'clerk'}->start_recovery(
738 xfer => $self->{'xfer'},
739 recovery_cb => sub { $self->recovery_cb(@_); });
744 my ($src, $msg, $xfer) = @_;
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}");
758 debug("recovery complete");
759 if (@{$params{'errors'}}) {
760 for (@{$params{'errors'}}) {
761 $self->sendmessage("$_");
763 return $self->quit();
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");
778 # close the data fd for writing to signal EOF
779 $self->close($self->{'data_stream'}, 'w');
787 if ($self->{'clerk'}) {
788 $self->{'clerk'}->quit(finished_cb => sub {
790 $self->{'chg'}->quit() if defined $self->{'chg'};
792 # it's *way* too late to report this to amrecover now!
793 warning("while quitting clerk: $err");
798 $self->{'scan'}->quit() if defined $self->{'scan'};
799 $self->{'chg'}->quit() if defined $self->{'chg'};
808 $self->{'fetch_done'} = 1;
809 if (!%{$self->{'all_filter'}}) {
810 Amanda::MainLoop::quit();
816 sub check_inetd_security {
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";
827 my $errmsg = $self->check_bsd_security($stream, $1);
829 print "ERROR $errmsg\r\n";
841 my $buf = Amanda::Util::full_read($self->rfd('main'), 1024);
845 # we've read main to EOF, so close it
846 $self->close('main', 'r');
848 return $self->{'req'} = $self->parse_req($req_str);
853 my ($streams, $errors) = @_;
856 # first, if there were errors in the REQ, report them
858 for my $err (@$errors) {
859 $rep .= "ERROR $err\n";
862 my $connline = $self->connect_streams(@$streams);
863 $rep .= "$connline\n";
865 # rep needs a empty-line terminator, I think
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');
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)
879 my $fd = $self->rfd($stream);
884 POSIX::read($fd, $c, 1)
891 $chopped =~ s/[\r\n]*$//g;
892 debug("CTL << $chopped");
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
902 my ($stream, $async_read_cb) = @_;
903 my $fd = $self->rfd($stream);
909 my ($err, $data) = @_;
911 return $async_read_cb->($err, undef) if $err;
914 if ($buf =~ /\r\n$/) {
916 $chopped =~ s/[\r\n]*$//g;
917 debug("CTL << $chopped");
919 $async_read_cb->(undef, $buf);
921 Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
924 Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
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)
931 my ($stream, $data, $async_write_cb) = @_;
932 my $fd = $self->wfd($stream);
934 if (defined $async_write_cb) {
935 return Amanda::MainLoop::async_write(
938 async_write_cb => $async_write_cb);
940 Amanda::Util::full_write($fd, $data, length($data))
941 or die "writing to $stream: $!";
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
949 my ($msg, $async_write_cb) = @_;
952 $chopped =~ s/[\r\n]*$//g;
954 if ($self->{'ctl_stream'}) {
955 debug("CTL >> $chopped");
956 return $self->senddata($self->{'ctl_stream'}, $msg, $async_write_cb);
958 debug("not sending CTL message as CTL is closed >> $chopped");
959 if (defined $async_write_cb) {
960 $async_write_cb->(undef, length($msg));
965 # send a MESSAGE on the CTL stream, but only if the remote has
966 # fe_amrecover_message
971 if ($self->{'their_features'}->has($Amanda::Feature::fe_amrecover_message)) {
972 $self->sendctlline("MESSAGE $msg\r\n");
974 warning("remote does not understand MESSAGE; not sent: MESSAGE $msg");
978 # covert a tapespec to a holding filename
979 sub tapespec_to_holding {
983 my $filelist = Amanda::Util::unmarshal_tapespec($tapespec);
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;
990 return $filelist->[0];
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 {
997 my ($label, $spec) = @_;
999 # search the catalog; get_dumps cannot search by labels, so we have to use
1001 my @parts = Amanda::DB::Catalog::get_parts(
1003 dumpspecs => [ $spec ]);
1006 $self->sendmessage("could not find any matching dumps on volume '$label'");
1010 # (note that if there is more than one dump in @parts, the planner will
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);
1017 # loop over the parts for the dump and make a filelist.
1018 my $last_label = '';
1019 my $last_filenums = undef;
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;
1028 push @$last_filenums, $part->{'filenum'};
1038 use Amanda::Debug qw( debug );
1039 use Amanda::Util qw( :constants );
1040 use Amanda::Config qw( :init );
1042 our $exit_status = 0;
1045 Amanda::Util::setup_application("amidxtaped", "server", $CONTEXT_DAEMON);
1046 config_init(0, undef);
1047 Amanda::Debug::debug_dup_stderr_to_debug();
1049 my $cs = main::ClientService->new();
1050 Amanda::MainLoop::call_later(sub { $cs->run(); });
1051 Amanda::MainLoop::run();
1053 debug("exiting with $exit_status");
1054 Amanda::Util::finish_application();