Imported Upstream version 3.1.0
[debian/amanda] / recover-src / amrecover.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998, 2000 University of Maryland at College Park
4  * All Rights Reserved.
5  *
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.
15  *
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.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: amrecover.c,v 1.73 2006/07/25 18:27:57 martinea Exp $
28  *
29  * an interactive program for recovering backed-up files
30  */
31
32 #include "amanda.h"
33 #include "stream.h"
34 #include "amfeatures.h"
35 #include "amrecover.h"
36 #include "getfsent.h"
37 #include "dgram.h"
38 #include "util.h"
39 #include "conffile.h"
40 #include "protocol.h"
41 #include "event.h"
42 #include "security.h"
43 #include "conffile.h"
44
45 #define amrecover_debug(i, ...) do {    \
46         if ((i) <= debug_amrecover) {   \
47             dbprintf(__VA_ARGS__);      \
48         }                               \
49 } while (0)
50
51 extern int process_line(char *line);
52 int get_line(void);
53 int grab_reply(int show);
54 void sigint_handler(int signum);
55 int main(int argc, char **argv);
56
57 #define USAGE _("Usage: amrecover [[-C] <config>] [-s <index-server>] [-t <tape-server>] [-d <tape-device>] [-o <clientconfigoption>]*\n")
58
59 char *server_name = NULL;
60 int server_socket;
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;
79 char *authopt;
80 int amindexd_alive = 0;
81
82 static struct {
83     const char *name;
84     security_stream_t *fd;
85 } streams[] = {
86 #define MESGFD  0
87     { "MESG", NULL },
88 };
89 #define NSTREAMS        (int)(sizeof(streams) / sizeof(streams[0]))
90
91 static void amindexd_response(void *, pkt_t *, security_handle_t *);
92 void stop_amindexd(void);
93
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 */
98
99 int
100 get_line(void)
101 {
102     ssize_t size;
103     char *newbuf, *s;
104     void *buf;
105
106     if (!mesg_buffer)
107         mesg_buffer = stralloc("");
108  
109     while (!strstr(mesg_buffer,"\r\n")) {
110         buf = NULL;
111         size = security_stream_read_sync(streams[MESGFD].fd, &buf);
112         if(size < 0) {
113             amrecover_debug(1, "amrecover: get_line size < 0 (%zd)\n", size);
114             return -1;
115         }
116         else if(size == 0) {
117             amrecover_debug(1, "amrecover: get_line size == 0 (%zd)\n", size);
118             return -1;
119         }
120         else if (buf == NULL) {
121             amrecover_debug(1, "amrecover: get_line buf == NULL\n");
122             return -1;
123         }
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';
129         amfree(mesg_buffer);
130         mesg_buffer = newbuf;
131         amfree(buf);
132     }
133
134     s = strstr(mesg_buffer,"\r\n");
135     *s = '\0';
136     newbuf = stralloc(s+2);
137     server_line = newstralloc(server_line, mesg_buffer);
138     amfree(mesg_buffer);
139     mesg_buffer = newbuf;
140     amrecover_debug(1, "get: %s\n", mesg_buffer);
141     return 0;
142 }
143
144
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            */
152 int
153 grab_reply(
154     int show)
155 {
156     do {
157         if (get_line() == -1) {
158             return -1;
159         }
160         if (show || server_line[0] == '5') {
161             puts(server_line);
162         }
163     } while (server_line[3] == '-');
164     if(show) fflush(stdout);
165
166     return 0;
167 }
168
169
170 /* get 1 line of reply */
171 /* returns -1 if error, 0 if last (or only) line, 1 if more to follow */
172 int
173 get_reply_line(void)
174 {
175     if (get_line() == -1)
176         return -1;
177     return server_line[3] == '-';
178 }
179
180
181 /* returns pointer to returned line */
182 char *
183 reply_line(void)
184 {
185     return server_line;
186 }
187
188
189
190 /* returns 0 if server returned an error code (ie code starting with 5)
191    and non-zero otherwise */
192 int
193 server_happy(void)
194 {
195     return server_line[0] != '5';
196 }
197
198
199 int
200 send_command(
201     char *      cmd)
202 {
203     /*
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.
208      */
209     char *buffer;
210
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';
216
217     g_debug("sending: %s\n", buffer);
218     if(security_stream_write(streams[MESGFD].fd, buffer, strlen(buffer)) < 0) {
219         return -1;
220     }
221     amfree(buffer);
222     return (0);
223 }
224
225
226 /* send a command to the server, get reply and print to screen */
227 int
228 converse(
229     char *      cmd)
230 {
231     if (send_command(cmd) == -1) return -1;
232     if (grab_reply(1) == -1) return -1;
233     return 0;
234 }
235
236
237 /* same as converse() but reply not echoed to stdout */
238 int
239 exchange(
240     char *      cmd)
241 {
242     if (send_command(cmd) == -1) return -1;
243     if (grab_reply(0) == -1) return -1;
244     return 0;
245 }
246
247
248 /* basic interrupt handler for when user presses ^C */
249 /* Bale out, letting server know before doing so */
250 void
251 sigint_handler(
252     int signum)
253 {
254     /*
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.
260      */
261     (void)signum;       /* Quiet unused parameter warning */
262
263     if (extract_restore_child_pid != -1)
264         (void)kill(extract_restore_child_pid, SIGKILL);
265     extract_restore_child_pid = -1;
266
267     if(amindexd_alive) 
268         (void)send_command("QUIT");
269
270     _exit(1);
271 }
272
273
274 void
275 clean_pathname(
276     char *      s)
277 {
278     size_t length;
279     length = strlen(s);
280
281     /* remove "/" at end of path */
282     if(length>1 && s[length-1]=='/')
283         s[length-1]='\0';
284
285     /* change "/." to "/" */
286     if(strcmp(s,"/.")==0)
287         s[1]='\0';
288
289     /* remove "/." at end of path */
290     if(strcmp(&(s[length-2]),"/.")==0)
291         s[length-2]='\0';
292 }
293
294
295 void
296 quit(void)
297 {
298     quit_prog = 1;
299     (void)converse("QUIT");
300     stop_amindexd();
301 }
302
303 char *localhost = NULL;
304
305 #ifdef DEFAULT_TAPE_SERVER
306 # define DEFAULT_TAPE_SERVER_FAILOVER (DEFAULT_TAPE_SERVER)
307 #else
308 # define DEFAULT_TAPE_SERVER_FAILOVER (NULL)
309 #endif
310
311 int
312 main(
313     int         argc,
314     char **     argv)
315 {
316     int i;
317     time_t timer;
318     char *lineread = NULL;
319     struct sigaction act, oact;
320     extern char *optarg;
321     extern int optind;
322     char *line = NULL;
323     const security_driver_t *secdrv;
324     char *req = NULL;
325     int response_error;
326     struct tm *tm;
327     config_overrides_t *cfg_ovr;
328
329     /*
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.
334      */  
335     setlocale(LC_MESSAGES, "C");
336     textdomain("amanda"); 
337
338     safe_fd(-1, 0);
339
340     set_pname("amrecover");
341
342     /* Don't die when child closes pipe */
343     signal(SIGPIPE, SIG_IGN);
344
345     dbopen(DBG_SUBDIR_CLIENT);
346
347     localhost = alloc(MAX_HOSTNAME_LENGTH+1);
348     if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) {
349         error(_("cannot determine local host name\n"));
350         /*NOTREACHED*/
351     }
352     localhost[MAX_HOSTNAME_LENGTH] = '\0';
353
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);
357
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]);
363
364         /* remove that option from the command line */
365         argv[1] = argv[0];
366         argv++; argc--;
367     }
368
369     /* now parse regular command-line '-' options */
370     while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) {
371         switch (i) {
372             case 'C':
373                 add_config_override(cfg_ovr, "conf", optarg);
374                 break;
375
376             case 's':
377                 add_config_override(cfg_ovr, "index_server", optarg);
378                 break;
379
380             case 't':
381                 add_config_override(cfg_ovr, "tape_server", optarg);
382                 break;
383
384             case 'd':
385                 add_config_override(cfg_ovr, "tapedev", optarg);
386                 break;
387
388             case 'o':
389                 add_config_override_opt(cfg_ovr, optarg);
390                 break;
391
392             case 'U':
393             case '?':
394                 (void)g_printf(USAGE);
395                 return 0;
396         }
397     }
398     if (optind != argc) {
399         (void)g_fprintf(stderr, USAGE);
400         exit(1);
401     }
402
403     /* load the base client configuration */
404     set_config_overrides(cfg_ovr);
405     config_init(CONFIG_INIT_CLIENT, NULL);
406
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"));
411         }
412     }
413
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));
417
418     check_running_as(RUNNING_AS_ROOT);
419
420     dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
421
422     our_features = am_init_feature_set();
423     our_features_string = am_feature_to_string(our_features);
424
425     server_name = NULL;
426     if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
427         server_name = getconf_str(CNF_INDEX_SERVER);
428     }
429     if (!server_name) {
430         server_name = getenv("AMANDA_SERVER");
431         if (server_name) {
432             g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
433         }
434     }
435     if (!server_name) {
436         server_name = getconf_str(CNF_INDEX_SERVER);
437     }
438     if (!server_name) {
439         error(_("No index server set"));
440         /*NOTREACHED*/
441     }
442     server_name = stralloc(server_name);
443
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);
447     }
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);
454             }
455         } else {
456             g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
457         }
458     }
459     if (!tape_server_name) {
460         tape_server_name = getconf_str(CNF_TAPE_SERVER);
461     }
462     if (!tape_server_name) {
463         error(_("No tape server set"));
464         /*NOTREACHED*/
465     }
466     tape_server_name = stralloc(tape_server_name);
467
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;
474     } else {
475         tape_device_name = stralloc(tape_device_name);
476     }
477
478     authopt = stralloc(getconf_str(CNF_AUTH));
479
480
481     amfree(disk_name);
482     amfree(mount_point);
483     amfree(disk_path);
484     dump_date[0] = '\0';
485
486     /* Don't die when child closes pipe */
487     signal(SIGPIPE, SIG_IGN);
488
489     /* set up signal handler */
490     act.sa_handler = sigint_handler;
491     sigemptyset(&act.sa_mask);
492     act.sa_flags = 0;
493     if (sigaction(SIGINT, &act, &oact) != 0) {
494         error(_("error setting signal handler: %s"), strerror(errno));
495         /*NOTREACHED*/
496     }
497
498     proplist = g_hash_table_new_full(g_str_hash, g_str_equal, &g_free, &free_property_t);
499
500     protocol_init();
501
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);
508
509     secdrv = security_getdriver(authopt);
510     if (secdrv == NULL) {
511         error(_("no '%s' security driver available for host '%s'"),
512             authopt, server_name);
513         /*NOTREACHED*/
514     }
515
516     protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
517                      req, STARTUP_TIMEOUT, amindexd_response, &response_error);
518
519     amfree(req);
520     protocol_run();
521
522     g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
523            VERSION, server_name);
524
525     if(response_error != 0) {
526         g_fprintf(stderr,"%s\n",errstr);
527         exit(1);
528     }
529
530     /* get server's banner */
531     if (grab_reply(1) == -1) {
532         aclose(server_socket);
533         exit(1);
534     }
535     if (!server_happy()) {
536         dbclose();
537         aclose(server_socket);
538         exit(1);
539     }
540
541     /* try to get the features from the server */
542     {
543         char *their_feature_string = NULL;
544
545         indexsrv_features = NULL;
546
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);
553         }
554         if (!indexsrv_features)
555             indexsrv_features = am_set_default_feature_set();
556
557         amfree(their_feature_string);
558         amfree(line);
559     }
560
561     /* set the date of extraction to be today */
562     (void)time(&timer);
563     tm = localtime(&timer);
564     if (tm) 
565         strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
566     else
567         error(_("BAD DATE"));
568
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);
573         exit(1);
574     }
575     amfree(line);
576
577     line = vstrallocf("SCNF %s", get_config_name());
578     if (converse(line) == -1) {
579         aclose(server_socket);
580         exit(1);
581     }
582     amfree(line);
583
584     if (server_happy()) {
585         /* set host we are restoring to this host by default */
586         amfree(dump_hostname);
587         set_host(localhost);
588         if (dump_hostname)
589             g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
590         else
591             g_printf(_("Use the sethost command to choose a host to recover\n"));
592
593     }
594
595     quit_prog = 0;
596     do {
597         if ((lineread = readline("amrecover> ")) == NULL) {
598             clearerr(stdin);
599             putchar('\n');
600             break;
601         }
602         if (lineread[0] != '\0') 
603         {
604             add_history(lineread);
605             dbprintf(_("user command: '%s'\n"), lineread);
606             process_line(lineread);     /* act on line's content */
607         }
608         amfree(lineread);
609     } while (!quit_prog);
610
611     dbclose();
612
613     aclose(server_socket);
614     return 0;
615 }
616
617 static void
618 amindexd_response(
619     void *datap,
620     pkt_t *pkt,
621     security_handle_t *sech)
622 {
623     int ports[NSTREAMS], *response_error = datap, i;
624     char *p;
625     char *tok;
626     char *extra = NULL;
627
628     assert(response_error != NULL);
629     assert(sech != NULL);
630
631     if (pkt == NULL) {
632         errstr = newvstrallocf(errstr, _("[request failed: %s]"),
633                              security_geterror(sech));
634         *response_error = 1;
635         return;
636     }
637
638     if (pkt->type == P_NAK) {
639 #if defined(PACKET_DEBUG)
640         dbprintf(_("got nak response:\n----\n%s\n----\n\n"), pkt->body);
641 #endif
642
643         tok = strtok(pkt->body, " ");
644         if (tok == NULL || strcmp(tok, "ERROR") != 0)
645             goto bad_nak;
646
647         tok = strtok(NULL, "\n");
648         if (tok != NULL) {
649             errstr = newvstrallocf(errstr, "NAK: %s", tok);
650             *response_error = 1;
651         } else {
652 bad_nak:
653             errstr = newvstrallocf(errstr, _("request NAK"));
654             *response_error = 2;
655         }
656         return;
657     }
658
659     if (pkt->type != P_REP) {
660         errstr = newvstrallocf(errstr, _("received strange packet type %s: %s"),
661                               pkt_type2str(pkt->type), pkt->body);
662         *response_error = 1;
663         return;
664     }
665
666 #if defined(PACKET_DEBUG)
667     g_fprintf(stderr, _("got response:\n----\n%s\n----\n\n"), pkt->body);
668 #endif
669
670     for(i = 0; i < NSTREAMS; i++) {
671         ports[i] = -1;
672         streams[i].fd = NULL;
673     }
674
675     p = pkt->body;
676     while((tok = strtok(p, " \n")) != NULL) {
677         p = NULL;
678
679         /*
680          * Error response packets have "ERROR" followed by the error message
681          * followed by a newline.
682          */
683         if (strcmp(tok, "ERROR") == 0) {
684             tok = strtok(NULL, "\n");
685             if (tok == NULL) {
686                 errstr = newvstrallocf(errstr, _("[bogus error packet]"));
687             } else {
688                 errstr = newvstrallocf(errstr, "%s", tok);
689             }
690             *response_error = 2;
691             return;
692         }
693
694
695         /*
696          * Regular packets have CONNECT followed by three streams
697          */
698         if (strcmp(tok, "CONNECT") == 0) {
699
700             /*
701              * Parse the three stream specifiers out of the packet.
702              */
703             for (i = 0; i < NSTREAMS; i++) {
704                 tok = strtok(NULL, " ");
705                 if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
706                     extra = vstrallocf(
707                            _("CONNECT token is \"%s\": expected \"%s\""),
708                            tok ? tok : _("(null)"), streams[i].name);
709                     goto parse_error;
710                 }
711                 tok = strtok(NULL, " \n");
712                 if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
713                     extra = vstrallocf(
714                            _("CONNECT %s token is \"%s\" expected a port number"),
715                            streams[i].name, tok ? tok : _("(null)"));
716                     goto parse_error;
717                 }
718             }
719             continue;
720         }
721
722         /*
723          * OPTIONS [options string] '\n'
724          */
725         if (strcmp(tok, "OPTIONS") == 0) {
726             tok = strtok(NULL, "\n");
727             if (tok == NULL) {
728                 extra = vstrallocf(_("OPTIONS token is missing"));
729                 goto parse_error;
730             }
731 #if 0
732             tok_end = tok + strlen(tok);
733             while((p = strchr(tok, ';')) != NULL) {
734                 *p++ = '\0';
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"),
741                                       tok);
742                         goto parse_error;
743                     }
744                 }
745                 tok = p;
746             }
747 #endif
748             continue;
749         }
750 #if 0
751         extra = vstrallocf(_("next token is \"%s\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\""), tok ? tok : _("(null)"));
752         goto parse_error;
753 #endif
754     }
755
756     /*
757      * Connect the streams to their remote ports
758      */
759     for (i = 0; i < NSTREAMS; i++) {
760 /*@i@*/ if (ports[i] == -1)
761             continue;
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));
767             goto connect_error;
768         }
769     }
770     /*
771      * Authenticate the streams
772      */
773     for (i = 0; i < NSTREAMS; i++) {
774         if (streams[i].fd == NULL)
775             continue;
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));
780             goto connect_error;
781         }
782     }
783
784     /*
785      * The MESGFD and DATAFD streams are mandatory.  If we didn't get
786      * them, complain.
787      */
788     if (streams[MESGFD].fd == NULL) {
789         errstr = newvstrallocf(errstr, _("[couldn't open MESG streams]"));
790         goto connect_error;
791     }
792
793     /* everything worked */
794     *response_error = 0;
795     amindexd_alive = 1;
796     return;
797
798 parse_error:
799     errstr = newvstrallocf(errstr,
800                           _("[parse of reply message failed: %s]"),
801                           extra ? extra : _("(no additional information)"));
802     amfree(extra);
803     *response_error = 2;
804     return;
805
806 connect_error:
807     stop_amindexd();
808     *response_error = 1;
809 }
810
811 /*
812  * This is called when everything needs to shut down so event_loop()
813  * will exit.
814  */
815 void
816 stop_amindexd(void)
817 {
818     int i;
819
820     amindexd_alive = 0;
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;
825         }
826     }
827 }