Imported Upstream version 2.6.1p1
[debian/amanda] / amandad-src / amandad.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1999 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 /*
28  * $Id: amandad.c,v 1.18 2006/08/21 20:17:09 martinea Exp $
29  *
30  * handle client-host side of Amanda network communications, including
31  * security checks, execution of the proper service, and acking the
32  * master side
33  */
34
35 #include "amanda.h"
36 #include "amandad.h"
37 #include "clock.h"
38 #include "event.h"
39 #include "amfeatures.h"
40 #include "packet.h"
41 #include "version.h"
42 #include "queue.h"
43 #include "security.h"
44 #include "stream.h"
45 #include "util.h"
46 #include "conffile.h"
47
48 #define REP_TIMEOUT     (6*60*60)       /* secs for service to reply */
49 #define ACK_TIMEOUT     10              /* XXX should be configurable */
50 #define STDERR_PIPE (DATA_FD_COUNT + 1)
51
52 #define amandad_debug(i, ...) do {      \
53         if ((i) <= debug_amandad) {     \
54                 dbprintf(__VA_ARGS__);  \
55         }                               \
56 } while (0)
57
58 /*
59  * These are the actions for entering the state machine
60  */
61 typedef enum { A_START, A_RECVPKT, A_RECVREP, A_PENDING, A_FINISH, A_CONTINUE,
62     A_SENDNAK, A_TIMEOUT } action_t;
63
64 /*
65  * This is a state in the state machine.  It is a function pointer to
66  * the function that actually implements the state.
67  */
68 struct active_service;
69 typedef action_t (*state_t)(struct active_service *, action_t, pkt_t *);
70
71 /* string that we scan for in sendbackup's MESG stream */
72 static const char info_end_str[] = "sendbackup: info end\n";
73 #define INFO_END_LEN (sizeof(info_end_str)-1)
74
75 /* 
76  * Here are the services that we allow.
77  * Must be in the same order as services[].
78  */
79 typedef enum {
80     SERVICE_NOOP,
81     SERVICE_SENDSIZE,
82     SERVICE_SENDBACKUP,
83     SERVICE_SELFCHECK,
84     SERVICE_AMINDEXD,
85     SERVICE_AMIDXTAPED
86 } service_t;
87
88 static struct services {
89     char *name;
90     int  active;
91     service_t service;
92 } services[] = {
93    { "noop", 1, SERVICE_NOOP },
94    { "sendsize", 1, SERVICE_SENDSIZE },
95    { "sendbackup", 1, SERVICE_SENDBACKUP },
96    { "selfcheck", 1, SERVICE_SELFCHECK },
97    { "amindexd", 0, SERVICE_AMINDEXD },
98    { "amidxtaped", 0, SERVICE_AMIDXTAPED }
99 };
100 #define NSERVICES       (int)(sizeof(services) / sizeof(services[0]))
101
102 /*
103  * This structure describes an active running service.
104  *
105  * An active service is something running that we have received
106  * a request for.  This structure holds info on that service, including
107  * file descriptors for data, etc, as well as the security handle
108  * for communications with the amanda server.
109  */
110 struct active_service {
111     service_t service;                  /* service name */
112     char *cmd;                          /* name of command we ran */
113     char *arguments;                    /* arguments we sent it */
114     security_handle_t *security_handle; /* remote server */
115     state_t state;                      /* how far this has progressed */
116     pid_t pid;                          /* pid of subprocess */
117     int send_partial_reply;             /* send PREP packet */
118     int reqfd;                          /* pipe to write requests */
119     int repfd;                          /* pipe to read replies */
120     int errfd;                          /* pipe to read stderr */
121     event_handle_t *ev_repfd;           /* read event handle for repfd */
122     event_handle_t *ev_reptimeout;      /* timeout for rep data */
123     event_handle_t *ev_errfd;           /* read event handle for errfd */
124     pkt_t rep_pkt;                      /* rep packet we're sending out */
125     char *errbuf;                       /* buffer to read the err into */
126     char *repbuf;                       /* buffer to read the rep into */
127     size_t bufsize;                     /* length of repbuf */
128     size_t repbufsize;                  /* length of repbuf */
129     int repretry;                       /* times we'll retry sending the rep */
130     int seen_info_end;                  /* have we seen "sendbackup info end\n"? */
131     char info_end_buf[INFO_END_LEN];    /* last few bytes read, used for scanning for info end */
132
133     /*
134      * General user streams to the process, and their equivalent
135      * network streams.
136      */
137     struct datafd_handle {
138         int fd_read;                    /* pipe to child process */
139         int fd_write;                   /* pipe to child process */
140         event_handle_t *ev_read;        /* it's read event handle */
141         event_handle_t *ev_write;       /* it's write event handle */
142         security_stream_t *netfd;       /* stream to amanda server */
143         struct active_service *as;      /* pointer back to our enclosure */
144     } data[DATA_FD_COUNT];
145     char databuf[NETWORK_BLOCK_BYTES];  /* buffer to relay netfd data in */
146     TAILQ_ENTRY(active_service) tq;     /* queue handle */
147 };
148
149 /*
150  * Queue of outstanding requests that we are running.
151  */
152 static struct {
153     TAILQ_HEAD(, active_service) tailq;
154     int qlength;
155 } serviceq = {
156     TAILQ_HEAD_INITIALIZER(serviceq.tailq), 0
157 };
158
159 static int wait_30s = 1;
160 static int exit_on_qlength = 1;
161 static char *auth = NULL;
162 static kencrypt_type amandad_kencrypt = KENCRYPT_NONE;
163
164 int main(int argc, char **argv);
165
166 static int allocstream(struct active_service *, int);
167 static void exit_check(void *);
168 static void protocol_accept(security_handle_t *, pkt_t *);
169 static void state_machine(struct active_service *, action_t, pkt_t *);
170
171 static action_t s_sendack(struct active_service *, action_t, pkt_t *);
172 static action_t s_repwait(struct active_service *, action_t, pkt_t *);
173 static action_t s_processrep(struct active_service *, action_t, pkt_t *);
174 static action_t s_sendrep(struct active_service *, action_t, pkt_t *);
175 static action_t s_ackwait(struct active_service *, action_t, pkt_t *);
176
177 static void repfd_recv(void *);
178 static void errfd_recv(void *);
179 static void timeout_repfd(void *);
180 static void protocol_recv(void *, pkt_t *, security_status_t);
181 static void process_readnetfd(void *);
182 static void process_writenetfd(void *, void *, ssize_t);
183 static struct active_service *service_new(security_handle_t *,
184     const char *, service_t, const char *);
185 static void service_delete(struct active_service *);
186 static int writebuf(struct active_service *, const void *, size_t);
187 static ssize_t do_sendpkt(security_handle_t *handle, pkt_t *pkt);
188 static char *amandad_get_security_conf (char *, void *);
189
190 static const char *state2str(state_t);
191 static const char *action2str(action_t);
192
193 int
194 main(
195     int         argc,
196     char **     argv)
197 {
198     int i, j;
199     int have_services;
200     int in, out;
201     const security_driver_t *secdrv;
202     int no_exit = 0;
203     char *pgm = "amandad";              /* in case argv[0] is not set */
204 #if defined(USE_REUSEADDR)
205     const int on = 1;
206     int r;
207 #endif
208
209     /*
210      * Configure program for internationalization:
211      *   1) Only set the message locale for now.
212      *   2) Set textdomain for all amanda related programs to "amanda"
213      *      We don't want to be forced to support dozens of message catalogs.
214      */  
215     setlocale(LC_MESSAGES, "C");
216     textdomain("amanda"); 
217
218     safe_fd(-1, 0);
219     safe_cd();
220
221     /*
222      * When called via inetd, it is not uncommon to forget to put the
223      * argv[0] value on the config line.  On some systems (e.g. Solaris)
224      * this causes argv and/or argv[0] to be NULL, so we have to be
225      * careful getting our name.
226      */
227     if ((argv == NULL) || (argv[0] == NULL)) {
228             pgm = "amandad";            /* in case argv[0] is not set */
229     } else {
230             pgm = basename(argv[0]);    /* Strip of leading path get debug name */
231     }
232     set_pname(pgm);
233     dbopen(DBG_SUBDIR_AMANDAD);
234
235     if(argv == NULL) {
236         error(_("argv == NULL\n"));
237         /*NOTREACHED*/
238     }
239
240     /* Don't die when child closes pipe */
241     signal(SIGPIPE, SIG_IGN);
242
243     /* Parse the configuration; we'll handle errors later */
244     config_init(CONFIG_INIT_CLIENT, NULL);
245
246     if (geteuid() == 0) {
247         check_running_as(RUNNING_AS_ROOT);
248         initgroups(CLIENT_LOGIN, get_client_gid());
249         setgid(get_client_gid());
250         setegid(get_client_gid());
251         seteuid(get_client_uid());
252     } else {
253         check_running_as(RUNNING_AS_CLIENT_LOGIN);
254     }
255
256     erroutput_type = (ERR_INTERACTIVE|ERR_SYSLOG);
257
258     /*
259      * ad-hoc argument parsing
260      *
261      * We accept        -auth=[authentication type]
262      *                  -no-exit
263      *                  -tcp=[port]
264      *                  -udp=[port]
265      * We also add a list of services that amandad can launch
266      */
267     secdrv = NULL;
268     in = 0; out = 1;            /* default to stdin/stdout */
269     have_services = 0;
270     for (i = 1; i < argc; i++) {
271         /*
272          * accept -krb4 as an alias for -auth=krb4 (for compatibility)
273          */
274         if (strcmp(argv[i], "-krb4") == 0) {
275             argv[i] = "-auth=krb4";
276             /* FALLTHROUGH */
277             auth = "krb4";
278         }
279
280         /*
281          * Get a driver for a security type specified after -auth=
282          */
283         else if (strncmp(argv[i], "-auth=", strlen("-auth=")) == 0) {
284             argv[i] += strlen("-auth=");
285             secdrv = security_getdriver(argv[i]);
286             auth = argv[i];
287             if (secdrv == NULL) {
288                 error(_("no driver for security type '%s'\n"), argv[i]);
289                 /*NOTREACHED*/
290             }
291             continue;
292         }
293
294         /*
295          * If -no-exit is specified, always run even after requests have
296          * been satisfied.
297          */
298         else if (strcmp(argv[i], "-no-exit") == 0) {
299             no_exit = 1;
300             continue;
301         }
302
303         /*
304          * Allow us to directly bind to a udp port for debugging.
305          * This may only apply to some security types.
306          */
307         else if (strncmp(argv[i], "-udp=", strlen("-udp=")) == 0) {
308 #ifdef WORKING_IPV6
309             struct sockaddr_in6 sin;
310 #else
311             struct sockaddr_in sin;
312 #endif
313
314             argv[i] += strlen("-udp=");
315 #ifdef WORKING_IPV6
316             in = out = socket(AF_INET6, SOCK_DGRAM, 0);
317 #else
318             in = out = socket(AF_INET, SOCK_DGRAM, 0);
319 #endif
320             if (in < 0) {
321                 error(_("can't create dgram socket: %s\n"), strerror(errno));
322                 /*NOTREACHED*/
323             }
324 #ifdef USE_REUSEADDR
325             r = setsockopt(in, SOL_SOCKET, SO_REUSEADDR,
326                 (void *)&on, (socklen_t_equiv)sizeof(on));
327             if (r < 0) {
328                 dbprintf(_("amandad: setsockopt(SO_REUSEADDR) failed: %s\n"),
329                           strerror(errno));
330             }
331 #endif
332
333 #ifdef WORKING_IPV6
334             sin.sin6_family = (sa_family_t)AF_INET6;
335             sin.sin6_addr = in6addr_any;
336             sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
337 #else
338             sin.sin_family = (sa_family_t)AF_INET;
339             sin.sin_addr.s_addr = INADDR_ANY;
340             sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
341 #endif
342             if (bind(in, (struct sockaddr *)&sin, (socklen_t_equiv)sizeof(sin)) < 0) {
343                 error(_("can't bind to port %d: %s\n"), atoi(argv[i]),
344                     strerror(errno));
345                 /*NOTREACHED*/
346             }
347         }
348         /*
349          * Ditto for tcp ports.
350          */
351         else if (strncmp(argv[i], "-tcp=", strlen("-tcp=")) == 0) {
352 #ifdef WORKING_IPV6
353             struct sockaddr_in6 sin;
354 #else
355             struct sockaddr_in sin;
356 #endif
357             int sock;
358             socklen_t_equiv n;
359
360             argv[i] += strlen("-tcp=");
361 #ifdef WORKING_IPV6
362             sock = socket(AF_INET6, SOCK_STREAM, 0);
363 #else
364             sock = socket(AF_INET, SOCK_STREAM, 0);
365 #endif
366             if (sock < 0) {
367                 error(_("can't create tcp socket: %s\n"), strerror(errno));
368                 /*NOTREACHED*/
369             }
370 #ifdef USE_REUSEADDR
371             r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
372                 (void *)&on, (socklen_t_equiv)sizeof(on));
373             if (r < 0) {
374                 dbprintf(_("amandad: setsockopt(SO_REUSEADDR) failed: %s\n"),
375                           strerror(errno));
376             }
377 #endif
378 #ifdef WORKING_IPV6
379             sin.sin6_family = (sa_family_t)AF_INET6;
380             sin.sin6_addr = in6addr_any;
381             sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
382 #else
383             sin.sin_family = (sa_family_t)AF_INET;
384             sin.sin_addr.s_addr = INADDR_ANY;
385             sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
386 #endif
387             if (bind(sock, (struct sockaddr *)&sin, (socklen_t_equiv)sizeof(sin)) < 0) {
388                 error(_("can't bind to port %d: %s\n"), atoi(argv[i]),
389                     strerror(errno));
390                 /*NOTREACHED*/
391             }
392             listen(sock, 10);
393             n = (socklen_t_equiv)sizeof(sin);
394             in = out = accept(sock, (struct sockaddr *)&sin, &n);
395         }
396         /*
397          * It must be a service name
398          */
399         else {
400             /* clear all services */
401             if(!have_services) {
402                 for (j = 0; j < (int)NSERVICES; j++)
403                     services[j].active = 0;
404             }
405             have_services = 1;
406
407             if(strcmp(argv[i],"amdump") == 0) {
408                 services[0].active = 1;
409                 services[1].active = 1;
410                 services[2].active = 1;
411                 services[3].active = 1;
412             }
413             else {
414                 for (j = 0; j < (int)NSERVICES; j++)
415                     if (strcmp(services[j].name, argv[i]) == 0)
416                         break;
417                 if (j == (int)NSERVICES) {
418                     dbprintf(_("%s: invalid service\n"), argv[i]);
419                     exit(1);
420                 }
421                 services[j].active = 1;
422             }
423         }
424     }
425
426     /*
427      * If no security type specified, use BSD
428      */
429     if (secdrv == NULL) {
430         secdrv = security_getdriver("BSD");
431         auth = "bsd";
432         if (secdrv == NULL) {
433             error(_("no driver for default security type 'BSD'\n"));
434             /*NOTREACHED*/
435         }
436     }
437
438     if(strcasecmp(auth, "rsh") == 0 ||
439        strcasecmp(auth, "ssh") == 0 ||
440        strcasecmp(auth, "local") == 0 ||
441        strcasecmp(auth, "bsdtcp") == 0) {
442         wait_30s = 0;
443         exit_on_qlength = 1;
444     }
445
446     if (getuid() == 0) {
447         if (strcasecmp(auth, "krb5") != 0) {
448             error(_("Amanda must be run as user '%s' when using '%s' authentication"),
449                   CLIENT_LOGIN, auth);
450         }
451     } else {
452         if (strcasecmp(auth, "krb5") == 0) {
453             error(_("Amanda must be run as user 'root' when using 'krb5' authentication"));
454         }
455     }
456
457
458     /* initialize */
459
460     startclock();
461
462     dbprintf(_("version %s\n"), version());
463     for (i = 0; version_info[i] != NULL; i++) {
464         dbprintf("    %s", version_info[i]);
465     }
466
467     if (! (argc >= 1 && argv != NULL && argv[0] != NULL)) {
468         dbprintf(_("WARNING: argv[0] not defined: check inetd.conf\n"));
469     }
470
471     /* krb5 require the euid to be 0 */
472     if (strcasecmp(auth, "krb5") == 0) {
473         seteuid((uid_t)0);
474     }
475
476     /*
477      * Schedule to call protocol_accept() when new security handles
478      * are created on stdin.
479      */
480     security_accept(secdrv, amandad_get_security_conf, in, out, protocol_accept, NULL);
481
482     /*
483      * Schedule an event that will try to exit every 30 seconds if there
484      * are no requests outstanding.
485      */
486     if(wait_30s)
487         (void)event_register((event_id_t)30, EV_TIME, exit_check, &no_exit);
488
489     /*
490      * Call event_loop() with an arg of 0, telling it to block until all
491      * events are completed.
492      */
493     event_loop(0);
494
495     close(in);
496     close(out);
497     dbclose();
498     return(0);
499 }
500
501 /*
502  * This runs periodically and checks to see if we have any active services
503  * still running.  If we don't, then we quit.
504  */
505 static void
506 exit_check(
507     void *      cookie)
508 {
509     int no_exit;
510
511     assert(cookie != NULL);
512     no_exit = *(int *)cookie;
513
514     /*
515      * If things are still running, then don't exit.
516      */
517     if (serviceq.qlength > 0)
518         return;
519
520     /*
521      * If the caller asked us to never exit, then we're done
522      */
523     if (no_exit)
524         return;
525
526     dbclose();
527     exit(0);
528 }
529
530 /*
531  * Handles new incoming protocol handles.  This is a callback for
532  * security_accept(), which gets called when new handles are detected.
533  */
534 static void
535 protocol_accept(
536     security_handle_t * handle,
537     pkt_t *             pkt)
538 {
539     pkt_t pkt_out;
540     struct active_service *as;
541     char *pktbody, *tok, *service, *arguments;
542     char *service_path = NULL;
543     GSList *errlist = NULL;
544     int i;
545
546     pkt_out.body = NULL;
547
548     /*
549      * If handle is NULL, then the connection is closed.
550      */
551     if(handle == NULL) {
552         return;
553     }
554
555     /*
556      * If we have errors (not warnings) from the config file, let the server
557      * know immediately.  Unfortunately, we only get one ERROR line, so if there
558      * are multiple errors, we just show the first.
559      */
560     if (config_errors(&errlist) >= CFGERR_ERRORS) {
561         GSList *iter = errlist;
562         char *errmsg;
563         gboolean multiple_errors = FALSE;
564
565         if (iter) {
566             errmsg = (char *)iter->data;
567             if (iter->next)
568                 multiple_errors = TRUE;
569         } else {
570             errmsg = "(no error message)";
571         }
572
573         pkt_init(&pkt_out, P_NAK, "ERROR %s%s", errmsg,
574             multiple_errors? _(" (additional errors not displayed)"):"");
575         do_sendpkt(handle, &pkt_out);
576         amfree(pkt_out.body);
577         security_close(handle);
578         return;
579     }
580
581     /*
582      * If pkt is NULL, then there was a problem with the new connection.
583      */
584     if (pkt == NULL) {
585         dbprintf(_("accept error: %s\n"), security_geterror(handle));
586         pkt_init(&pkt_out, P_NAK, "ERROR %s\n", security_geterror(handle));
587         do_sendpkt(handle, &pkt_out);
588         amfree(pkt_out.body);
589         security_close(handle);
590         return;
591     }
592
593     dbprintf(_("accept recv %s pkt:\n<<<<<\n%s>>>>>\n"),
594         pkt_type2str(pkt->type), pkt->body);
595
596     /*
597      * If this is not a REQ packet, just forget about it.
598      */
599     if (pkt->type != P_REQ) {
600         dbprintf(_("received unexpected %s packet:\n<<<<<\n%s>>>>>\n\n"),
601             pkt_type2str(pkt->type), pkt->body);
602         security_close(handle);
603         return;
604     }
605
606     pktbody = service = arguments = NULL;
607     as = NULL;
608
609     /*
610      * Parse out the service and arguments
611      */
612
613     pktbody = stralloc(pkt->body);
614
615     tok = strtok(pktbody, " ");
616     if (tok == NULL)
617         goto badreq;
618     if (strcmp(tok, "SERVICE") != 0)
619         goto badreq;
620
621     tok = strtok(NULL, " \n");
622     if (tok == NULL)
623         goto badreq;
624     service = stralloc(tok);
625
626     /* we call everything else 'arguments' */
627     tok = strtok(NULL, "");
628     if (tok == NULL)
629         goto badreq;
630     arguments = stralloc(tok);
631
632     /* see if it's one we allow */
633     for (i = 0; i < (int)NSERVICES; i++)
634         if (services[i].active == 1 && strcmp(services[i].name, service) == 0)
635             break;
636     if (i == (int)NSERVICES) {
637         dbprintf(_("%s: invalid service\n"), service);
638         pkt_init(&pkt_out, P_NAK, _("ERROR %s: invalid service, add '%s' as argument to amandad\n"), service, service);
639         goto send_pkt_out;
640     }
641
642     service_path = vstralloc(amlibexecdir, "/", service, versionsuffix(), NULL);
643     if (access(service_path, X_OK) < 0) {
644         dbprintf(_("can't execute %s: %s\n"), service_path, strerror(errno));
645             pkt_init(&pkt_out, P_NAK,
646                      _("ERROR execute access to \"%s\" denied\n"),
647                      service_path);
648         goto send_pkt_out;
649     }
650
651     /* see if its already running */
652     for (as = TAILQ_FIRST(&serviceq.tailq); as != NULL;
653         as = TAILQ_NEXT(as, tq)) {
654             if (strcmp(as->cmd, service_path) == 0 &&
655                 strcmp(as->arguments, arguments) == 0) {
656                     dbprintf(_("%s %s: already running, acking req\n"),
657                         service, arguments);
658                     pkt_init_empty(&pkt_out, P_ACK);
659                     goto send_pkt_out_no_delete;
660             }
661     }
662
663     /*
664      * create a new service instance, and send the arguments down
665      * the request pipe.
666      */
667     dbprintf(_("creating new service: %s\n%s\n"), service, arguments);
668     as = service_new(handle, service_path, services[i].service, arguments);
669     if (writebuf(as, arguments, strlen(arguments)) < 0) {
670         const char *errmsg = strerror(errno);
671         dbprintf(_("error sending arguments to %s: %s\n"), service, errmsg);
672         pkt_init(&pkt_out, P_NAK, _("ERROR error writing arguments to %s: %s\n"),
673             service, errmsg);
674         goto send_pkt_out;
675     }
676     aclose(as->reqfd);
677
678     amfree(pktbody);
679     amfree(service);
680     amfree(service_path);
681     amfree(arguments);
682
683     /*
684      * Move to the sendack state, and start up the state
685      * machine.
686      */
687     as->state = s_sendack;
688     state_machine(as, A_START, NULL);
689     return;
690
691 badreq:
692     pkt_init(&pkt_out, P_NAK, _("ERROR invalid REQ\n"));
693     dbprintf(_("received invalid %s packet:\n<<<<<\n%s>>>>>\n\n"),
694         pkt_type2str(pkt->type), pkt->body);
695
696 send_pkt_out:
697     if(as)
698         service_delete(as);
699 send_pkt_out_no_delete:
700     amfree(pktbody);
701     amfree(service_path);
702     amfree(service);
703     amfree(arguments);
704     do_sendpkt(handle, &pkt_out);
705     security_close(handle);
706     amfree(pkt_out.body);
707 }
708
709 /*
710  * Handles incoming protocol packets.  Routes responses to the proper
711  * running service.
712  */
713 static void
714 state_machine(
715     struct active_service *     as,
716     action_t                    action,
717     pkt_t *                     pkt)
718 {
719     action_t retaction;
720     state_t curstate;
721     pkt_t nak;
722
723     amandad_debug(1, _("state_machine: %p entering\n"), as);
724     for (;;) {
725         curstate = as->state;
726         amandad_debug(1, _("state_machine: %p curstate=%s action=%s\n"), as,
727                           state2str(curstate), action2str(action));
728         retaction = (*curstate)(as, action, pkt);
729         amandad_debug(1, _("state_machine: %p curstate=%s returned %s (nextstate=%s)\n"),
730                           as, state2str(curstate), action2str(retaction),
731                           state2str(as->state));
732
733         switch (retaction) {
734         /*
735          * State has queued up and is now blocking on input.
736          */
737         case A_PENDING:
738             amandad_debug(1, _("state_machine: %p leaving (A_PENDING)\n"), as);
739             return;
740
741         /*
742          * service has switched states.  Loop.
743          */
744         case A_CONTINUE:
745             break;
746
747         /*
748          * state has determined that the packet it received was bogus.
749          * Send a nak, and return.
750          */
751         case A_SENDNAK:
752             dbprintf(_("received unexpected %s packet\n"),
753                 pkt_type2str(pkt->type));
754             dbprintf(_("<<<<<\n%s----\n\n"), pkt->body);
755             pkt_init(&nak, P_NAK, _("ERROR unexpected packet type %s\n"),
756                 pkt_type2str(pkt->type));
757             do_sendpkt(as->security_handle, &nak);
758             amfree(nak.body);
759             security_recvpkt(as->security_handle, protocol_recv, as, -1);
760             amandad_debug(1, _("state_machine: %p leaving (A_SENDNAK)\n"), as);
761             return;
762
763         /*
764          * Service is done.  Remove it and finish.
765          */
766         case A_FINISH:
767             amandad_debug(1, _("state_machine: %p leaving (A_FINISH)\n"), as);
768             service_delete(as);
769             return;
770
771         default:
772             assert(0);
773             break;
774         }
775     }
776     /*NOTREACHED*/
777 }
778
779 /*
780  * This state just sends an ack.  After that, we move to the repwait
781  * state to wait for REP data to arrive from the subprocess.
782  */
783 static action_t
784 s_sendack(
785     struct active_service *     as,
786     action_t                    action,
787     pkt_t *                     pkt)
788 {
789     pkt_t ack;
790
791     (void)action;       /* Quiet unused parameter warning */
792     (void)pkt;          /* Quiet unused parameter warning */
793
794     pkt_init_empty(&ack, P_ACK);
795     if (do_sendpkt(as->security_handle, &ack) < 0) {
796         dbprintf(_("error sending ACK: %s\n"),
797             security_geterror(as->security_handle));
798         amfree(ack.body);
799         return (A_FINISH);
800     }
801     amfree(ack.body);
802
803     /*
804      * move to the repwait state
805      * Setup a listener for data on the reply fd, but also
806      * listen for packets over the wire, as the server may
807      * poll us if we take a long time.
808      * Setup a timeout that will fire if it takes too long to
809      * receive rep data.
810      */
811     as->state = s_repwait;
812     as->ev_repfd = event_register((event_id_t)as->repfd, EV_READFD, repfd_recv, as);
813     as->ev_reptimeout = event_register(REP_TIMEOUT, EV_TIME,
814         timeout_repfd, as);
815     as->errbuf = NULL;
816     as->ev_errfd = event_register((event_id_t)as->errfd, EV_READFD, errfd_recv, as);
817     security_recvpkt(as->security_handle, protocol_recv, as, -1);
818     return (A_PENDING);
819 }
820
821 /*
822  * This is the repwait state.  We have responded to the initial REQ with
823  * an ACK, and we are now waiting for the process we spawned to pass us 
824  * data to send in a REP.
825  */
826 static action_t
827 s_repwait(
828     struct active_service *     as,
829     action_t                    action,
830     pkt_t *                     pkt)
831 {
832     ssize_t   n;
833     char     *repbuf_temp;
834     char     *what;
835     char     *msg;
836     int       code = 0;
837     int       pid;
838     amwait_t  retstat;
839
840     /*
841      * We normally shouldn't receive any packets while waiting
842      * for our REP data, but in some cases we do.
843      */
844     if (action == A_RECVPKT) {
845         assert(pkt != NULL);
846         /*
847          * Another req for something that's running.  Just send an ACK
848          * and go back and wait for more data.
849          */
850         if (pkt->type == P_REQ) {
851             dbprintf(_("received dup P_REQ packet, ACKing it\n"));
852             amfree(as->rep_pkt.body);
853             pkt_init_empty(&as->rep_pkt, P_ACK);
854             do_sendpkt(as->security_handle, &as->rep_pkt);
855             security_recvpkt(as->security_handle, protocol_recv, as, -1);
856             return (A_PENDING);
857         }
858         /* something unexpected.  Nak it */
859         return (A_SENDNAK);
860     }
861
862     if (action == A_TIMEOUT) {
863         amfree(as->rep_pkt.body);
864         pkt_init(&as->rep_pkt, P_NAK, _("ERROR timeout on reply pipe\n"));
865         dbprintf(_("%s timed out waiting for REP data\n"), as->cmd);
866         do_sendpkt(as->security_handle, &as->rep_pkt);
867         return (A_FINISH);
868     }
869
870     assert(action == A_RECVREP);
871     if(as->bufsize == 0) {
872         as->bufsize = NETWORK_BLOCK_BYTES;
873         as->repbuf = alloc(as->bufsize);
874     }
875
876     do {
877         n = read(as->repfd, as->repbuf + as->repbufsize,
878                  as->bufsize - as->repbufsize - 1);
879     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
880     if (n < 0) {
881         const char *errstr = strerror(errno);
882         dbprintf(_("read error on reply pipe: %s\n"), errstr);
883         amfree(as->rep_pkt.body);
884         pkt_init(&as->rep_pkt, P_NAK, _("ERROR read error on reply pipe: %s\n"),
885                  errstr);
886         do_sendpkt(as->security_handle, &as->rep_pkt);
887         return (A_FINISH);
888     }
889
890     /* If end of service, wait for process status */
891     if (n == 0) {
892         pid = waitpid(as->pid, &retstat, WNOHANG);
893         if (as->service  == SERVICE_NOOP ||
894             as->service  == SERVICE_SENDSIZE ||
895             as->service  == SERVICE_SELFCHECK) {
896             int t = 0;
897             while (t<5 && pid == 0) {
898                 sleep(1);
899                 t++;
900                 pid = waitpid(as->pid, &retstat, WNOHANG);
901             }
902         }
903
904         /* Process errfd before sending the REP packet */
905         if (as->ev_errfd) {
906             SELECT_ARG_TYPE readset;
907             struct timeval  tv;
908             int             nfound;
909
910             memset(&tv, 0, SIZEOF(tv));
911             FD_ZERO(&readset);
912             FD_SET(as->errfd, &readset);
913             nfound = select(as->errfd+1, &readset, NULL, NULL, &tv);
914             if (nfound && FD_ISSET(as->errfd, &readset)) {
915                 errfd_recv(as);
916             }
917         }
918
919         if (pid == 0)
920             pid = waitpid(as->pid, &retstat, WNOHANG);
921
922         if (pid > 0) {
923             what = NULL;
924             if (! WIFEXITED(retstat)) {
925                 what = _("signal");
926                 code = WTERMSIG(retstat);
927             } else if (WEXITSTATUS(retstat) != 0) {
928                 what = _("code");
929                 code = WEXITSTATUS(retstat);
930             }
931             if (what) {
932                 dbprintf(_("service %s failed: pid %u exited with %s %d\n"),
933                          (as->cmd)?as->cmd:_("??UNKONWN??"),
934                          (unsigned)as->pid,
935                          what, code);
936                 msg = vstrallocf(
937                      _("ERROR service %s failed: pid %u exited with %s %d\n"),
938                      (as->cmd)?as->cmd:_("??UNKONWN??"), (unsigned)as->pid,
939                      what, code);
940                 if (as->repbufsize + strlen(msg) >= (as->bufsize - 1)) {
941                         as->bufsize *= 2;
942                         repbuf_temp = alloc(as->bufsize);
943                         memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
944                         amfree(as->repbuf);
945                         as->repbuf = repbuf_temp;
946                 }
947                 strcpy(as->repbuf + as->repbufsize, msg);
948                 as->repbufsize += strlen(msg);
949                 amfree(msg);
950             }
951         }
952     }
953
954     /*
955      * If we got some data, go back and wait for more, or EOF.  Nul terminate
956      * the buffer first.
957      */
958     as->repbuf[n + as->repbufsize] = '\0';
959     if (n > 0) {
960         as->repbufsize += n;
961         if(as->repbufsize >= (as->bufsize - 1)) {
962             as->bufsize *= 2;
963             repbuf_temp = alloc(as->bufsize);
964             memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
965             amfree(as->repbuf);
966             as->repbuf = repbuf_temp;
967         }
968         else if(as->send_partial_reply) {
969             amfree(as->rep_pkt.body);
970             pkt_init(&as->rep_pkt, P_PREP, "%s", as->repbuf);
971             do_sendpkt(as->security_handle, &as->rep_pkt);
972             amfree(as->rep_pkt.body);
973             pkt_init_empty(&as->rep_pkt, P_REP);
974         }
975  
976         return (A_PENDING);
977     }
978
979     /*
980      * If we got 0, then we hit EOF.  Process the data and release
981      * the timeout.
982      */
983     assert(n == 0);
984
985     assert(as->ev_repfd != NULL);
986     event_release(as->ev_repfd);
987     as->ev_repfd = NULL;
988
989     assert(as->ev_reptimeout != NULL);
990     event_release(as->ev_reptimeout);
991     as->ev_reptimeout = NULL;
992
993     as->state = s_processrep;
994     aclose(as->repfd);
995     return (A_CONTINUE);
996 }
997
998 /*
999  * After we have read in all of the rep data, we process it and send
1000  * it out as a REP packet.
1001  */
1002 static action_t
1003 s_processrep(
1004     struct active_service *     as,
1005     action_t                    action,
1006     pkt_t *                     pkt)
1007 {
1008     char *tok, *repbuf;
1009
1010     (void)action;       /* Quiet unused parameter warning */
1011     (void)pkt;          /* Quiet unused parameter warning */
1012
1013     /*
1014      * Copy the rep lines into the outgoing packet.
1015      *
1016      * If this line is a CONNECT, translate it
1017      * Format is "CONNECT <tag> <handle> <tag> <handle> etc...
1018      * Example:
1019      *
1020      *  CONNECT DATA 4 MESG 5 INDEX 6
1021      *
1022      * The tags are arbitrary.  The handles are in the DATA_FD pool.
1023      * We need to map these to security streams and pass them back
1024      * to the amanda server.  If the handle is -1, then we don't map.
1025      */
1026     if (strncmp_const(as->repbuf,"KENCRYPT\n") == 0) {
1027         amandad_kencrypt = KENCRYPT_WILL_DO;
1028         repbuf = stralloc(as->repbuf + 9);
1029     } else {
1030         repbuf = stralloc(as->repbuf);
1031     }
1032     amfree(as->rep_pkt.body);
1033     pkt_init_empty(&as->rep_pkt, P_REP);
1034     tok = strtok(repbuf, " ");
1035     if (tok == NULL)
1036         goto error;
1037     if (strcmp(tok, "CONNECT") == 0) {
1038         char *line, *nextbuf;
1039
1040         /* Save the entire line */
1041         line = strtok(NULL, "\n");
1042         /* Save the buf following the line */
1043         nextbuf = strtok(NULL, "");
1044
1045         if (line == NULL || nextbuf == NULL)
1046             goto error;
1047
1048         pkt_cat(&as->rep_pkt, "CONNECT");
1049
1050         /* loop over the id/handle pairs */
1051         for (;;) {
1052             /* id */
1053             tok = strtok(line, " ");
1054             line = NULL;        /* keep working from line */
1055             if (tok == NULL)
1056                 break;
1057             pkt_cat(&as->rep_pkt, " %s", tok);
1058
1059             /* handle */
1060             tok = strtok(NULL, " \n");
1061             if (tok == NULL)
1062                 goto error;
1063             /* convert the handle into something the server can process */
1064             pkt_cat(&as->rep_pkt, " %d", allocstream(as, atoi(tok)));
1065         }
1066         pkt_cat(&as->rep_pkt, "\n%s", nextbuf);
1067     } else {
1068 error:
1069         pkt_cat(&as->rep_pkt, "%s", as->repbuf);
1070     }
1071
1072     /*
1073      * We've setup our REP packet in as->rep_pkt.  Now move to the transmission
1074      * state.
1075      */
1076     as->state = s_sendrep;
1077     as->repretry = getconf_int(CNF_REP_TRIES);
1078     amfree(repbuf);
1079     return (A_CONTINUE);
1080 }
1081
1082 /*
1083  * This is the state where we send the REP we just collected from our child.
1084  */
1085 static action_t
1086 s_sendrep(
1087     struct active_service *     as,
1088     action_t                    action,
1089     pkt_t *                     pkt)
1090 {
1091     (void)action;       /* Quiet unused parameter warning */
1092     (void)pkt;          /* Quiet unused parameter warning */
1093
1094     /*
1095      * Transmit it and move to the ack state.
1096      */
1097     do_sendpkt(as->security_handle, &as->rep_pkt);
1098     security_recvpkt(as->security_handle, protocol_recv, as, ACK_TIMEOUT);
1099     as->state = s_ackwait;
1100     return (A_PENDING);
1101 }
1102
1103 /*
1104  * This is the state in which we wait for the server to ACK the REP
1105  * we just sent it.
1106  */
1107 static action_t
1108 s_ackwait(
1109     struct active_service *     as,
1110     action_t                    action,
1111     pkt_t *                     pkt)
1112 {
1113     struct datafd_handle *dh;
1114     int npipes;
1115
1116     /*
1117      * If we got a timeout, try again, but eventually give up.
1118      */
1119     if (action == A_TIMEOUT) {
1120         if (--as->repretry > 0) {
1121             as->state = s_sendrep;
1122             return (A_CONTINUE);
1123         }
1124         dbprintf(_("timeout waiting for ACK for our REP\n"));
1125         return (A_FINISH);
1126     }
1127     amandad_debug(1, _("received ACK, now opening streams\n"));
1128
1129     assert(action == A_RECVPKT);
1130
1131     if (pkt->type == P_REQ) {
1132         dbprintf(_("received dup P_REQ packet, resending REP\n"));
1133         as->state = s_sendrep;
1134         return (A_CONTINUE);
1135     }
1136
1137     if (pkt->type != P_ACK)
1138         return (A_SENDNAK);
1139
1140     if (amandad_kencrypt == KENCRYPT_WILL_DO) {
1141         amandad_kencrypt = KENCRYPT_YES;
1142     }
1143
1144     /*
1145      * Got the ack, now open the pipes
1146      */
1147     for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1148         if (dh->netfd == NULL)
1149             continue;
1150         if (security_stream_accept(dh->netfd) < 0) {
1151             dbprintf(_("stream %td accept failed: %s\n"),
1152                 dh - &as->data[0], security_geterror(as->security_handle));
1153             security_stream_close(dh->netfd);
1154             dh->netfd = NULL;
1155             continue;
1156         }
1157
1158         /* setup an event for reads from it.  As a special case, don't start
1159          * listening on as->data[0] until we read some data on another fd, if
1160          * the service is sendbackup.  This ensures that we send a MESG or 
1161          * INDEX token before any DATA tokens, as dumper assumes. This is a
1162          * hack, if that wasn't already obvious! */
1163         if (dh != &as->data[0] || as->service != SERVICE_SENDBACKUP) {
1164             dh->ev_read = event_register((event_id_t)dh->fd_read, EV_READFD,
1165                                          process_readnetfd, dh);
1166         } else {
1167             amandad_debug(1, "Skipping registration of sendbackup's data FD\n");
1168         }
1169
1170         security_stream_read(dh->netfd, process_writenetfd, dh);
1171
1172     }
1173
1174     /*
1175      * Pipes are open, so auth them.  Count them at the same time.
1176      */
1177     for (npipes = 0, dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1178         if (dh->netfd == NULL)
1179             continue;
1180         if (security_stream_auth(dh->netfd) < 0) {
1181             security_stream_close(dh->netfd);
1182             dh->netfd = NULL;
1183             event_release(dh->ev_read);
1184             event_release(dh->ev_write);
1185             dh->ev_read = NULL;
1186             dh->ev_write = NULL;
1187         } else {
1188             npipes++;
1189         }
1190     }
1191
1192     /*
1193      * If no pipes are open, then we're done.  Otherwise, just start running.
1194      * The event handlers on all of the pipes will take it from here.
1195      */
1196     amandad_debug(1, _("at end of s_ackwait, npipes is %d\n"), npipes);
1197     if (npipes == 0)
1198         return (A_FINISH);
1199     else {
1200         security_close(as->security_handle);
1201         as->security_handle = NULL;
1202         return (A_PENDING);
1203     }
1204 }
1205
1206 /*
1207  * Called when a repfd has received data
1208  */
1209 static void
1210 repfd_recv(
1211     void *      cookie)
1212 {
1213     struct active_service *as = cookie;
1214
1215     assert(as != NULL);
1216     assert(as->ev_repfd != NULL);
1217
1218     state_machine(as, A_RECVREP, NULL);
1219 }
1220
1221 /*
1222  * Called when a errfd has received data
1223  */
1224 static void
1225 errfd_recv(
1226     void *      cookie)
1227 {
1228     struct active_service *as = cookie;
1229     char  buf[32769];
1230     int   n;
1231     char *r;
1232
1233     assert(as != NULL);
1234     assert(as->ev_errfd != NULL);
1235
1236     n = read(as->errfd, &buf, 32768);
1237     /* merge buffer */
1238     if (n > 0) {
1239         /* Terminate it with '\0' */
1240         buf[n+1] = '\0';
1241
1242         if (as->errbuf) {
1243             as->errbuf = vstrextend(&as->errbuf, buf, NULL);
1244         } else {
1245             as->errbuf = stralloc(buf);
1246         }
1247     } else if (n == 0) {
1248         event_release(as->ev_errfd);
1249         as->ev_errfd = NULL;
1250     } else { /* n < 0 */
1251         event_release(as->ev_errfd);
1252         as->ev_errfd = NULL;
1253         g_snprintf(buf, 32768,
1254                    "error reading stderr or service: %s\n", strerror(errno));
1255     }
1256
1257     /* for each line terminate by '\n' */
1258     while (as->errbuf != NULL  && (r = strchr(as->errbuf, '\n')) != NULL) {
1259         char *s;
1260
1261         *r = '\0';
1262         s = vstrallocf("ERROR service %s: %s\n",
1263                        services[as->service].name, as->errbuf);
1264
1265         /* Add to repbuf, error message will be in the REP packet if it
1266          * is not already sent
1267          */
1268         n = strlen(s);
1269         if (as->bufsize == 0) {
1270             as->bufsize = NETWORK_BLOCK_BYTES;
1271             as->repbuf = alloc(as->bufsize);
1272         }
1273         while (as->bufsize < as->repbufsize + n) {
1274             char *repbuf_temp;
1275             as->bufsize *= 2;
1276             repbuf_temp = alloc(as->bufsize);
1277             memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
1278             amfree(as->repbuf);
1279             as->repbuf = repbuf_temp;
1280         }
1281         memcpy(as->repbuf + as->repbufsize, s, n);
1282         as->repbufsize += n;
1283
1284         dbprintf("%s", s);
1285
1286         /* remove first line from buffer */
1287         r++;
1288         s = stralloc(r);
1289         amfree(as->errbuf);
1290         as->errbuf = s;
1291     }
1292 }
1293
1294 /*
1295  * Called when a repfd has timed out
1296  */
1297 static void
1298 timeout_repfd(
1299     void *      cookie)
1300 {
1301     struct active_service *as = cookie;
1302
1303     assert(as != NULL);
1304     assert(as->ev_reptimeout != NULL);
1305
1306     state_machine(as, A_TIMEOUT, NULL);
1307 }
1308
1309 /*
1310  * Called when a handle has received data
1311  */
1312 static void
1313 protocol_recv(
1314     void *              cookie,
1315     pkt_t *             pkt,
1316     security_status_t   status)
1317 {
1318     struct active_service *as = cookie;
1319
1320     assert(as != NULL);
1321
1322     switch (status) {
1323     case S_OK:
1324         dbprintf(_("received %s pkt:\n<<<<<\n%s>>>>>\n"),
1325             pkt_type2str(pkt->type), pkt->body);
1326         state_machine(as, A_RECVPKT, pkt);
1327         break;
1328     case S_TIMEOUT:
1329         dbprintf(_("timeout\n"));
1330         state_machine(as, A_TIMEOUT, NULL);
1331         break;
1332     case S_ERROR:
1333         dbprintf(_("receive error: %s\n"),
1334             security_geterror(as->security_handle));
1335         break;
1336     }
1337 }
1338
1339 /*
1340  * This is a generic relay function that just reads data from one of
1341  * the process's pipes and passes it up the equivalent security_stream_t
1342  */
1343 static void
1344 process_readnetfd(
1345     void *      cookie)
1346 {
1347     pkt_t nak;
1348     struct datafd_handle *dh = cookie;
1349     struct active_service *as = dh->as;
1350     ssize_t n;
1351
1352     nak.body = NULL;
1353
1354     do {
1355         n = read(dh->fd_read, as->databuf, SIZEOF(as->databuf));
1356     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
1357
1358     /*
1359      * Process has died.
1360      */
1361     if (n < 0) {
1362         pkt_init(&nak, P_NAK, _("A ERROR data descriptor %d broken: %s\n"),
1363             dh->fd_read, strerror(errno));
1364         goto sendnak;
1365     }
1366     /*
1367      * Process has closed the pipe.  Just remove this event handler.
1368      * If all pipes are closed, shut down this service.
1369      */
1370     if (n == 0) {
1371         event_release(dh->ev_read);
1372         dh->ev_read = NULL;
1373         if(dh->ev_write == NULL) {
1374             security_stream_close(dh->netfd);
1375             dh->netfd = NULL;
1376         }
1377         for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1378             if (dh->netfd != NULL)
1379                 return;
1380         }
1381         service_delete(as);
1382         return;
1383     }
1384
1385     /* Handle the special case of recognizing "sendbackup info end"
1386      * from sendbackup's MESG fd */
1387     if (as->service == SERVICE_SENDBACKUP && !as->seen_info_end && dh == &as->data[1]) {
1388         /* make a buffer containing the combined data from info_end_buf
1389          * and what we've read this time, and search it for info_end_strj
1390          * This includes a NULL byte for strstr's sanity. */
1391         char *combined_buf = malloc(INFO_END_LEN + n + 1);
1392         memcpy(combined_buf, as->info_end_buf, INFO_END_LEN);
1393         memcpy(combined_buf+INFO_END_LEN, as->databuf, n);
1394         combined_buf[INFO_END_LEN+n] = '\0';
1395
1396         as->seen_info_end = (strstr(combined_buf, info_end_str) != NULL);
1397
1398         /* fill info_end_buf from the tail end of combined_buf */
1399         memcpy(as->info_end_buf, combined_buf + n, INFO_END_LEN);
1400
1401         /* if we did see info_end_str, start reading the data fd (fd 0) */
1402         if (as->seen_info_end) {
1403             struct datafd_handle *dh = &as->data[0];
1404             amandad_debug(1, "Opening datafd to sendbackup (delayed until sendbackup sent header info)\n");
1405             dh->ev_read = event_register((event_id_t)dh->fd_read, EV_READFD,
1406                                          process_readnetfd, dh);
1407         } else {
1408             amandad_debug(1, "sendbackup header info still not complete\n");
1409         }
1410     }
1411
1412     if (security_stream_write(dh->netfd, as->databuf, (size_t)n) < 0) {
1413         /* stream has croaked */
1414         pkt_init(&nak, P_NAK, _("ERROR write error on stream %d: %s\n"),
1415             security_stream_id(dh->netfd),
1416             security_stream_geterror(dh->netfd));
1417         goto sendnak;
1418     }
1419     return;
1420
1421 sendnak:
1422     do_sendpkt(as->security_handle, &nak);
1423     service_delete(as);
1424     amfree(nak.body);
1425 }
1426
1427 /*
1428  * This is a generic relay function that just read data from one of
1429  * the security_stream_t and passes it up the equivalent process's pipes
1430  */
1431 static void
1432 process_writenetfd(
1433     void *      cookie,
1434     void *      buf,
1435     ssize_t     size)
1436 {
1437     struct datafd_handle *dh;
1438
1439     assert(cookie != NULL);
1440     dh = cookie;
1441
1442     if (dh->fd_write <= 0) {
1443         dbprintf(_("process_writenetfd: dh->fd_write <= 0\n"));
1444     } else if (size > 0) {
1445         full_write(dh->fd_write, buf, (size_t)size);
1446         security_stream_read(dh->netfd, process_writenetfd, dh);
1447     }
1448     else {
1449         aclose(dh->fd_write);
1450     }
1451 }
1452
1453
1454 /*
1455  * Convert a local stream handle (DATA_FD...) into something that
1456  * can be sent to the amanda server.
1457  *
1458  * Returns a number that should be sent to the server in the REP packet.
1459  */
1460 static int
1461 allocstream(
1462     struct active_service *     as,
1463     int                         handle)
1464 {
1465     struct datafd_handle *dh;
1466
1467     /* if the handle is -1, then we don't bother */
1468     if (handle < 0)
1469         return (-1);
1470
1471     /* make sure the handle's kosher */
1472     if (handle < DATA_FD_OFFSET || handle >= DATA_FD_OFFSET + DATA_FD_COUNT)
1473         return (-1);
1474
1475     /* get a pointer into our handle array */
1476     dh = &as->data[handle - DATA_FD_OFFSET];
1477
1478     /* make sure we're not already using the net handle */
1479     if (dh->netfd != NULL)
1480         return (-1);
1481
1482     /* allocate a stream from the security layer and return */
1483     dh->netfd = security_stream_server(as->security_handle);
1484     if (dh->netfd == NULL) {
1485         dbprintf(_("couldn't open stream to server: %s\n"),
1486             security_geterror(as->security_handle));
1487         return (-1);
1488     }
1489
1490     /*
1491      * convert the stream into a numeric id that can be sent to the
1492      * remote end.
1493      */
1494     return (security_stream_id(dh->netfd));
1495 }
1496
1497 /*
1498  * Create a new service instance
1499  */
1500 static struct active_service *
1501 service_new(
1502     security_handle_t * security_handle,
1503     const char *        cmd,
1504     service_t           service,
1505     const char *        arguments)
1506 {
1507     int i;
1508     int data_read[DATA_FD_COUNT + 2][2];
1509     int data_write[DATA_FD_COUNT + 2][2];
1510     struct active_service *as;
1511     pid_t pid;
1512     int newfd;
1513
1514     assert(security_handle != NULL);
1515     assert(cmd != NULL);
1516     assert(arguments != NULL);
1517
1518     /* a plethora of pipes */
1519     /* data_read[0]                : stdin
1520      * data_write[0]               : stdout
1521      * data_read[1], data_write[1] : first  stream
1522      * data_read[2], data_write[2] : second stream
1523      * data_read[3], data_write[3] : third stream
1524      * data_write[4]               : stderr
1525      */
1526     for (i = 0; i < DATA_FD_COUNT + 1; i++) {
1527         if (pipe(data_read[i]) < 0) {
1528             error(_("pipe: %s\n"), strerror(errno));
1529             /*NOTREACHED*/
1530         }
1531         if (pipe(data_write[i]) < 0) {
1532             error(_("pipe: %s\n"), strerror(errno));
1533             /*NOTREACHED*/
1534         }
1535     }
1536     if (pipe(data_write[STDERR_PIPE]) < 0) {
1537         error(_("pipe: %s\n"), strerror(errno));
1538         /*NOTREACHED*/
1539     }
1540
1541     switch(pid = fork()) {
1542     case -1:
1543         error(_("could not fork service %s: %s\n"), cmd, strerror(errno));
1544         /*NOTREACHED*/
1545     default:
1546         /*
1547          * The parent.  Close the far ends of our pipes and return.
1548          */
1549         as = g_new0(struct active_service, 1);
1550         as->cmd = stralloc(cmd);
1551         as->arguments = stralloc(arguments);
1552         as->security_handle = security_handle;
1553         as->state = NULL;
1554         as->service = service;
1555         as->pid = pid;
1556         as->send_partial_reply = 0;
1557         as->seen_info_end = FALSE;
1558         /* fill in info_end_buf with non-null characters */
1559         memset(as->info_end_buf, '-', sizeof(as->info_end_buf));
1560         if(service == SERVICE_SENDSIZE) {
1561             g_option_t *g_options;
1562             char *option_str, *p;
1563
1564             option_str = stralloc(as->arguments+8);
1565             p = strchr(option_str,'\n');
1566             if(p) *p = '\0';
1567
1568             g_options = parse_g_options(option_str, 1);
1569             if(am_has_feature(g_options->features, fe_partial_estimate)) {
1570                 as->send_partial_reply = 1;
1571             }
1572             free_g_options(g_options);
1573             amfree(option_str);
1574         }
1575
1576         /* write to the request pipe */
1577         aclose(data_read[0][0]);
1578         as->reqfd = data_read[0][1];
1579
1580         /*
1581          * read from the reply pipe
1582          */
1583         as->repfd = data_write[0][0];
1584         aclose(data_write[0][1]);
1585         as->ev_repfd = NULL;
1586         as->repbuf = NULL;
1587         as->repbufsize = 0;
1588         as->bufsize = 0;
1589         as->repretry = 0;
1590         as->rep_pkt.body = NULL;
1591
1592         /*
1593          * read from the stderr pipe
1594          */
1595         as->errfd = data_write[STDERR_PIPE][0];
1596         aclose(data_write[STDERR_PIPE][1]);
1597         as->ev_errfd = NULL;
1598         as->errbuf = NULL;
1599
1600         /*
1601          * read from the rest of the general-use pipes
1602          * (netfds are opened as the client requests them)
1603          */
1604         for (i = 0; i < DATA_FD_COUNT; i++) {
1605             aclose(data_read[i + 1][1]);
1606             aclose(data_write[i + 1][0]);
1607             as->data[i].fd_read = data_read[i + 1][0];
1608             as->data[i].fd_write = data_write[i + 1][1];
1609             as->data[i].ev_read = NULL;
1610             as->data[i].ev_write = NULL;
1611             as->data[i].netfd = NULL;
1612             as->data[i].as = as;
1613         }
1614
1615         /* add it to the service queue */
1616         /* increment the active service count */
1617         TAILQ_INSERT_TAIL(&serviceq.tailq, as, tq);
1618         serviceq.qlength++;
1619
1620         return (as);
1621     case 0:
1622         /*
1623          * The child.  Put our pipes in their advertised locations
1624          * and start up.
1625          */
1626
1627         /*
1628          * The data stream is stdin in the new process
1629          */
1630         if (dup2(data_read[0][0], 0) < 0) {
1631             error(_("dup %d to %d failed: %s\n"), data_read[0][0], 0,
1632                 strerror(errno));
1633             /*NOTREACHED*/
1634         }
1635         aclose(data_read[0][0]);
1636         aclose(data_read[0][1]);
1637
1638         /*
1639          * The reply stream is stdout
1640          */
1641         if (dup2(data_write[0][1], 1) < 0) {
1642             error(_("dup %d to %d failed: %s\n"), data_write[0][1], 1,
1643                 strerror(errno));
1644         }
1645         aclose(data_write[0][0]);
1646         aclose(data_write[0][1]);
1647
1648         for (i = 0; i < DATA_FD_COUNT; i++) {
1649             aclose(data_read[i + 1][0]);
1650             aclose(data_write[i + 1][1]);
1651         }
1652
1653         /*
1654          *  Make sure they are not open in the range DATA_FD_OFFSET to
1655          *      DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1
1656          */
1657         for (i = 0; i < DATA_FD_COUNT; i++) {
1658             while(data_read[i + 1][1] >= DATA_FD_OFFSET &&
1659                   data_read[i + 1][1] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1660                 newfd = dup(data_read[i + 1][1]);
1661                 if(newfd == -1)
1662                     error(_("Can't dup out off DATA_FD range"));
1663                 data_read[i + 1][1] = newfd;
1664             }
1665             while(data_write[i + 1][0] >= DATA_FD_OFFSET &&
1666                   data_write[i + 1][0] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1667                 newfd = dup(data_write[i + 1][0]);
1668                 if(newfd == -1)
1669                     error(_("Can't dup out off DATA_FD range"));
1670                 data_write[i + 1][0] = newfd;
1671             }
1672         }
1673         for (i = 0; i < DATA_FD_COUNT*2; i++)
1674             close(DATA_FD_OFFSET + i);
1675
1676         /*
1677          * The rest start at the offset defined in amandad.h, and continue
1678          * through the internal defined.
1679          */
1680         for (i = 0; i < DATA_FD_COUNT; i++) {
1681             if (dup2(data_read[i + 1][1], i*2 + DATA_FD_OFFSET) < 0) {
1682                 error(_("dup %d to %d failed: %s\n"), data_read[i + 1][1],
1683                     i + DATA_FD_OFFSET, strerror(errno));
1684             }
1685             aclose(data_read[i + 1][1]);
1686
1687             if (dup2(data_write[i + 1][0], i*2 + 1 + DATA_FD_OFFSET) < 0) {
1688                 error(_("dup %d to %d failed: %s\n"), data_write[i + 1][0],
1689                     i + DATA_FD_OFFSET, strerror(errno));
1690             }
1691             aclose(data_write[i + 1][0]);
1692         }
1693
1694         /* close all unneeded fd */
1695         close(STDERR_FILENO);
1696         dup2(data_write[STDERR_PIPE][1], 2);
1697         aclose(data_write[STDERR_PIPE][0]);
1698         aclose(data_write[STDERR_PIPE][1]);
1699         safe_fd(DATA_FD_OFFSET, DATA_FD_COUNT*2);
1700
1701         execle(cmd, cmd, "amandad", auth, (char *)NULL, safe_env());
1702         error(_("could not exec service %s: %s\n"), cmd, strerror(errno));
1703         /*NOTREACHED*/
1704     }
1705     return NULL;
1706 }
1707
1708 /*
1709  * Unallocate a service instance
1710  */
1711 static void
1712 service_delete(
1713     struct active_service *     as)
1714 {
1715     int i;
1716     struct datafd_handle *dh;
1717
1718     amandad_debug(1, _("closing service: %s\n"),
1719                       (as->cmd)?as->cmd:_("??UNKONWN??"));
1720
1721     assert(as != NULL);
1722
1723     assert(as->cmd != NULL);
1724     amfree(as->cmd);
1725
1726     assert(as->arguments != NULL);
1727     amfree(as->arguments);
1728
1729     if (as->reqfd != -1)
1730         aclose(as->reqfd);
1731     if (as->repfd != -1)
1732         aclose(as->repfd);
1733
1734     if (as->ev_repfd != NULL)
1735         event_release(as->ev_repfd);
1736     if (as->ev_reptimeout != NULL)
1737         event_release(as->ev_reptimeout);
1738
1739     for (i = 0; i < DATA_FD_COUNT; i++) {
1740         dh = &as->data[i];
1741
1742         aclose(dh->fd_read);
1743         aclose(dh->fd_write);
1744
1745         if (dh->netfd != NULL)
1746             security_stream_close(dh->netfd);
1747
1748         if (dh->ev_read != NULL)
1749             event_release(dh->ev_read);
1750         if (dh->ev_write != NULL)
1751             event_release(dh->ev_write);
1752     }
1753
1754     if (as->security_handle != NULL)
1755         security_close(as->security_handle);
1756
1757     assert(as->pid > 0);
1758     kill(as->pid, SIGTERM);
1759     waitpid(as->pid, NULL, WNOHANG);
1760
1761     TAILQ_REMOVE(&serviceq.tailq, as, tq);
1762     assert(serviceq.qlength > 0);
1763     serviceq.qlength--;
1764
1765     amfree(as->cmd);
1766     amfree(as->arguments);
1767     amfree(as->repbuf);
1768     amfree(as->rep_pkt.body);
1769     amfree(as);
1770
1771     if(exit_on_qlength == 0 && serviceq.qlength == 0) {
1772         dbclose();
1773         exit(0);
1774     }
1775 }
1776
1777 /*
1778  * Like 'fullwrite', but does the work in a child process so pipelines
1779  * do not hang.
1780  */
1781 static int
1782 writebuf(
1783     struct active_service *     as,
1784     const void *                bufp,
1785     size_t                      size)
1786 {
1787     pid_t pid;
1788     size_t    writesize;
1789
1790     switch (pid=fork()) {
1791     case -1:
1792         break;
1793
1794     default:
1795         waitpid(pid, NULL, WNOHANG);
1796         return 0;                       /* this is the parent */
1797
1798     case 0:                             /* this is the child */
1799         close(as->repfd);
1800         writesize = full_write(as->reqfd, bufp, size);
1801         exit(writesize != size);
1802         /* NOTREACHED */
1803     }
1804     return -1;
1805 }
1806
1807 static ssize_t
1808 do_sendpkt(
1809     security_handle_t * handle,
1810     pkt_t *             pkt)
1811 {
1812     dbprintf(_("sending %s pkt:\n<<<<<\n%s>>>>>\n"),
1813         pkt_type2str(pkt->type), pkt->body);
1814     if (handle)
1815         return security_sendpkt(handle, pkt);
1816     else
1817         return 1;
1818 }
1819
1820 /*
1821  * Convert a state into a string
1822  */
1823 static const char *
1824 state2str(
1825     state_t     state)
1826 {
1827     static const struct {
1828         state_t state;
1829         const char str[13];
1830     } states[] = {
1831 #define X(state)        { state, stringize(state) }
1832         X(s_sendack),
1833         X(s_repwait),
1834         X(s_processrep),
1835         X(s_sendrep),
1836         X(s_ackwait),
1837 #undef X
1838     };
1839     int i;
1840
1841     for (i = 0; i < (int)(sizeof(states) / sizeof(states[0])); i++)
1842         if (state == states[i].state)
1843             return (states[i].str);
1844     return (_("INVALID STATE"));
1845 }
1846
1847 /*
1848  * Convert an action into a string
1849  */
1850 static const char *
1851 action2str(
1852     action_t    action)
1853 {
1854     static const struct {
1855         action_t action;
1856         const char str[12];
1857     } actions[] = {
1858 #define X(action)       { action, stringize(action) }
1859         X(A_START),
1860         X(A_RECVPKT),
1861         X(A_RECVREP),
1862         X(A_PENDING),
1863         X(A_FINISH),
1864         X(A_CONTINUE),
1865         X(A_SENDNAK),
1866         X(A_TIMEOUT),
1867 #undef X
1868     };
1869     int i;
1870
1871     for (i = 0; i < (int)(sizeof(actions) / sizeof(actions[0])); i++)
1872         if (action == actions[i].action)
1873             return (actions[i].str);
1874     return (_("UNKNOWN ACTION"));
1875 }
1876
1877 static char *
1878 amandad_get_security_conf(
1879     char *      string,
1880     void *      arg)
1881 {
1882     (void)arg;      /* Quiet unused parameter warning */
1883
1884     if (!string || !*string)
1885         return(NULL);
1886
1887     if (strcmp(string, "kencrypt")==0) {
1888         if (amandad_kencrypt == KENCRYPT_YES)
1889             return ("yes");
1890         else
1891             return (NULL);
1892     }
1893     return(NULL);
1894 }
1895