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 );
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;
133 use Amanda::Logfile qw( match_disk match_host );
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
142 $self->{'my_features'} = Amanda::Feature::Set->mine();
143 $self->{'their_features'} = Amanda::Feature::Set->old();
144 $self->{'all_filter'} = {};
146 $self->setup_streams();
152 # get started checking security for inetd or processing the REQ/REP
154 if ($self->from_inetd()) {
155 if (!$self->check_inetd_security('main')) {
156 $main::exit_status = 1;
157 return $self->quit();
159 $self->{'ctl_stream'} = 'main';
160 $self->{'data_stream'} = undef; # no data stream yet
162 my $req = $self->get_req();
164 # make some sanity checks
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;
175 # and pull out the features, if given
176 if (defined($req->{'features'})) {
177 $self->{'their_features'} = $req->{'features'};
180 $self->send_rep(['CTL' => 'rw', 'DATA' => 'w'], $errors);
181 return $self->quit() if (@$errors);
183 $self->{'ctl_stream'} = 'CTL';
184 $self->{'data_stream'} = 'DATA';
187 $self->read_command();
192 my $ctl_stream = $self->{'ctl_stream'};
193 my $command = $self->{'command'} = {};
195 my @known_commands = qw(
196 HOST DISK DATESTAMP LABEL DEVICE FSF HEADER
199 $_ = $self->getline($ctl_stream);
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();
211 if (exists $command->{$cmd}) {
212 warning("got duplicate command key '$cmd' from remote");
214 $command->{$cmd} = $val || 1;
218 # features are handled specially. This is pretty weird!
221 my $featurestr = $self->{'my_features'}->as_string();
222 if ($self->from_amandad) {
223 $featreply = "FEATURES=$featurestr\r\n";
225 $featreply = $featurestr;
228 $self->senddata($ctl_stream, $featreply);
232 # process some info from the command
233 if ($command->{'FEATURES'}) {
234 $self->{'their_features'} = Amanda::Feature::Set->from_string($command->{'FEATURES'});
237 # load the configuration
238 if (!$command->{'CONFIG'}) {
239 die "no CONFIG line given";
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";
246 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER_PREFERRED);
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";
255 $self->setup_data_stream();
258 sub setup_data_stream {
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(@_); });
270 $self->{'ctl_stream'} = undef; # don't use this for ctl anymore
271 $self->{'data_stream'} = 'main';
284 $self->sendmessage("$err");
285 return $self->quit();
288 if (!$self->check_inetd_security('DATA')) {
289 $main::exit_status = 1;
290 return $self->quit();
292 $self->{'data_stream'} = 'DATA';
300 # put together a dumpspec
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");
310 $spec = Amanda::Cmdline::dumpspec_t->new(
311 $self->{'command'}{'HOST'},
313 $self->{'command'}{'DATESTAMP'},
314 undef, # amidxtaped protocol does not provide a level (!?)
315 undef); # amidxtaped protocol does not provide a write timestamp
318 # figure out if this is a holding-disk recovery
320 if (!exists $self->{'command'}{'LABEL'} and exists $self->{'command'}{'DEVICE'}) {
326 # for holding, give the clerk a null; it won't touch it
327 $chg = Amanda::Changer->new("chg-null:");
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:
333 if (!exists $self->{'command'}{'DEVICE'}) {
335 } elsif ($self->{'command'}{'DEVICE'} eq getconf($CNF_AMRECOVER_CHANGER)) {
339 my $tlf = Amanda::Config::config_dir_relative(getconf($CNF_TAPELIST));
340 my $tl = Amanda::Tapelist->new($tlf);
342 $chg = Amanda::Changer->new(undef, tapelist => $tl);
344 $chg = Amanda::Changer->new($self->{'command'}{'DEVICE'}, tapelist => $tl);
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")) {
351 $chg = Amanda::Changer->new("chg-null:");
354 $self->{'chg'} = $chg;
356 my $interactivity = main::Interactivity->new(clientservice => $self);
358 my $scan = Amanda::Recovery::Scan->new(
360 interactivity => $interactivity);
361 $self->{'scan'} = $scan;
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;
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
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);
379 return Amanda::Recovery::Planner::make_plan(
380 holding_file => $holding_file,
381 $spec? (dumpspec => $spec) : (),
382 plan_cb => sub { $self->plan_cb(@_); });
384 my $filelist = Amanda::Util::unmarshal_tapespec($self->{'command'}{'LABEL'});
386 # if LABEL was just a label, then FSF should contain the filenum we want to
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.
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'},
400 return $self->quit();
405 return Amanda::Recovery::Planner::make_plan(
406 filelist => $filelist,
407 $spec? (dumpspec => $spec) : (),
408 plan_cb => sub { $self->plan_cb(@_); });
414 my ($err, $plan) = @_;
417 $self->sendmessage("$err");
418 return $self->quit();
421 if (@{$plan->{'dumps'}} > 1) {
422 $self->sendmessage("multiple matching dumps; cannot recover");
423 return $self->quit();
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'});
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);
439 my $peer = $ENV{'AMANDA_AUTHENTICATED_PEER'};
440 if (defined $recovery_limit) { # undef -> no recovery limit
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();
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'})) {
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)) {
464 # otherwise use match_host to allow match expressions
465 if (match_host($rl, $peer)) {
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();
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");
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(@_); });
497 my ($errors, $header, $xfer_src, $directtcp_supported) = @_;
501 $self->sendmessage("$_");
503 return $self->quit();
506 $self->{'xfer_src'} = $xfer_src;
507 $self->{'xfer_src_supports_directtcp'} = $directtcp_supported;
508 $self->{'header'} = $header;
510 debug("recovering from " . $header->summary());
512 # set up any filters that need to be applied, decryption first
514 if ($header->{'encrypted'}) {
515 if ($header->{'srv_encrypt'}) {
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)) {
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';
538 debug("Not decrypting client encrypted stream");
541 $self->sendmessage("could not decrypt encrypted dump: no program specified");
542 return $self->quit();
547 if ($header->{'compressed'}) {
548 # need to uncompress this file
549 debug("..with decompression applied");
550 my $dle = $header->get_dle();
552 if ($header->{'srvcompprog'}) {
553 # TODO: this assumes that srvcompprog takes "-d" to decrypt
555 Amanda::Xfer::Filter::Process->new(
556 [ $header->{'srvcompprog'}, "-d" ], 0);
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
565 Amanda::Xfer::Filter::Process->new(
566 [ $header->{'clntcompprog'}, "-d" ], 0);
568 $header->{'compressed'} = 0;
569 $header->{'uncompress_cmd'} = '';
570 $header->{'clntcompprog'} = '';
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) {
577 Amanda::Xfer::Filter::Process->new(
578 [ $Amanda::Constants::UNCOMPRESS_PATH,
579 $Amanda::Constants::UNCOMPRESS_OPT ], 0);
581 $header->{'compressed'} = 0;
582 $header->{'uncompress_cmd'} = '';
587 $self->{'xfer_filters'} = [ @filters ];
589 # only send the header if requested
590 if ($self->{'command'}{'HEADER'}) {
591 $self->send_header();
593 $self->expect_datapath();
600 my $header = $self->{'header'};
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;
606 if (!$self->{'their_features'}->has($Amanda::Feature::fe_amrecover_origsize_in_header)) {
607 $header->{'orig_size'} = 0;
610 # even with fe_amrecover_splits, amrecover doesn't like F_SPLIT_DUMPFILE.
611 $header->{'type'} = $Amanda::Header::F_DUMPFILE;
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}: $!";
617 $self->expect_datapath();
620 sub expect_datapath {
623 $self->{'datapath'} = 'none';
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();
630 my $line = $self->getline($self->{'ctl_stream'});
631 if ($line eq "ABORT\r\n") {
632 return Amanda::MainLoop::quit();
634 my ($dpspec) = ($line =~ /^AVAIL-DATAPATH (.*)\r\n$/);
635 die "bad AVAIL-DATAPATH line" unless $dpspec;
636 my @avail_dps = split / /, $dpspec;
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';
643 $self->{'datapath'} = 'amanda';
646 # remote can at least handle AMANDA
647 die "remote cannot handle AMANDA datapath??"
648 unless grep /^AMANDA$/, @avail_dps;
649 $self->{'datapath'} = 'amanda';
658 # create the appropriate destination based on our datapath
660 if ($self->{'datapath'} eq 'directtcp') {
661 $xfer_dest = Amanda::Xfer::Dest::DirectTCPListen->new();
663 $xfer_dest = Amanda::Xfer::Dest::Fd->new(
664 $self->wfd($self->{'data_stream'})),
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";
675 # start reading all filter stderr
676 foreach my $filter (@{$self->{'xfer_filters'}}) {
677 my $fd = $filter->get_stderr_fd();
680 my $src = Amanda::MainLoop::fd_source($fd,
681 $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
683 $self->{'all_filter'}{$src} = 1;
684 $src->set_callback( sub {
686 my $n_read = POSIX::read($fd, $b, 1);
687 if (!defined $n_read) {
689 } elsif ($n_read == 0) {
690 delete $self->{'all_filter'}->{$src};
693 if (!%{$self->{'all_filter'}} and $self->{'fetch_done'}) {
694 Amanda::MainLoop::quit();
700 #print STDERR "filter stderr: $line";
702 $self->sendmessage("filter stderr: $line");
703 debug("filter stderr: $line");
710 # create and start the transfer
711 $self->{'xfer'} = Amanda::Xfer->new([
713 @{$self->{'xfer_filters'}},
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}");
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";
733 # and let the clerk know
734 $self->{'clerk'}->start_recovery(
735 xfer => $self->{'xfer'},
736 recovery_cb => sub { $self->recovery_cb(@_); });
741 my ($src, $msg, $xfer) = @_;
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}");
755 debug("recovery complete");
756 if (@{$params{'errors'}}) {
757 for (@{$params{'errors'}}) {
758 $self->sendmessage("$_");
760 return $self->quit();
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");
775 # close the data fd for writing to signal EOF
776 $self->close($self->{'data_stream'}, 'w');
784 if ($self->{'clerk'}) {
785 $self->{'clerk'}->quit(finished_cb => sub {
787 $self->{'chg'}->quit() if defined $self->{'chg'};
789 # it's *way* too late to report this to amrecover now!
790 warning("while quitting clerk: $err");
795 $self->{'scan'}->quit() if defined $self->{'scan'};
796 $self->{'chg'}->quit() if defined $self->{'chg'};
805 $self->{'fetch_done'} = 1;
806 if (!%{$self->{'all_filter'}}) {
807 Amanda::MainLoop::quit();
813 sub check_inetd_security {
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";
824 my $errmsg = $self->check_bsd_security($stream, $1);
826 print "ERROR $errmsg\r\n";
838 my $buf = Amanda::Util::full_read($self->rfd('main'), 1024);
842 # we've read main to EOF, so close it
843 $self->close('main', 'r');
845 return $self->{'req'} = $self->parse_req($req_str);
850 my ($streams, $errors) = @_;
853 # first, if there were errors in the REQ, report them
855 for my $err (@$errors) {
856 $rep .= "ERROR $err\n";
859 my $connline = $self->connect_streams(@$streams);
860 $rep .= "$connline\n";
862 # rep needs a empty-line terminator, I think
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');
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)
876 my $fd = $self->rfd($stream);
881 POSIX::read($fd, $c, 1)
888 $chopped =~ s/[\r\n]*$//g;
889 debug("CTL << $chopped");
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
899 my ($stream, $async_read_cb) = @_;
900 my $fd = $self->rfd($stream);
906 my ($err, $data) = @_;
908 return $async_read_cb->($err, undef) if $err;
911 if ($buf =~ /\r\n$/) {
913 $chopped =~ s/[\r\n]*$//g;
914 debug("CTL << $chopped");
916 $async_read_cb->(undef, $buf);
918 Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
921 Amanda::MainLoop::async_read(fd => $fd, size => 1, async_read_cb => $data_in);
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)
928 my ($stream, $data, $async_write_cb) = @_;
929 my $fd = $self->wfd($stream);
931 if (defined $async_write_cb) {
932 return Amanda::MainLoop::async_write(
935 async_write_cb => $async_write_cb);
937 Amanda::Util::full_write($fd, $data, length($data))
938 or die "writing to $stream: $!";
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
946 my ($msg, $async_write_cb) = @_;
949 $chopped =~ s/[\r\n]*$//g;
951 if ($self->{'ctl_stream'}) {
952 debug("CTL >> $chopped");
953 return $self->senddata($self->{'ctl_stream'}, $msg, $async_write_cb);
955 debug("not sending CTL message as CTL is closed >> $chopped");
956 if (defined $async_write_cb) {
957 $async_write_cb->(undef, length($msg));
962 # send a MESSAGE on the CTL stream, but only if the remote has
963 # fe_amrecover_message
968 if ($self->{'their_features'}->has($Amanda::Feature::fe_amrecover_message)) {
969 $self->sendctlline("MESSAGE $msg\r\n");
971 warning("remote does not understand MESSAGE; not sent: MESSAGE $msg");
975 # covert a tapespec to a holding filename
976 sub tapespec_to_holding {
980 my $filelist = Amanda::Util::unmarshal_tapespec($tapespec);
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;
987 return $filelist->[0];
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 {
994 my ($label, $spec) = @_;
996 # search the catalog; get_dumps cannot search by labels, so we have to use
998 my @parts = Amanda::DB::Catalog::get_parts(
1000 dumpspecs => [ $spec ]);
1003 $self->sendmessage("could not find any matching dumps on volume '$label'");
1007 # (note that if there is more than one dump in @parts, the planner will
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);
1014 # loop over the parts for the dump and make a filelist.
1015 my $last_label = '';
1016 my $last_filenums = undef;
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;
1025 push @$last_filenums, $part->{'filenum'};
1035 use Amanda::Debug qw( debug );
1036 use Amanda::Util qw( :constants );
1037 use Amanda::Config qw( :init );
1039 our $exit_status = 0;
1042 Amanda::Util::setup_application("amidxtaped", "server", $CONTEXT_DAEMON);
1043 config_init(0, undef);
1044 Amanda::Debug::debug_dup_stderr_to_debug();
1046 my $cs = main::ClientService->new();
1047 Amanda::MainLoop::call_later(sub { $cs->run(); });
1048 Amanda::MainLoop::run();
1050 debug("exiting with $exit_status");
1051 Amanda::Util::finish_application();