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
34 #include "amfeatures.h"
35 #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 proplist_t proplist = NULL;
78 static char *errstr = NULL;
80 int amindexd_alive = 0;
84 security_stream_t *fd;
89 #define NSTREAMS (int)(sizeof(streams) / sizeof(streams[0]))
91 static void amindexd_response(void *, pkt_t *, security_handle_t *);
92 void stop_amindexd(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;
134 s = strstr(mesg_buffer,"\r\n");
136 newbuf = stralloc(s+2);
137 server_line = newstralloc(server_line, mesg_buffer);
139 mesg_buffer = newbuf;
140 amrecover_debug(1, "get: %s\n", mesg_buffer);
145 /* get reply from server and print to screen */
146 /* handle multi-line reply */
147 /* return -1 if error */
148 /* return code returned by server always occupies first 3 bytes of global
149 variable server_line */
150 /* show == 0: Print the reply if it is an error */
151 /* show == 1: Always print the reply */
157 if (get_line() == -1) {
160 if (show || server_line[0] == '5') {
163 } while (server_line[3] == '-');
164 if(show) fflush(stdout);
170 /* get 1 line of reply */
171 /* returns -1 if error, 0 if last (or only) line, 1 if more to follow */
175 if (get_line() == -1)
177 return server_line[3] == '-';
181 /* returns pointer to returned line */
190 /* returns 0 if server returned an error code (ie code starting with 5)
191 and non-zero otherwise */
195 return server_line[0] != '5';
204 * NOTE: this routine is called from sigint_handler, so we must be
205 * **very** careful about what we do since there is no way to know
206 * our state at the time the interrupt happened. For instance,
207 * do not use any stdio or malloc routines here.
211 buffer = alloc(strlen(cmd)+3);
212 strncpy(buffer, cmd, strlen(cmd));
213 buffer[strlen(cmd)] = '\r';
214 buffer[strlen(cmd)+1] = '\n';
215 buffer[strlen(cmd)+2] = '\0';
217 g_debug("sending: %s\n", buffer);
218 if(security_stream_write(streams[MESGFD].fd, buffer, strlen(buffer)) < 0) {
226 /* send a command to the server, get reply and print to screen */
231 if (send_command(cmd) == -1) return -1;
232 if (grab_reply(1) == -1) return -1;
237 /* same as converse() but reply not echoed to stdout */
242 if (send_command(cmd) == -1) return -1;
243 if (grab_reply(0) == -1) return -1;
248 /* basic interrupt handler for when user presses ^C */
249 /* Bale out, letting server know before doing so */
255 * NOTE: we must be **very** careful about what we do here since there
256 * is no way to know our state at the time the interrupt happened.
257 * For instance, do not use any stdio routines here or in any called
258 * routines. Also, use _exit() instead of exit() to make sure stdio
259 * buffer flushing is not attempted.
261 (void)signum; /* Quiet unused parameter warning */
263 if (extract_restore_child_pid != -1)
264 (void)kill(extract_restore_child_pid, SIGKILL);
265 extract_restore_child_pid = -1;
268 (void)send_command("QUIT");
281 /* remove "/" at end of path */
282 if(length>1 && s[length-1]=='/')
285 /* change "/." to "/" */
286 if(strcmp(s,"/.")==0)
289 /* remove "/." at end of path */
290 if(strcmp(&(s[length-2]),"/.")==0)
299 (void)converse("QUIT");
303 char *localhost = NULL;
305 #ifdef DEFAULT_TAPE_SERVER
306 # define DEFAULT_TAPE_SERVER_FAILOVER (DEFAULT_TAPE_SERVER)
308 # define DEFAULT_TAPE_SERVER_FAILOVER (NULL)
318 char *lineread = NULL;
319 struct sigaction act, oact;
323 const security_driver_t *secdrv;
327 config_overrides_t *cfg_ovr;
330 * Configure program for internationalization:
331 * 1) Only set the message locale for now.
332 * 2) Set textdomain for all amanda related programs to "amanda"
333 * We don't want to be forced to support dozens of message catalogs.
335 setlocale(LC_MESSAGES, "C");
336 textdomain("amanda");
340 set_pname("amrecover");
342 /* Don't die when child closes pipe */
343 signal(SIGPIPE, SIG_IGN);
345 dbopen(DBG_SUBDIR_CLIENT);
347 localhost = alloc(MAX_HOSTNAME_LENGTH+1);
348 if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) {
349 error(_("cannot determine local host name\n"));
352 localhost[MAX_HOSTNAME_LENGTH] = '\0';
354 /* treat amrecover-specific command line options as the equivalent
355 * -o command-line options to set configuration values */
356 cfg_ovr = new_config_overrides(argc/2);
358 /* If the first argument is not an option flag, then we assume
359 * it is a configuration name to match the syntax of the other
360 * Amanda utilities. */
361 if (argc > 1 && argv[1][0] != '-') {
362 add_config_override(cfg_ovr, "conf", argv[1]);
364 /* remove that option from the command line */
369 /* now parse regular command-line '-' options */
370 while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) {
373 add_config_override(cfg_ovr, "conf", optarg);
377 add_config_override(cfg_ovr, "index_server", optarg);
381 add_config_override(cfg_ovr, "tape_server", optarg);
385 add_config_override(cfg_ovr, "tapedev", optarg);
389 add_config_override_opt(cfg_ovr, optarg);
394 (void)g_printf(USAGE);
398 if (optind != argc) {
399 (void)g_fprintf(stderr, USAGE);
403 /* load the base client configuration */
404 set_config_overrides(cfg_ovr);
405 config_init(CONFIG_INIT_CLIENT, NULL);
407 if (config_errors(NULL) >= CFGERR_WARNINGS) {
408 config_print_errors();
409 if (config_errors(NULL) >= CFGERR_ERRORS) {
410 g_critical(_("errors processing config file"));
414 /* and now try to load the configuration named in that file */
415 config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
416 getconf_str(CNF_CONF));
418 check_running_as(RUNNING_AS_ROOT);
420 dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
422 our_features = am_init_feature_set();
423 our_features_string = am_feature_to_string(our_features);
426 if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
427 server_name = getconf_str(CNF_INDEX_SERVER);
430 server_name = getenv("AMANDA_SERVER");
432 g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
436 server_name = getconf_str(CNF_INDEX_SERVER);
439 error(_("No index server set"));
442 server_name = stralloc(server_name);
444 tape_server_name = NULL;
445 if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */
446 tape_server_name = getconf_str(CNF_TAPE_SERVER);
448 if (!tape_server_name) {
449 tape_server_name = getenv("AMANDA_TAPE_SERVER");
450 if (!tape_server_name) {
451 tape_server_name = getenv("AMANDA_TAPESERVER");
452 if (tape_server_name) {
453 g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name);
456 g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
459 if (!tape_server_name) {
460 tape_server_name = getconf_str(CNF_TAPE_SERVER);
462 if (!tape_server_name) {
463 error(_("No tape server set"));
466 tape_server_name = stralloc(tape_server_name);
468 amfree(tape_device_name);
469 tape_device_name = getconf_str(CNF_TAPEDEV);
470 if (!tape_device_name ||
471 strlen(tape_device_name) == 0 ||
472 !getconf_seen(CNF_TAPEDEV)) {
473 tape_device_name = NULL;
475 tape_device_name = stralloc(tape_device_name);
478 authopt = stralloc(getconf_str(CNF_AUTH));
486 /* Don't die when child closes pipe */
487 signal(SIGPIPE, SIG_IGN);
489 /* set up signal handler */
490 act.sa_handler = sigint_handler;
491 sigemptyset(&act.sa_mask);
493 if (sigaction(SIGINT, &act, &oact) != 0) {
494 error(_("error setting signal handler: %s"), strerror(errno));
498 proplist = g_hash_table_new_full(g_str_hash, g_str_equal, &g_free, &free_property_t);
502 /* We assume that amindexd support fe_amindexd_options_features */
503 /* and fe_amindexd_options_auth */
504 /* We should send a noop to really know */
505 req = vstrallocf("SERVICE amindexd\n"
506 "OPTIONS features=%s;auth=%s;\n",
507 our_features_string, authopt);
509 secdrv = security_getdriver(authopt);
510 if (secdrv == NULL) {
511 error(_("no '%s' security driver available for host '%s'"),
512 authopt, server_name);
516 protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
517 req, STARTUP_TIMEOUT, amindexd_response, &response_error);
522 g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
523 VERSION, server_name);
525 if(response_error != 0) {
526 g_fprintf(stderr,"%s\n",errstr);
530 /* get server's banner */
531 if (grab_reply(1) == -1) {
532 aclose(server_socket);
535 if (!server_happy()) {
537 aclose(server_socket);
541 /* try to get the features from the server */
543 char *their_feature_string = NULL;
545 indexsrv_features = NULL;
547 line = vstrallocf("FEATURES %s", our_features_string);
548 if(exchange(line) == 0) {
549 their_feature_string = stralloc(server_line+13);
550 indexsrv_features = am_string_to_feature(their_feature_string);
551 if (!indexsrv_features)
552 g_printf(_("Bad feature string from server: %s"), their_feature_string);
554 if (!indexsrv_features)
555 indexsrv_features = am_set_default_feature_set();
557 amfree(their_feature_string);
561 /* set the date of extraction to be today */
563 tm = localtime(&timer);
565 strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
567 error(_("BAD DATE"));
569 g_printf(_("Setting restore date to today (%s)\n"), dump_date);
570 line = vstrallocf("DATE %s", dump_date);
571 if (converse(line) == -1) {
572 aclose(server_socket);
577 line = vstrallocf("SCNF %s", get_config_name());
578 if (converse(line) == -1) {
579 aclose(server_socket);
584 if (server_happy()) {
585 /* set host we are restoring to this host by default */
586 amfree(dump_hostname);
589 g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
591 g_printf(_("Use the sethost command to choose a host to recover\n"));
597 if ((lineread = readline("amrecover> ")) == NULL) {
602 if (lineread[0] != '\0')
604 add_history(lineread);
605 dbprintf(_("user command: '%s'\n"), lineread);
606 process_line(lineread); /* act on line's content */
609 } while (!quit_prog);
613 aclose(server_socket);
621 security_handle_t *sech)
623 int ports[NSTREAMS], *response_error = datap, i;
628 assert(response_error != NULL);
629 assert(sech != NULL);
632 errstr = newvstrallocf(errstr, _("[request failed: %s]"),
633 security_geterror(sech));
638 if (pkt->type == P_NAK) {
639 #if defined(PACKET_DEBUG)
640 dbprintf(_("got nak response:\n----\n%s\n----\n\n"), pkt->body);
643 tok = strtok(pkt->body, " ");
644 if (tok == NULL || strcmp(tok, "ERROR") != 0)
647 tok = strtok(NULL, "\n");
649 errstr = newvstrallocf(errstr, "NAK: %s", tok);
653 errstr = newvstrallocf(errstr, _("request NAK"));
659 if (pkt->type != P_REP) {
660 errstr = newvstrallocf(errstr, _("received strange packet type %s: %s"),
661 pkt_type2str(pkt->type), pkt->body);
666 #if defined(PACKET_DEBUG)
667 g_fprintf(stderr, _("got response:\n----\n%s\n----\n\n"), pkt->body);
670 for(i = 0; i < NSTREAMS; i++) {
672 streams[i].fd = NULL;
676 while((tok = strtok(p, " \n")) != NULL) {
680 * Error response packets have "ERROR" followed by the error message
681 * followed by a newline.
683 if (strcmp(tok, "ERROR") == 0) {
684 tok = strtok(NULL, "\n");
686 errstr = newvstrallocf(errstr, _("[bogus error packet]"));
688 errstr = newvstrallocf(errstr, "%s", tok);
696 * Regular packets have CONNECT followed by three streams
698 if (strcmp(tok, "CONNECT") == 0) {
701 * Parse the three stream specifiers out of the packet.
703 for (i = 0; i < NSTREAMS; i++) {
704 tok = strtok(NULL, " ");
705 if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
707 _("CONNECT token is \"%s\": expected \"%s\""),
708 tok ? tok : _("(null)"), streams[i].name);
711 tok = strtok(NULL, " \n");
712 if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
714 _("CONNECT %s token is \"%s\" expected a port number"),
715 streams[i].name, tok ? tok : _("(null)"));
723 * OPTIONS [options string] '\n'
725 if (strcmp(tok, "OPTIONS") == 0) {
726 tok = strtok(NULL, "\n");
728 extra = vstrallocf(_("OPTIONS token is missing"));
732 tok_end = tok + strlen(tok);
733 while((p = strchr(tok, ';')) != NULL) {
735 if(strncmp_const(tok, "features=") == 0) {
736 tok += SIZEOF("features=") - 1;
737 am_release_feature_set(their_features);
738 if((their_features = am_string_to_feature(tok)) == NULL) {
739 errstr = newvstrallocf(errstr,
740 _("OPTIONS: bad features value: %s"),
751 extra = vstrallocf(_("next token is \"%s\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\""), tok ? tok : _("(null)"));
757 * Connect the streams to their remote ports
759 for (i = 0; i < NSTREAMS; i++) {
760 /*@i@*/ if (ports[i] == -1)
762 streams[i].fd = security_stream_client(sech, ports[i]);
763 if (streams[i].fd == NULL) {
764 errstr = newvstrallocf(errstr,
765 _("[could not connect %s stream: %s]"),
766 streams[i].name, security_geterror(sech));
771 * Authenticate the streams
773 for (i = 0; i < NSTREAMS; i++) {
774 if (streams[i].fd == NULL)
776 if (security_stream_auth(streams[i].fd) < 0) {
777 errstr = newvstrallocf(errstr,
778 _("[could not authenticate %s stream: %s]"),
779 streams[i].name, security_stream_geterror(streams[i].fd));
785 * The MESGFD and DATAFD streams are mandatory. If we didn't get
788 if (streams[MESGFD].fd == NULL) {
789 errstr = newvstrallocf(errstr, _("[couldn't open MESG streams]"));
793 /* everything worked */
799 errstr = newvstrallocf(errstr,
800 _("[parse of reply message failed: %s]"),
801 extra ? extra : _("(no additional information)"));
812 * This is called when everything needs to shut down so event_loop()
821 for (i = 0; i < NSTREAMS; i++) {
822 if (streams[i].fd != NULL) {
823 security_stream_close(streams[i].fd);
824 streams[i].fd = NULL;