2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1991-1998, 2000 University of Maryland at College Park
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that
9 * copyright notice and this permission notice appear in supporting
10 * documentation, and that the name of U.M. not be used in advertising or
11 * publicity pertaining to distribution of the software without specific,
12 * written prior permission. U.M. makes no representations about the
13 * suitability of this software for any purpose. It is provided "as is"
14 * without express or implied warranty.
16 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 * Authors: the Amanda Development Team. Its members are listed in a
24 * file named AUTHORS, in the root directory of this distribution.
27 * $Id: amrecover.c,v 1.73 2006/07/25 18:27:57 martinea Exp $
29 * an interactive program for recovering backed-up files
35 #include "amfeatures.h"
36 #include "amrecover.h"
45 #define amrecover_debug(i, ...) do { \
46 if ((i) <= debug_amrecover) { \
47 dbprintf(__VA_ARGS__); \
51 extern int process_line(char *line);
53 int grab_reply(int show);
54 void sigint_handler(int signum);
55 int main(int argc, char **argv);
57 #define USAGE _("Usage: amrecover [[-C] <config>] [-s <index-server>] [-t <tape-server>] [-d <tape-device>] [-o <clientconfigoption>]*\n")
59 char *server_name = NULL;
61 char *server_line = NULL;
62 char *dump_datestamp = NULL; /* date we are restoring */
63 char *dump_hostname; /* which machine we are restoring */
64 char *disk_name = NULL; /* disk we are restoring */
65 char *mount_point = NULL; /* where disk was mounted */
66 char *disk_path = NULL; /* path relative to mount point */
67 char dump_date[STR_SIZE]; /* date on which we are restoring */
68 int quit_prog; /* set when time to exit parser */
69 char *tape_server_name = NULL;
70 int tape_server_socket;
71 char *tape_device_name = NULL;
72 am_feature_t *our_features = NULL;
73 char *our_features_string = NULL;
74 am_feature_t *indexsrv_features = NULL;
75 am_feature_t *tapesrv_features = NULL;
76 static char *errstr = NULL;
78 int amindexd_alive = 0;
82 security_stream_t *fd;
87 #define NSTREAMS (int)(sizeof(streams) / sizeof(streams[0]))
89 static void amindexd_response(void *, pkt_t *, security_handle_t *);
90 void stop_amindexd(void);
91 char *amindexd_client_get_security_conf(char *, void *);
93 static char* mesg_buffer = NULL;
94 /* gets a "line" from server and put in server_line */
95 /* server_line is terminated with \0, \r\n is striped */
96 /* returns -1 if error */
106 mesg_buffer = stralloc("");
108 while (!strstr(mesg_buffer,"\r\n")) {
110 size = security_stream_read_sync(streams[MESGFD].fd, &buf);
112 amrecover_debug(1, "amrecover: get_line size < 0 (%zd)\n", size);
116 amrecover_debug(1, "amrecover: get_line size == 0 (%zd)\n", size);
119 else if (buf == NULL) {
120 amrecover_debug(1, "amrecover: get_line buf == NULL\n");
123 amrecover_debug(1, "amrecover: get_line size = %zd\n", size);
124 newbuf = alloc(strlen(mesg_buffer)+size+1);
125 strncpy(newbuf, mesg_buffer, (size_t)(strlen(mesg_buffer) + size));
126 memcpy(newbuf+strlen(mesg_buffer), buf, (size_t)size);
127 newbuf[strlen(mesg_buffer)+size] = '\0';
129 mesg_buffer = newbuf;
132 s = strstr(mesg_buffer,"\r\n");
134 newbuf = stralloc(s+2);
135 server_line = newstralloc(server_line, mesg_buffer);
137 mesg_buffer = newbuf;
142 /* get reply from server and print to screen */
143 /* handle multi-line reply */
144 /* return -1 if error */
145 /* return code returned by server always occupies first 3 bytes of global
146 variable server_line */
152 if (get_line() == -1) {
155 if(show) puts(server_line);
156 } while (server_line[3] == '-');
157 if(show) fflush(stdout);
163 /* get 1 line of reply */
164 /* returns -1 if error, 0 if last (or only) line, 1 if more to follow */
168 if (get_line() == -1)
170 return server_line[3] == '-';
174 /* returns pointer to returned line */
183 /* returns 0 if server returned an error code (ie code starting with 5)
184 and non-zero otherwise */
188 return server_line[0] != '5';
197 * NOTE: this routine is called from sigint_handler, so we must be
198 * **very** careful about what we do since there is no way to know
199 * our state at the time the interrupt happened. For instance,
200 * do not use any stdio or malloc routines here.
204 buffer = alloc(strlen(cmd)+3);
205 strncpy(buffer, cmd, strlen(cmd));
206 buffer[strlen(cmd)] = '\r';
207 buffer[strlen(cmd)+1] = '\n';
208 buffer[strlen(cmd)+2] = '\0';
210 if(security_stream_write(streams[MESGFD].fd, buffer, strlen(buffer)) < 0) {
218 /* send a command to the server, get reply and print to screen */
223 if (send_command(cmd) == -1) return -1;
224 if (grab_reply(1) == -1) return -1;
229 /* same as converse() but reply not echoed to stdout */
234 if (send_command(cmd) == -1) return -1;
235 if (grab_reply(0) == -1) return -1;
240 /* basic interrupt handler for when user presses ^C */
241 /* Bale out, letting server know before doing so */
247 * NOTE: we must be **very** careful about what we do here since there
248 * is no way to know our state at the time the interrupt happened.
249 * For instance, do not use any stdio routines here or in any called
250 * routines. Also, use _exit() instead of exit() to make sure stdio
251 * buffer flushing is not attempted.
253 (void)signum; /* Quiet unused parameter warning */
255 if (extract_restore_child_pid != -1)
256 (void)kill(extract_restore_child_pid, SIGKILL);
257 extract_restore_child_pid = -1;
260 (void)send_command("QUIT");
273 /* remove "/" at end of path */
274 if(length>1 && s[length-1]=='/')
277 /* change "/." to "/" */
278 if(strcmp(s,"/.")==0)
281 /* remove "/." at end of path */
282 if(strcmp(&(s[length-2]),"/.")==0)
291 (void)converse("QUIT");
295 char *localhost = NULL;
297 #ifdef DEFAULT_TAPE_SERVER
298 # define DEFAULT_TAPE_SERVER_FAILOVER (DEFAULT_TAPE_SERVER)
300 # define DEFAULT_TAPE_SERVER_FAILOVER (NULL)
310 char *lineread = NULL;
311 struct sigaction act, oact;
315 const security_driver_t *secdrv;
319 config_overwrites_t *cfg_ovr;
322 * Configure program for internationalization:
323 * 1) Only set the message locale for now.
324 * 2) Set textdomain for all amanda related programs to "amanda"
325 * We don't want to be forced to support dozens of message catalogs.
327 setlocale(LC_MESSAGES, "C");
328 textdomain("amanda");
332 set_pname("amrecover");
334 /* Don't die when child closes pipe */
335 signal(SIGPIPE, SIG_IGN);
337 dbopen(DBG_SUBDIR_CLIENT);
339 localhost = alloc(MAX_HOSTNAME_LENGTH+1);
340 if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) {
341 error(_("cannot determine local host name\n"));
344 localhost[MAX_HOSTNAME_LENGTH] = '\0';
346 /* load the base client configuration */
347 config_init(CONFIG_INIT_CLIENT, NULL);
349 /* treat amrecover-specific command line options as the equivalent
350 * -o command-line options to set configuration values */
351 cfg_ovr = new_config_overwrites(argc/2);
353 /* If the first argument is not an option flag, then we assume
354 * it is a configuration name to match the syntax of the other
355 * Amanda utilities. */
356 if (argc > 1 && argv[1][0] != '-') {
357 add_config_overwrite(cfg_ovr, "conf", argv[1]);
359 /* remove that option from the command line */
364 /* now parse regular command-line '-' options */
365 while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) {
368 add_config_overwrite(cfg_ovr, "conf", optarg);
372 add_config_overwrite(cfg_ovr, "index_server", optarg);
376 add_config_overwrite(cfg_ovr, "tape_server", optarg);
380 add_config_overwrite(cfg_ovr, "tapedev", optarg);
384 add_config_overwrite_opt(cfg_ovr, optarg);
389 (void)g_printf(USAGE);
393 if (optind != argc) {
394 (void)g_fprintf(stderr, USAGE);
398 /* and now try to load the configuration named in that file */
399 apply_config_overwrites(cfg_ovr);
400 config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
401 getconf_str(CNF_CONF));
403 check_running_as(RUNNING_AS_ROOT);
405 dbrename(config_name, DBG_SUBDIR_CLIENT);
407 our_features = am_init_feature_set();
408 our_features_string = am_feature_to_string(our_features);
411 if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
412 server_name = getconf_str(CNF_INDEX_SERVER);
415 server_name = getenv("AMANDA_SERVER");
417 g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
421 server_name = getconf_str(CNF_INDEX_SERVER);
424 error(_("No index server set"));
427 server_name = stralloc(server_name);
429 tape_server_name = NULL;
430 if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */
431 tape_server_name = getconf_str(CNF_TAPE_SERVER);
433 if (!tape_server_name) {
434 tape_server_name = getenv("AMANDA_TAPE_SERVER");
435 if (!tape_server_name) {
436 tape_server_name = getenv("AMANDA_TAPESERVER");
437 if (tape_server_name) {
438 g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name);
441 g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
444 if (!tape_server_name) {
445 tape_server_name = getconf_str(CNF_TAPE_SERVER);
447 if (!tape_server_name) {
448 error(_("No tape server set"));
451 tape_server_name = stralloc(tape_server_name);
453 amfree(tape_device_name);
454 tape_device_name = getconf_str(CNF_TAPEDEV);
455 if (!tape_device_name ||
456 strlen(tape_device_name) == 0 ||
457 !getconf_seen(CNF_TAPEDEV)) {
458 tape_device_name = NULL;
460 tape_device_name = stralloc(tape_device_name);
463 authopt = stralloc(getconf_str(CNF_AUTH));
471 /* Don't die when child closes pipe */
472 signal(SIGPIPE, SIG_IGN);
474 /* set up signal handler */
475 act.sa_handler = sigint_handler;
476 sigemptyset(&act.sa_mask);
478 if (sigaction(SIGINT, &act, &oact) != 0) {
479 error(_("error setting signal handler: %s"), strerror(errno));
485 /* We assume that amindexd support fe_amindexd_options_features */
486 /* and fe_amindexd_options_auth */
487 /* We should send a noop to really know */
488 req = vstrallocf("SERVICE amindexd\n"
489 "OPTIONS features=%s;auth=%s;\n",
490 our_features_string, authopt);
492 secdrv = security_getdriver(authopt);
493 if (secdrv == NULL) {
494 error(_("no '%s' security driver available for host '%s'"),
495 authopt, server_name);
499 protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
500 req, STARTUP_TIMEOUT, amindexd_response, &response_error);
505 g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
506 version(), server_name);
508 if(response_error != 0) {
509 g_fprintf(stderr,"%s\n",errstr);
513 /* get server's banner */
514 if (grab_reply(1) == -1) {
515 aclose(server_socket);
518 if (!server_happy()) {
520 aclose(server_socket);
524 /* try to get the features from the server */
526 char *their_feature_string = NULL;
528 line = vstrallocf("FEATURES %s", our_features_string);
529 if(exchange(line) == 0) {
530 their_feature_string = stralloc(server_line+13);
531 indexsrv_features = am_string_to_feature(their_feature_string);
534 indexsrv_features = am_set_default_feature_set();
536 amfree(their_feature_string);
540 /* set the date of extraction to be today */
542 tm = localtime(&timer);
544 strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
546 error(_("BAD DATE"));
548 g_printf(_("Setting restore date to today (%s)\n"), dump_date);
549 line = vstrallocf("DATE %s", dump_date);
550 if (converse(line) == -1) {
551 aclose(server_socket);
556 line = vstrallocf("SCNF %s", config_name);
557 if (converse(line) == -1) {
558 aclose(server_socket);
563 if (server_happy()) {
564 /* set host we are restoring to this host by default */
565 amfree(dump_hostname);
568 g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
570 g_printf(_("Use the sethost command to choose a host to recover\n"));
576 if ((lineread = readline("amrecover> ")) == NULL) {
581 if (lineread[0] != '\0')
583 add_history(lineread);
584 dbprintf(_("user command: '%s'\n"), lineread);
585 process_line(lineread); /* act on line's content */
588 } while (!quit_prog);
592 aclose(server_socket);
600 security_handle_t *sech)
602 int ports[NSTREAMS], *response_error = datap, i;
607 assert(response_error != NULL);
608 assert(sech != NULL);
611 errstr = newvstrallocf(errstr, _("[request failed: %s]"),
612 security_geterror(sech));
617 if (pkt->type == P_NAK) {
618 #if defined(PACKET_DEBUG)
619 dbprintf(_("got nak response:\n----\n%s\n----\n\n"), pkt->body);
622 tok = strtok(pkt->body, " ");
623 if (tok == NULL || strcmp(tok, "ERROR") != 0)
626 tok = strtok(NULL, "\n");
628 errstr = newvstrallocf(errstr, "NAK: %s", tok);
632 errstr = newvstrallocf(errstr, _("request NAK"));
638 if (pkt->type != P_REP) {
639 errstr = newvstrallocf(errstr, _("received strange packet type %s: %s"),
640 pkt_type2str(pkt->type), pkt->body);
645 #if defined(PACKET_DEBUG)
646 g_fprintf(stderr, _("got response:\n----\n%s\n----\n\n"), pkt->body);
649 for(i = 0; i < NSTREAMS; i++) {
651 streams[i].fd = NULL;
655 while((tok = strtok(p, " \n")) != NULL) {
659 * Error response packets have "ERROR" followed by the error message
660 * followed by a newline.
662 if (strcmp(tok, "ERROR") == 0) {
663 tok = strtok(NULL, "\n");
665 errstr = newvstrallocf(errstr, _("[bogus error packet]"));
667 errstr = newvstrallocf(errstr, "%s", tok);
675 * Regular packets have CONNECT followed by three streams
677 if (strcmp(tok, "CONNECT") == 0) {
680 * Parse the three stream specifiers out of the packet.
682 for (i = 0; i < NSTREAMS; i++) {
683 tok = strtok(NULL, " ");
684 if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
686 _("CONNECT token is \"%s\": expected \"%s\""),
687 tok ? tok : _("(null)"), streams[i].name);
690 tok = strtok(NULL, " \n");
691 if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
693 _("CONNECT %s token is \"%s\" expected a port number"),
694 streams[i].name, tok ? tok : _("(null)"));
702 * OPTIONS [options string] '\n'
704 if (strcmp(tok, "OPTIONS") == 0) {
705 tok = strtok(NULL, "\n");
707 extra = vstrallocf(_("OPTIONS token is missing"));
711 tok_end = tok + strlen(tok);
712 while((p = strchr(tok, ';')) != NULL) {
714 if(strncmp_const(tok, "features=") == 0) {
715 tok += SIZEOF("features=") - 1;
716 am_release_feature_set(their_features);
717 if((their_features = am_string_to_feature(tok)) == NULL) {
718 errstr = newvstrallocf(errstr,
719 _("OPTIONS: bad features value: %s"),
730 extra = vstrallocf(_("next token is \"%s\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\""), tok ? tok : _("(null)"));
736 * Connect the streams to their remote ports
738 for (i = 0; i < NSTREAMS; i++) {
739 /*@i@*/ if (ports[i] == -1)
741 streams[i].fd = security_stream_client(sech, ports[i]);
742 if (streams[i].fd == NULL) {
743 errstr = newvstrallocf(errstr,
744 _("[could not connect %s stream: %s]"),
745 streams[i].name, security_geterror(sech));
750 * Authenticate the streams
752 for (i = 0; i < NSTREAMS; i++) {
753 if (streams[i].fd == NULL)
755 if (security_stream_auth(streams[i].fd) < 0) {
756 errstr = newvstrallocf(errstr,
757 _("[could not authenticate %s stream: %s]"),
758 streams[i].name, security_stream_geterror(streams[i].fd));
764 * The MESGFD and DATAFD streams are mandatory. If we didn't get
767 if (streams[MESGFD].fd == NULL) {
768 errstr = newvstrallocf(errstr, _("[couldn't open MESG streams]"));
772 /* everything worked */
778 errstr = newvstrallocf(errstr,
779 _("[parse of reply message failed: %s]"),
780 extra ? extra : _("(no additional information)"));
791 * This is called when everything needs to shut down so event_loop()
800 for (i = 0; i < NSTREAMS; i++) {
801 if (streams[i].fd != NULL) {
802 security_stream_close(streams[i].fd);
803 streams[i].fd = NULL;
809 amindexd_client_get_security_conf(
813 (void)arg; /* Quiet unused parameter warning */
815 if(!string || !*string)
818 if(strcmp(string, "auth")==0) {
819 return(getconf_str(CNF_AUTH));
821 else if(strcmp(string, "ssh_keys")==0) {
822 return(getconf_str(CNF_SSH_KEYS));