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 dle_t *dump_dle = NULL;
66 char *mount_point = NULL; /* where disk was mounted */
67 char *disk_path = NULL; /* path relative to mount point */
68 char dump_date[STR_SIZE]; /* date on which we are restoring */
69 int quit_prog; /* set when time to exit parser */
70 char *tape_server_name = NULL;
71 int tape_server_socket;
72 char *tape_device_name = NULL;
73 am_feature_t *our_features = NULL;
74 char *our_features_string = NULL;
75 am_feature_t *indexsrv_features = NULL;
76 am_feature_t *tapesrv_features = NULL;
77 static char *errstr = NULL;
79 int amindexd_alive = 0;
83 security_stream_t *fd;
88 #define NSTREAMS (int)(sizeof(streams) / sizeof(streams[0]))
90 static void amindexd_response(void *, pkt_t *, security_handle_t *);
91 void stop_amindexd(void);
92 char *amindexd_client_get_security_conf(char *, void *);
94 static char* mesg_buffer = NULL;
95 /* gets a "line" from server and put in server_line */
96 /* server_line is terminated with \0, \r\n is striped */
97 /* returns -1 if error */
107 mesg_buffer = stralloc("");
109 while (!strstr(mesg_buffer,"\r\n")) {
111 size = security_stream_read_sync(streams[MESGFD].fd, &buf);
113 amrecover_debug(1, "amrecover: get_line size < 0 (%zd)\n", size);
117 amrecover_debug(1, "amrecover: get_line size == 0 (%zd)\n", size);
120 else if (buf == NULL) {
121 amrecover_debug(1, "amrecover: get_line buf == NULL\n");
124 amrecover_debug(1, "amrecover: get_line size = %zd\n", size);
125 newbuf = alloc(strlen(mesg_buffer)+size+1);
126 strncpy(newbuf, mesg_buffer, (size_t)(strlen(mesg_buffer) + size));
127 memcpy(newbuf+strlen(mesg_buffer), buf, (size_t)size);
128 newbuf[strlen(mesg_buffer)+size] = '\0';
130 mesg_buffer = newbuf;
133 s = strstr(mesg_buffer,"\r\n");
135 newbuf = stralloc(s+2);
136 server_line = newstralloc(server_line, mesg_buffer);
138 mesg_buffer = newbuf;
139 amrecover_debug(1, "get: %s\n", mesg_buffer);
144 /* get reply from server and print to screen */
145 /* handle multi-line reply */
146 /* return -1 if error */
147 /* return code returned by server always occupies first 3 bytes of global
148 variable server_line */
154 if (get_line() == -1) {
157 if(show) puts(server_line);
158 } while (server_line[3] == '-');
159 if(show) fflush(stdout);
165 /* get 1 line of reply */
166 /* returns -1 if error, 0 if last (or only) line, 1 if more to follow */
170 if (get_line() == -1)
172 return server_line[3] == '-';
176 /* returns pointer to returned line */
185 /* returns 0 if server returned an error code (ie code starting with 5)
186 and non-zero otherwise */
190 return server_line[0] != '5';
199 * NOTE: this routine is called from sigint_handler, so we must be
200 * **very** careful about what we do since there is no way to know
201 * our state at the time the interrupt happened. For instance,
202 * do not use any stdio or malloc routines here.
206 buffer = alloc(strlen(cmd)+3);
207 strncpy(buffer, cmd, strlen(cmd));
208 buffer[strlen(cmd)] = '\r';
209 buffer[strlen(cmd)+1] = '\n';
210 buffer[strlen(cmd)+2] = '\0';
212 if(security_stream_write(streams[MESGFD].fd, buffer, strlen(buffer)) < 0) {
220 /* send a command to the server, get reply and print to screen */
225 if (send_command(cmd) == -1) return -1;
226 if (grab_reply(1) == -1) return -1;
231 /* same as converse() but reply not echoed to stdout */
236 if (send_command(cmd) == -1) return -1;
237 if (grab_reply(0) == -1) return -1;
242 /* basic interrupt handler for when user presses ^C */
243 /* Bale out, letting server know before doing so */
249 * NOTE: we must be **very** careful about what we do here since there
250 * is no way to know our state at the time the interrupt happened.
251 * For instance, do not use any stdio routines here or in any called
252 * routines. Also, use _exit() instead of exit() to make sure stdio
253 * buffer flushing is not attempted.
255 (void)signum; /* Quiet unused parameter warning */
257 if (extract_restore_child_pid != -1)
258 (void)kill(extract_restore_child_pid, SIGKILL);
259 extract_restore_child_pid = -1;
262 (void)send_command("QUIT");
275 /* remove "/" at end of path */
276 if(length>1 && s[length-1]=='/')
279 /* change "/." to "/" */
280 if(strcmp(s,"/.")==0)
283 /* remove "/." at end of path */
284 if(strcmp(&(s[length-2]),"/.")==0)
293 (void)converse("QUIT");
297 char *localhost = NULL;
299 #ifdef DEFAULT_TAPE_SERVER
300 # define DEFAULT_TAPE_SERVER_FAILOVER (DEFAULT_TAPE_SERVER)
302 # define DEFAULT_TAPE_SERVER_FAILOVER (NULL)
312 char *lineread = NULL;
313 struct sigaction act, oact;
317 const security_driver_t *secdrv;
321 config_overwrites_t *cfg_ovr;
324 * Configure program for internationalization:
325 * 1) Only set the message locale for now.
326 * 2) Set textdomain for all amanda related programs to "amanda"
327 * We don't want to be forced to support dozens of message catalogs.
329 setlocale(LC_MESSAGES, "C");
330 textdomain("amanda");
334 set_pname("amrecover");
336 /* Don't die when child closes pipe */
337 signal(SIGPIPE, SIG_IGN);
339 dbopen(DBG_SUBDIR_CLIENT);
341 localhost = alloc(MAX_HOSTNAME_LENGTH+1);
342 if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) {
343 error(_("cannot determine local host name\n"));
346 localhost[MAX_HOSTNAME_LENGTH] = '\0';
348 /* load the base client configuration */
349 config_init(CONFIG_INIT_CLIENT, NULL);
351 if (config_errors(NULL) >= CFGERR_WARNINGS) {
352 config_print_errors();
353 if (config_errors(NULL) >= CFGERR_ERRORS) {
354 g_critical(_("errors processing config file"));
358 /* treat amrecover-specific command line options as the equivalent
359 * -o command-line options to set configuration values */
360 cfg_ovr = new_config_overwrites(argc/2);
362 /* If the first argument is not an option flag, then we assume
363 * it is a configuration name to match the syntax of the other
364 * Amanda utilities. */
365 if (argc > 1 && argv[1][0] != '-') {
366 add_config_overwrite(cfg_ovr, "conf", argv[1]);
368 /* remove that option from the command line */
373 /* now parse regular command-line '-' options */
374 while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) {
377 add_config_overwrite(cfg_ovr, "conf", optarg);
381 add_config_overwrite(cfg_ovr, "index_server", optarg);
385 add_config_overwrite(cfg_ovr, "tape_server", optarg);
389 add_config_overwrite(cfg_ovr, "tapedev", optarg);
393 add_config_overwrite_opt(cfg_ovr, optarg);
398 (void)g_printf(USAGE);
402 if (optind != argc) {
403 (void)g_fprintf(stderr, USAGE);
407 /* and now try to load the configuration named in that file */
408 apply_config_overwrites(cfg_ovr);
409 config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
410 getconf_str(CNF_CONF));
412 check_running_as(RUNNING_AS_ROOT);
414 dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
416 our_features = am_init_feature_set();
417 our_features_string = am_feature_to_string(our_features);
420 if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
421 server_name = getconf_str(CNF_INDEX_SERVER);
424 server_name = getenv("AMANDA_SERVER");
426 g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
430 server_name = getconf_str(CNF_INDEX_SERVER);
433 error(_("No index server set"));
436 server_name = stralloc(server_name);
438 tape_server_name = NULL;
439 if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */
440 tape_server_name = getconf_str(CNF_TAPE_SERVER);
442 if (!tape_server_name) {
443 tape_server_name = getenv("AMANDA_TAPE_SERVER");
444 if (!tape_server_name) {
445 tape_server_name = getenv("AMANDA_TAPESERVER");
446 if (tape_server_name) {
447 g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name);
450 g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
453 if (!tape_server_name) {
454 tape_server_name = getconf_str(CNF_TAPE_SERVER);
456 if (!tape_server_name) {
457 error(_("No tape server set"));
460 tape_server_name = stralloc(tape_server_name);
462 amfree(tape_device_name);
463 tape_device_name = getconf_str(CNF_TAPEDEV);
464 if (!tape_device_name ||
465 strlen(tape_device_name) == 0 ||
466 !getconf_seen(CNF_TAPEDEV)) {
467 tape_device_name = NULL;
469 tape_device_name = stralloc(tape_device_name);
472 authopt = stralloc(getconf_str(CNF_AUTH));
480 /* Don't die when child closes pipe */
481 signal(SIGPIPE, SIG_IGN);
483 /* set up signal handler */
484 act.sa_handler = sigint_handler;
485 sigemptyset(&act.sa_mask);
487 if (sigaction(SIGINT, &act, &oact) != 0) {
488 error(_("error setting signal handler: %s"), strerror(errno));
494 /* We assume that amindexd support fe_amindexd_options_features */
495 /* and fe_amindexd_options_auth */
496 /* We should send a noop to really know */
497 req = vstrallocf("SERVICE amindexd\n"
498 "OPTIONS features=%s;auth=%s;\n",
499 our_features_string, authopt);
501 secdrv = security_getdriver(authopt);
502 if (secdrv == NULL) {
503 error(_("no '%s' security driver available for host '%s'"),
504 authopt, server_name);
508 protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
509 req, STARTUP_TIMEOUT, amindexd_response, &response_error);
514 g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
515 version(), server_name);
517 if(response_error != 0) {
518 g_fprintf(stderr,"%s\n",errstr);
522 /* get server's banner */
523 if (grab_reply(1) == -1) {
524 aclose(server_socket);
527 if (!server_happy()) {
529 aclose(server_socket);
533 /* try to get the features from the server */
535 char *their_feature_string = NULL;
537 indexsrv_features = NULL;
539 line = vstrallocf("FEATURES %s", our_features_string);
540 if(exchange(line) == 0) {
541 their_feature_string = stralloc(server_line+13);
542 indexsrv_features = am_string_to_feature(their_feature_string);
543 if (!indexsrv_features)
544 g_printf(_("Bad feature string from server: %s"), their_feature_string);
546 if (!indexsrv_features)
547 indexsrv_features = am_set_default_feature_set();
549 amfree(their_feature_string);
553 /* set the date of extraction to be today */
555 tm = localtime(&timer);
557 strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
559 error(_("BAD DATE"));
561 g_printf(_("Setting restore date to today (%s)\n"), dump_date);
562 line = vstrallocf("DATE %s", dump_date);
563 if (converse(line) == -1) {
564 aclose(server_socket);
569 line = vstrallocf("SCNF %s", get_config_name());
570 if (converse(line) == -1) {
571 aclose(server_socket);
576 if (server_happy()) {
577 /* set host we are restoring to this host by default */
578 amfree(dump_hostname);
581 g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
583 g_printf(_("Use the sethost command to choose a host to recover\n"));
589 if ((lineread = readline("amrecover> ")) == NULL) {
594 if (lineread[0] != '\0')
596 add_history(lineread);
597 dbprintf(_("user command: '%s'\n"), lineread);
598 process_line(lineread); /* act on line's content */
601 } while (!quit_prog);
605 aclose(server_socket);
613 security_handle_t *sech)
615 int ports[NSTREAMS], *response_error = datap, i;
620 assert(response_error != NULL);
621 assert(sech != NULL);
624 errstr = newvstrallocf(errstr, _("[request failed: %s]"),
625 security_geterror(sech));
630 if (pkt->type == P_NAK) {
631 #if defined(PACKET_DEBUG)
632 dbprintf(_("got nak response:\n----\n%s\n----\n\n"), pkt->body);
635 tok = strtok(pkt->body, " ");
636 if (tok == NULL || strcmp(tok, "ERROR") != 0)
639 tok = strtok(NULL, "\n");
641 errstr = newvstrallocf(errstr, "NAK: %s", tok);
645 errstr = newvstrallocf(errstr, _("request NAK"));
651 if (pkt->type != P_REP) {
652 errstr = newvstrallocf(errstr, _("received strange packet type %s: %s"),
653 pkt_type2str(pkt->type), pkt->body);
658 #if defined(PACKET_DEBUG)
659 g_fprintf(stderr, _("got response:\n----\n%s\n----\n\n"), pkt->body);
662 for(i = 0; i < NSTREAMS; i++) {
664 streams[i].fd = NULL;
668 while((tok = strtok(p, " \n")) != NULL) {
672 * Error response packets have "ERROR" followed by the error message
673 * followed by a newline.
675 if (strcmp(tok, "ERROR") == 0) {
676 tok = strtok(NULL, "\n");
678 errstr = newvstrallocf(errstr, _("[bogus error packet]"));
680 errstr = newvstrallocf(errstr, "%s", tok);
688 * Regular packets have CONNECT followed by three streams
690 if (strcmp(tok, "CONNECT") == 0) {
693 * Parse the three stream specifiers out of the packet.
695 for (i = 0; i < NSTREAMS; i++) {
696 tok = strtok(NULL, " ");
697 if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
699 _("CONNECT token is \"%s\": expected \"%s\""),
700 tok ? tok : _("(null)"), streams[i].name);
703 tok = strtok(NULL, " \n");
704 if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
706 _("CONNECT %s token is \"%s\" expected a port number"),
707 streams[i].name, tok ? tok : _("(null)"));
715 * OPTIONS [options string] '\n'
717 if (strcmp(tok, "OPTIONS") == 0) {
718 tok = strtok(NULL, "\n");
720 extra = vstrallocf(_("OPTIONS token is missing"));
724 tok_end = tok + strlen(tok);
725 while((p = strchr(tok, ';')) != NULL) {
727 if(strncmp_const(tok, "features=") == 0) {
728 tok += SIZEOF("features=") - 1;
729 am_release_feature_set(their_features);
730 if((their_features = am_string_to_feature(tok)) == NULL) {
731 errstr = newvstrallocf(errstr,
732 _("OPTIONS: bad features value: %s"),
743 extra = vstrallocf(_("next token is \"%s\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\""), tok ? tok : _("(null)"));
749 * Connect the streams to their remote ports
751 for (i = 0; i < NSTREAMS; i++) {
752 /*@i@*/ if (ports[i] == -1)
754 streams[i].fd = security_stream_client(sech, ports[i]);
755 if (streams[i].fd == NULL) {
756 errstr = newvstrallocf(errstr,
757 _("[could not connect %s stream: %s]"),
758 streams[i].name, security_geterror(sech));
763 * Authenticate the streams
765 for (i = 0; i < NSTREAMS; i++) {
766 if (streams[i].fd == NULL)
768 if (security_stream_auth(streams[i].fd) < 0) {
769 errstr = newvstrallocf(errstr,
770 _("[could not authenticate %s stream: %s]"),
771 streams[i].name, security_stream_geterror(streams[i].fd));
777 * The MESGFD and DATAFD streams are mandatory. If we didn't get
780 if (streams[MESGFD].fd == NULL) {
781 errstr = newvstrallocf(errstr, _("[couldn't open MESG streams]"));
785 /* everything worked */
791 errstr = newvstrallocf(errstr,
792 _("[parse of reply message failed: %s]"),
793 extra ? extra : _("(no additional information)"));
804 * This is called when everything needs to shut down so event_loop()
813 for (i = 0; i < NSTREAMS; i++) {
814 if (streams[i].fd != NULL) {
815 security_stream_close(streams[i].fd);
816 streams[i].fd = NULL;
822 amindexd_client_get_security_conf(
826 (void)arg; /* Quiet unused parameter warning */
828 if(!string || !*string)
831 if(strcmp(string, "auth")==0) {
832 return(getconf_str(CNF_AUTH));
834 else if(strcmp(string, "ssh_keys")==0) {
835 return(getconf_str(CNF_SSH_KEYS));