2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1991-1999 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.
28 * $Id: amandad.c,v 1.18 2006/08/21 20:17:09 martinea Exp $
30 * handle client-host side of Amanda network communications, including
31 * security checks, execution of the proper service, and acking the
39 #include "amfeatures.h"
48 #define REP_TIMEOUT (6*60*60) /* secs for service to reply */
49 #define ACK_TIMEOUT 10 /* XXX should be configurable */
51 #define amandad_debug(i,x) do { \
52 if ((i) <= debug_amandad) { \
58 * These are the actions for entering the state machine
60 typedef enum { A_START, A_RECVPKT, A_RECVREP, A_PENDING, A_FINISH, A_CONTINUE,
61 A_SENDNAK, A_TIMEOUT } action_t;
64 * This is a state in the state machine. It is a function pointer to
65 * the function that actually implements the state.
67 struct active_service;
68 typedef action_t (*state_t)(struct active_service *, action_t, pkt_t *);
71 * This structure describes an active running service.
73 * An active service is something running that we have received
74 * a request for. This structure holds info on that service, including
75 * file descriptors for data, etc, as well as the security handle
76 * for communications with the amanda server.
78 struct active_service {
79 char *cmd; /* name of command we ran */
80 char *arguments; /* arguments we sent it */
81 security_handle_t *security_handle; /* remote server */
82 state_t state; /* how far this has progressed */
83 pid_t pid; /* pid of subprocess */
84 int send_partial_reply; /* send PREP packet */
85 int reqfd; /* pipe to write requests */
86 int repfd; /* pipe to read replies */
87 event_handle_t *ev_repfd; /* read event handle for repfd */
88 event_handle_t *ev_reptimeout; /* timeout for rep data */
89 pkt_t rep_pkt; /* rep packet we're sending out */
90 char *repbuf; /* buffer to read the rep into */
91 size_t bufsize; /* length of repbuf */
92 size_t repbufsize; /* length of repbuf */
93 int repretry; /* times we'll retry sending the rep */
95 * General user streams to the process, and their equivalent
98 struct datafd_handle {
99 int fd_read; /* pipe to child process */
100 int fd_write; /* pipe to child process */
101 event_handle_t *ev_read; /* it's read event handle */
102 event_handle_t *ev_write; /* it's write event handle */
103 security_stream_t *netfd; /* stream to amanda server */
104 struct active_service *as; /* pointer back to our enclosure */
105 } data[DATA_FD_COUNT];
106 char databuf[NETWORK_BLOCK_BYTES]; /* buffer to relay netfd data in */
107 TAILQ_ENTRY(active_service) tq; /* queue handle */
111 * Here are the services that we allow.
113 static struct services {
124 #define NSERVICES (int)(sizeof(services) / sizeof(services[0]))
127 * Queue of outstanding requests that we are running.
130 TAILQ_HEAD(, active_service) tailq;
133 TAILQ_HEAD_INITIALIZER(serviceq.tailq), 0
137 * Data for dbmalloc to check for memory leaks
142 unsigned long size, hist;
147 static int wait_30s = 1;
148 static int exit_on_qlength = 1;
149 static char *auth = NULL;
151 int main(int argc, char **argv);
153 static int allocstream(struct active_service *, int);
154 static void exit_check(void *);
155 static void protocol_accept(security_handle_t *, pkt_t *);
156 static void state_machine(struct active_service *, action_t, pkt_t *);
158 static action_t s_sendack(struct active_service *, action_t, pkt_t *);
159 static action_t s_repwait(struct active_service *, action_t, pkt_t *);
160 static action_t s_processrep(struct active_service *, action_t, pkt_t *);
161 static action_t s_sendrep(struct active_service *, action_t, pkt_t *);
162 static action_t s_ackwait(struct active_service *, action_t, pkt_t *);
164 static void repfd_recv(void *);
165 static void timeout_repfd(void *);
166 static void protocol_recv(void *, pkt_t *, security_status_t);
167 static void process_readnetfd(void *);
168 static void process_writenetfd(void *, void *, ssize_t);
169 static struct active_service *service_new(security_handle_t *,
170 const char *, const char *);
171 static void service_delete(struct active_service *);
172 static int writebuf(struct active_service *, const void *, size_t);
173 static ssize_t do_sendpkt(security_handle_t *handle, pkt_t *pkt);
175 static void child_signal(int signal);
177 static const char *state2str(state_t);
178 static const char *action2str(action_t);
181 * Harvests defunct processes...
190 (void)signal; /* Quite compiler warning */
192 * Reap and child status and promptly ignore since we don't care...
195 rp = waitpid(-1, NULL, WNOHANG);
207 const security_driver_t *secdrv;
209 struct sigaction act, oact;
210 char *pgm = "amandad"; /* in case argv[0] is not set */
211 #if defined(USE_REUSEADDR)
221 * When called via inetd, it is not uncommon to forget to put the
222 * argv[0] value on the config line. On some systems (e.g. Solaris)
223 * this causes argv and/or argv[0] to be NULL, so we have to be
224 * careful getting our name.
226 if ((argv == NULL) || (argv[0] == NULL)) {
227 pgm = "amandad"; /* in case argv[0] is not set */
229 pgm = basename(argv[0]); /* Strip of leading path get debug name */
232 dbopen(DBG_SUBDIR_AMANDAD);
235 error("argv == NULL\n");
239 /* Don't die when child closes pipe */
240 signal(SIGPIPE, SIG_IGN);
242 /* Tell me when a child exits or dies... */
243 act.sa_handler = child_signal;
244 sigemptyset(&act.sa_mask);
246 if(sigaction(SIGCHLD, &act, &oact) != 0) {
247 error("error setting SIGCHLD handler: %s", strerror(errno));
251 conffile = vstralloc(CONFIG_DIR, "/", "amanda-client.conf", NULL);
252 if (read_clientconf(conffile) > 0) {
253 error("error reading conffile: %s", conffile);
259 dbmalloc_info.start.size = malloc_inuse(&dbmalloc_info.start.hist);
262 erroutput_type = (ERR_INTERACTIVE|ERR_SYSLOG);
265 /* we'd rather not run as root */
266 if (geteuid() == 0) {
267 if(client_uid == (uid_t) -1) {
268 error("error [cannot find user %s in passwd file]\n", CLIENT_LOGIN);
271 initgroups(CLIENT_LOGIN, client_gid);
276 #endif /* FORCE_USERID */
279 * ad-hoc argument parsing
281 * We accept -auth=[authentication type]
285 * We also add a list of services that amandad can launch
288 in = 0; out = 1; /* default to stdin/stdout */
290 for (i = 1; i < argc; i++) {
292 * accept -krb4 as an alias for -auth=krb4 (for compatibility)
294 if (strcmp(argv[i], "-krb4") == 0) {
295 argv[i] = "-auth=krb4";
301 * Get a driver for a security type specified after -auth=
303 else if (strncmp(argv[i], "-auth=", strlen("-auth=")) == 0) {
304 argv[i] += strlen("-auth=");
305 secdrv = security_getdriver(argv[i]);
307 if (secdrv == NULL) {
308 error("no driver for security type '%s'\n", argv[i]);
315 * If -no-exit is specified, always run even after requests have
318 else if (strcmp(argv[i], "-no-exit") == 0) {
324 * Allow us to directly bind to a udp port for debugging.
325 * This may only apply to some security types.
327 else if (strncmp(argv[i], "-udp=", strlen("-udp=")) == 0) {
329 struct sockaddr_in6 sin;
331 struct sockaddr_in sin;
334 argv[i] += strlen("-udp=");
336 in = out = socket(AF_INET6, SOCK_DGRAM, 0);
338 in = out = socket(AF_INET, SOCK_DGRAM, 0);
341 error("can't create dgram socket: %s\n", strerror(errno));
345 r = setsockopt(in, SOL_SOCKET, SO_REUSEADDR,
346 (void *)&on, (socklen_t)sizeof(on));
348 dbprintf(("%s: amandad: setsockopt(SO_REUSEADDR) failed: %s\n",
349 debug_prefix_time(NULL),
355 sin.sin6_family = (sa_family_t)AF_INET6;
356 sin.sin6_addr = in6addr_any;
357 sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
359 sin.sin_family = (sa_family_t)AF_INET;
360 sin.sin_addr.s_addr = INADDR_ANY;
361 sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
363 if (bind(in, (struct sockaddr *)&sin, (socklen_t)sizeof(sin)) < 0) {
364 error("can't bind to port %d: %s\n", atoi(argv[i]),
370 * Ditto for tcp ports.
372 else if (strncmp(argv[i], "-tcp=", strlen("-tcp=")) == 0) {
374 struct sockaddr_in6 sin;
376 struct sockaddr_in sin;
381 argv[i] += strlen("-tcp=");
383 sock = socket(AF_INET6, SOCK_STREAM, 0);
385 sock = socket(AF_INET, SOCK_STREAM, 0);
388 error("can't create tcp socket: %s\n", strerror(errno));
392 r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
393 (void *)&on, (socklen_t)sizeof(on));
395 dbprintf(("%s: amandad: setsockopt(SO_REUSEADDR) failed: %s\n",
396 debug_prefix_time(NULL),
401 sin.sin6_family = (sa_family_t)AF_INET6;
402 sin.sin6_addr = in6addr_any;
403 sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
405 sin.sin_family = (sa_family_t)AF_INET;
406 sin.sin_addr.s_addr = INADDR_ANY;
407 sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
409 if (bind(sock, (struct sockaddr *)&sin, (socklen_t)sizeof(sin)) < 0) {
410 error("can't bind to port %d: %s\n", atoi(argv[i]),
415 n = (socklen_t)sizeof(sin);
416 in = out = accept(sock, (struct sockaddr *)&sin, &n);
419 * It must be a service name
422 /* clear all services */
424 for (j = 0; j < (int)NSERVICES; j++)
425 services[j].active = 0;
429 if(strcmp(argv[i],"amdump") == 0) {
430 services[0].active = 1;
431 services[1].active = 1;
432 services[2].active = 1;
433 services[3].active = 1;
436 for (j = 0; j < (int)NSERVICES; j++)
437 if (strcmp(services[j].name, argv[i]) == 0)
439 if (j == (int)NSERVICES) {
440 dbprintf(("%s: %s: invalid service\n",
441 debug_prefix_time(NULL), argv[i]));
444 services[j].active = 1;
450 * If no security type specified, use BSD
452 if (secdrv == NULL) {
453 secdrv = security_getdriver("BSD");
455 if (secdrv == NULL) {
456 error("no driver for default security type 'BSD'\n");
461 if(strcasecmp(auth, "rsh") == 0 ||
462 strcasecmp(auth, "ssh") == 0 ||
463 strcasecmp(auth, "bsdtcp") == 0) {
472 dbprintf(("%s: version %s\n", get_pname(), version()));
473 for (i = 0; version_info[i] != NULL; i++) {
474 dbprintf(("%s: %s", debug_prefix_time(NULL), version_info[i]));
477 if (! (argc >= 1 && argv != NULL && argv[0] != NULL)) {
478 dbprintf(("%s: WARNING: argv[0] not defined: check inetd.conf\n",
479 debug_prefix_time(NULL)));
483 * Schedule to call protocol_accept() when new security handles
484 * are created on stdin.
486 security_accept(secdrv, in, out, protocol_accept);
489 * Schedule an event that will try to exit every 30 seconds if there
490 * are no requests outstanding.
493 (void)event_register((event_id_t)30, EV_TIME, exit_check, &no_exit);
496 * Call event_loop() with an arg of 0, telling it to block until all
497 * events are completed.
508 * This runs periodically and checks to see if we have any active services
509 * still running. If we don't, then we quit.
517 assert(cookie != NULL);
518 no_exit = *(int *)cookie;
521 * If things are still running, then don't exit.
523 if (serviceq.qlength > 0)
527 * If the caller asked us to never exit, then we're done
533 dbmalloc_info.end.size = malloc_inuse(&dbmalloc_info.end.hist);
535 if (dbmalloc_info.start.size != dbmalloc_info.end.size) {
536 malloc_list(dbfd(), dbmalloc_info.start.hist,
537 dbmalloc_info.end.hist);
546 * Handles new incoming protocol handles. This is a callback for
547 * security_accept(), which gets called when new handles are detected.
551 security_handle_t * handle,
555 struct active_service *as;
556 char *pktbody, *tok, *service, *arguments;
557 char *service_path = NULL;
563 * If handle is NULL, then the connection is closed.
570 * If pkt is NULL, then there was a problem with the new connection.
573 dbprintf(("%s: accept error: %s\n",
574 debug_prefix_time(NULL), security_geterror(handle)));
575 pkt_init(&pkt_out, P_NAK, "ERROR %s\n", security_geterror(handle));
576 do_sendpkt(handle, &pkt_out);
577 amfree(pkt_out.body);
578 security_close(handle);
582 dbprintf(("%s: accept recv %s pkt:\n<<<<<\n%s>>>>>\n",
583 debug_prefix_time(NULL), pkt_type2str(pkt->type), pkt->body));
586 * If this is not a REQ packet, just forget about it.
588 if (pkt->type != P_REQ) {
589 dbprintf(("%s: received unexpected %s packet:\n<<<<<\n%s>>>>>\n\n",
590 debug_prefix_time(NULL), pkt_type2str(pkt->type), pkt->body));
591 security_close(handle);
595 pktbody = service = arguments = NULL;
599 * Parse out the service and arguments
602 pktbody = stralloc(pkt->body);
604 tok = strtok(pktbody, " ");
607 if (strcmp(tok, "SERVICE") != 0)
610 tok = strtok(NULL, " \n");
613 service = stralloc(tok);
615 /* we call everything else 'arguments' */
616 tok = strtok(NULL, "");
619 arguments = stralloc(tok);
621 /* see if it's one we allow */
622 for (i = 0; i < (int)NSERVICES; i++)
623 if (services[i].active == 1 && strcmp(services[i].name, service) == 0)
625 if (i == (int)NSERVICES) {
626 dbprintf(("%s: %s: invalid service\n",
627 debug_prefix_time(NULL), service));
628 pkt_init(&pkt_out, P_NAK, "ERROR %s: invalid service, add '%s' as argument to amandad\n", service, service);
632 service_path = vstralloc(libexecdir, "/", service, versionsuffix(), NULL);
633 if (access(service_path, X_OK) < 0) {
634 dbprintf(("%s: can't execute %s: %s\n",
635 debug_prefix_time(NULL), service_path, strerror(errno)));
636 pkt_init(&pkt_out, P_NAK,
637 "ERROR execute access to \"%s\" denied\n",
642 /* see if its already running */
643 for (as = TAILQ_FIRST(&serviceq.tailq); as != NULL;
644 as = TAILQ_NEXT(as, tq)) {
645 if (strcmp(as->cmd, service_path) == 0 &&
646 strcmp(as->arguments, arguments) == 0) {
647 dbprintf(("%s: %s %s: already running, acking req\n",
648 debug_prefix_time(NULL), service, arguments));
649 pkt_init_empty(&pkt_out, P_ACK);
650 goto send_pkt_out_no_delete;
655 * create a new service instance, and send the arguments down
658 dbprintf(("%s: creating new service: %s\n%s\n",
659 debug_prefix_time(NULL), service, arguments));
660 as = service_new(handle, service_path, arguments);
661 if (writebuf(as, arguments, strlen(arguments)) < 0) {
662 const char *errmsg = strerror(errno);
663 dbprintf(("%s: error sending arguments to %s: %s\n",
664 debug_prefix_time(NULL), service, errmsg));
665 pkt_init(&pkt_out, P_NAK, "ERROR error writing arguments to %s: %s\n",
673 amfree(service_path);
677 * Move to the sendack state, and start up the state
680 as->state = s_sendack;
681 state_machine(as, A_START, NULL);
685 pkt_init(&pkt_out, P_NAK, "ERROR invalid REQ\n");
686 dbprintf(("%s: received invalid %s packet:\n<<<<<\n%s>>>>>\n\n",
687 debug_prefix_time(NULL), pkt_type2str(pkt->type), pkt->body));
692 send_pkt_out_no_delete:
694 amfree(service_path);
697 do_sendpkt(handle, &pkt_out);
698 security_close(handle);
699 amfree(pkt_out.body);
703 * Handles incoming protocol packets. Routes responses to the proper
708 struct active_service * as,
716 amandad_debug(1, ("%s: state_machine: %p entering\n",
717 debug_prefix_time(NULL), as));
719 curstate = as->state;
720 amandad_debug(1, ("%s: state_machine: %p curstate=%s action=%s\n",
721 debug_prefix_time(NULL), as,
722 state2str(curstate), action2str(action)));
723 retaction = (*curstate)(as, action, pkt);
724 amandad_debug(1, ("%s: state_machine: %p curstate=%s returned %s (nextstate=%s)\n",
725 debug_prefix_time(NULL),
726 as, state2str(curstate), action2str(retaction),
727 state2str(as->state)));
731 * State has queued up and is now blocking on input.
734 amandad_debug(1, ("%s: state_machine: %p leaving (A_PENDING)\n",
735 debug_prefix_time(NULL), as));
739 * service has switched states. Loop.
745 * state has determined that the packet it received was bogus.
746 * Send a nak, and return.
749 dbprintf(("%s: received unexpected %s packet\n",
750 debug_prefix_time(NULL), pkt_type2str(pkt->type)));
751 dbprintf(("<<<<<\n%s----\n\n", pkt->body));
752 pkt_init(&nak, P_NAK, "ERROR unexpected packet type %s\n",
753 pkt_type2str(pkt->type));
754 do_sendpkt(as->security_handle, &nak);
756 security_recvpkt(as->security_handle, protocol_recv, as, -1);
757 amandad_debug(1, ("%s: state_machine: %p leaving (A_SENDNAK)\n",
758 debug_prefix_time(NULL), as));
762 * Service is done. Remove it and finish.
766 amandad_debug(1, ("%s: state_machine: %p leaving (A_FINISH)\n",
767 debug_prefix_time(NULL), as));
779 * This state just sends an ack. After that, we move to the repwait
780 * state to wait for REP data to arrive from the subprocess.
784 struct active_service * as,
790 (void)action; /* Quiet unused parameter warning */
791 (void)pkt; /* Quiet unused parameter warning */
793 pkt_init_empty(&ack, P_ACK);
794 if (do_sendpkt(as->security_handle, &ack) < 0) {
795 dbprintf(("%s: error sending ACK: %s\n",
796 debug_prefix_time(NULL), security_geterror(as->security_handle)));
803 * move to the repwait state
804 * Setup a listener for data on the reply fd, but also
805 * listen for packets over the wire, as the server may
806 * poll us if we take a long time.
807 * Setup a timeout that will fire if it takes too long to
810 as->state = s_repwait;
811 as->ev_repfd = event_register((event_id_t)as->repfd, EV_READFD, repfd_recv, as);
812 as->ev_reptimeout = event_register(REP_TIMEOUT, EV_TIME,
814 security_recvpkt(as->security_handle, protocol_recv, as, -1);
819 * This is the repwait state. We have responded to the initial REQ with
820 * an ACK, and we are now waiting for the process we spawned to pass us
821 * data to send in a REP.
825 struct active_service * as,
833 * We normally shouldn't receive any packets while waiting
834 * for our REP data, but in some cases we do.
836 if (action == A_RECVPKT) {
839 * Another req for something that's running. Just send an ACK
840 * and go back and wait for more data.
842 if (pkt->type == P_REQ) {
843 dbprintf(("%s: received dup P_REQ packet, ACKing it\n",
844 debug_prefix_time(NULL)));
845 amfree(as->rep_pkt.body);
846 pkt_init_empty(&as->rep_pkt, P_ACK);
847 do_sendpkt(as->security_handle, &as->rep_pkt);
848 security_recvpkt(as->security_handle, protocol_recv, as, -1);
851 /* something unexpected. Nak it */
855 if (action == A_TIMEOUT) {
856 amfree(as->rep_pkt.body);
857 pkt_init(&as->rep_pkt, P_NAK, "ERROR timeout on reply pipe\n");
858 dbprintf(("%s: %s timed out waiting for REP data\n",
859 debug_prefix_time(NULL), as->cmd));
860 do_sendpkt(as->security_handle, &as->rep_pkt);
864 assert(action == A_RECVREP);
865 if(as->bufsize == 0) {
866 as->bufsize = NETWORK_BLOCK_BYTES;
867 as->repbuf = alloc(as->bufsize);
871 n = read(as->repfd, as->repbuf + as->repbufsize,
872 as->bufsize - as->repbufsize - 1);
873 } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
875 const char *errstr = strerror(errno);
876 dbprintf(("%s: read error on reply pipe: %s\n",
877 debug_prefix_time(NULL), errstr));
878 amfree(as->rep_pkt.body);
879 pkt_init(&as->rep_pkt, P_NAK, "ERROR read error on reply pipe: %s\n",
881 do_sendpkt(as->security_handle, &as->rep_pkt);
885 * If we got some data, go back and wait for more, or EOF. Nul terminate
888 as->repbuf[n + as->repbufsize] = '\0';
891 if(as->repbufsize >= (as->bufsize - 1)) {
893 repbuf_temp = alloc(as->bufsize);
894 memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
896 as->repbuf = repbuf_temp;
898 else if(as->send_partial_reply) {
899 amfree(as->rep_pkt.body);
900 pkt_init(&as->rep_pkt, P_PREP, "%s", as->repbuf);
901 do_sendpkt(as->security_handle, &as->rep_pkt);
902 amfree(as->rep_pkt.body);
903 pkt_init_empty(&as->rep_pkt, P_REP);
910 * If we got 0, then we hit EOF. Process the data and release
915 assert(as->ev_repfd != NULL);
916 event_release(as->ev_repfd);
919 assert(as->ev_reptimeout != NULL);
920 event_release(as->ev_reptimeout);
921 as->ev_reptimeout = NULL;
923 as->state = s_processrep;
929 * After we have read in all of the rep data, we process it and send
930 * it out as a REP packet.
934 struct active_service * as,
940 (void)action; /* Quiet unused parameter warning */
941 (void)pkt; /* Quiet unused parameter warning */
944 * Copy the rep lines into the outgoing packet.
946 * If this line is a CONNECT, translate it
947 * Format is "CONNECT <tag> <handle> <tag> <handle> etc...
950 * CONNECT DATA 4 MESG 5 INDEX 6
952 * The tags are arbitrary. The handles are in the DATA_FD pool.
953 * We need to map these to security streams and pass them back
954 * to the amanda server. If the handle is -1, then we don't map.
956 repbuf = stralloc(as->repbuf);
957 amfree(as->rep_pkt.body);
958 pkt_init_empty(&as->rep_pkt, P_REP);
959 tok = strtok(repbuf, " ");
962 if (strcmp(tok, "CONNECT") == 0) {
963 char *line, *nextbuf;
965 /* Save the entire line */
966 line = strtok(NULL, "\n");
967 /* Save the buf following the line */
968 nextbuf = strtok(NULL, "");
970 if (line == NULL || nextbuf == NULL)
973 pkt_cat(&as->rep_pkt, "CONNECT");
975 /* loop over the id/handle pairs */
978 tok = strtok(line, " ");
979 line = NULL; /* keep working from line */
982 pkt_cat(&as->rep_pkt, " %s", tok);
985 tok = strtok(NULL, " \n");
988 /* convert the handle into something the server can process */
989 pkt_cat(&as->rep_pkt, " %d", allocstream(as, atoi(tok)));
991 pkt_cat(&as->rep_pkt, "\n%s", nextbuf);
994 pkt_cat(&as->rep_pkt, "%s", as->repbuf);
998 * We've setup our REP packet in as->rep_pkt. Now move to the transmission
1001 as->state = s_sendrep;
1002 as->repretry = getconf_int(CNF_REP_TRIES);
1004 return (A_CONTINUE);
1008 * This is the state where we send the REP we just collected from our child.
1012 struct active_service * as,
1016 (void)action; /* Quiet unused parameter warning */
1017 (void)pkt; /* Quiet unused parameter warning */
1020 * Transmit it and move to the ack state.
1022 do_sendpkt(as->security_handle, &as->rep_pkt);
1023 security_recvpkt(as->security_handle, protocol_recv, as, ACK_TIMEOUT);
1024 as->state = s_ackwait;
1029 * This is the state in which we wait for the server to ACK the REP
1034 struct active_service * as,
1038 struct datafd_handle *dh;
1042 * If we got a timeout, try again, but eventually give up.
1044 if (action == A_TIMEOUT) {
1045 if (--as->repretry > 0) {
1046 as->state = s_sendrep;
1047 return (A_CONTINUE);
1049 dbprintf(("%s: timeout waiting for ACK for our REP\n",
1050 debug_prefix_time(NULL)));
1053 amandad_debug(1, ("%s: received ACK, now opening streams\n",
1054 debug_prefix_time(NULL)));
1056 assert(action == A_RECVPKT);
1058 if (pkt->type == P_REQ) {
1059 dbprintf(("%s: received dup P_REQ packet, resending REP\n",
1060 debug_prefix_time(NULL)));
1061 as->state = s_sendrep;
1062 return (A_CONTINUE);
1065 if (pkt->type != P_ACK)
1069 * Got the ack, now open the pipes
1071 for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1072 if (dh->netfd == NULL)
1074 if (security_stream_accept(dh->netfd) < 0) {
1075 dbprintf(("%s: stream %td accept failed: %s\n",
1076 debug_prefix_time(NULL),
1077 dh - &as->data[0], security_geterror(as->security_handle)));
1078 security_stream_close(dh->netfd);
1082 /* setup an event for reads from it */
1083 dh->ev_read = event_register((event_id_t)dh->fd_read, EV_READFD,
1084 process_readnetfd, dh);
1086 security_stream_read(dh->netfd, process_writenetfd, dh);
1091 * Pipes are open, so auth them. Count them at the same time.
1093 for (npipes = 0, dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1094 if (dh->netfd == NULL)
1096 if (security_stream_auth(dh->netfd) < 0) {
1097 security_stream_close(dh->netfd);
1099 event_release(dh->ev_read);
1100 event_release(dh->ev_write);
1102 dh->ev_write = NULL;
1109 * If no pipes are open, then we're done. Otherwise, just start running.
1110 * The event handlers on all of the pipes will take it from here.
1112 amandad_debug(1, ("%s: at end of s_ackwait, npipes is %d\n",
1113 debug_prefix_time(NULL), npipes));
1117 security_close(as->security_handle);
1118 as->security_handle = NULL;
1124 * Called when a repfd has received data
1130 struct active_service *as = cookie;
1133 assert(as->ev_repfd != NULL);
1135 state_machine(as, A_RECVREP, NULL);
1139 * Called when a repfd has timed out
1145 struct active_service *as = cookie;
1148 assert(as->ev_reptimeout != NULL);
1150 state_machine(as, A_TIMEOUT, NULL);
1154 * Called when a handle has received data
1160 security_status_t status)
1162 struct active_service *as = cookie;
1168 dbprintf(("%s: received %s pkt:\n<<<<<\n%s>>>>>\n",
1169 debug_prefix_time(NULL), pkt_type2str(pkt->type), pkt->body));
1170 state_machine(as, A_RECVPKT, pkt);
1173 dbprintf(("%s: timeout\n", debug_prefix_time(NULL)));
1174 state_machine(as, A_TIMEOUT, NULL);
1177 dbprintf(("%s: receive error: %s\n",
1178 debug_prefix_time(NULL), security_geterror(as->security_handle)));
1184 * This is a generic relay function that just reads data from one of
1185 * the process's pipes and passes it up the equivalent security_stream_t
1192 struct datafd_handle *dh = cookie;
1193 struct active_service *as = dh->as;
1199 n = read(dh->fd_read, as->databuf, SIZEOF(as->databuf));
1200 } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
1206 pkt_init(&nak, P_NAK, "A ERROR data descriptor %d broken: %s\n",
1207 dh->fd_read, strerror(errno));
1211 * Process has closed the pipe. Just remove this event handler.
1212 * If all pipes are closed, shut down this service.
1215 event_release(dh->ev_read);
1217 if(dh->ev_write == NULL) {
1218 security_stream_close(dh->netfd);
1221 for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1222 if (dh->netfd != NULL)
1228 if (security_stream_write(dh->netfd, as->databuf, (size_t)n) < 0) {
1229 /* stream has croaked */
1230 pkt_init(&nak, P_NAK, "ERROR write error on stream %d: %s\n",
1231 security_stream_id(dh->netfd),
1232 security_stream_geterror(dh->netfd));
1238 do_sendpkt(as->security_handle, &nak);
1244 * This is a generic relay function that just read data from one of
1245 * the security_stream_t and passes it up the equivalent process's pipes
1253 struct datafd_handle *dh;
1255 assert(cookie != NULL);
1258 if (dh->fd_write <= 0) {
1259 dbprintf(("%s: process_writenetfd: dh->fd_write <= 0\n",
1260 debug_prefix_time(NULL)));
1261 } else if (size > 0) {
1262 fullwrite(dh->fd_write, buf, (size_t)size);
1263 security_stream_read(dh->netfd, process_writenetfd, dh);
1266 aclose(dh->fd_write);
1272 * Convert a local stream handle (DATA_FD...) into something that
1273 * can be sent to the amanda server.
1275 * Returns a number that should be sent to the server in the REP packet.
1279 struct active_service * as,
1282 struct datafd_handle *dh;
1284 /* if the handle is -1, then we don't bother */
1288 /* make sure the handle's kosher */
1289 if (handle < DATA_FD_OFFSET || handle >= DATA_FD_OFFSET + DATA_FD_COUNT)
1292 /* get a pointer into our handle array */
1293 dh = &as->data[handle - DATA_FD_OFFSET];
1295 /* make sure we're not already using the net handle */
1296 if (dh->netfd != NULL)
1299 /* allocate a stream from the security layer and return */
1300 dh->netfd = security_stream_server(as->security_handle);
1301 if (dh->netfd == NULL) {
1302 dbprintf(("%s: couldn't open stream to server: %s\n",
1303 debug_prefix_time(NULL), security_geterror(as->security_handle)));
1308 * convert the stream into a numeric id that can be sent to the
1311 return (security_stream_id(dh->netfd));
1315 * Create a new service instance
1317 static struct active_service *
1319 security_handle_t * security_handle,
1321 const char * arguments)
1324 int data_read[DATA_FD_COUNT + 1][2];
1325 int data_write[DATA_FD_COUNT + 1][2];
1326 struct active_service *as;
1330 assert(security_handle != NULL);
1331 assert(cmd != NULL);
1332 assert(arguments != NULL);
1334 /* a plethora of pipes */
1335 for (i = 0; i < DATA_FD_COUNT + 1; i++) {
1336 if (pipe(data_read[i]) < 0) {
1337 error("pipe: %s\n", strerror(errno));
1340 if (pipe(data_write[i]) < 0) {
1341 error("pipe: %s\n", strerror(errno));
1346 switch(pid = fork()) {
1348 error("could not fork service %s: %s\n", cmd, strerror(errno));
1352 * The parent. Close the far ends of our pipes and return.
1354 as = alloc(SIZEOF(*as));
1355 as->cmd = stralloc(cmd);
1356 as->arguments = stralloc(arguments);
1357 as->security_handle = security_handle;
1360 as->send_partial_reply = 0;
1361 if(strcmp(cmd+(strlen(cmd)-8), "sendsize") == 0) {
1362 g_option_t *g_options;
1363 char *option_str, *p;
1365 option_str = stralloc(as->arguments+8);
1366 p = strchr(option_str,'\n');
1369 g_options = parse_g_options(option_str, 1);
1370 if(am_has_feature(g_options->features, fe_partial_estimate)) {
1371 as->send_partial_reply = 1;
1373 free_g_options(g_options);
1377 /* write to the request pipe */
1378 aclose(data_read[0][0]);
1379 as->reqfd = data_read[0][1];
1382 * read from the reply pipe
1384 as->repfd = data_write[0][0];
1385 aclose(data_write[0][1]);
1386 as->ev_repfd = NULL;
1391 as->rep_pkt.body = NULL;
1394 * read from the rest of the general-use pipes
1395 * (netfds are opened as the client requests them)
1397 for (i = 0; i < DATA_FD_COUNT; i++) {
1398 aclose(data_read[i + 1][1]);
1399 aclose(data_write[i + 1][0]);
1400 as->data[i].fd_read = data_read[i + 1][0];
1401 as->data[i].fd_write = data_write[i + 1][1];
1402 as->data[i].ev_read = NULL;
1403 as->data[i].ev_write = NULL;
1404 as->data[i].netfd = NULL;
1405 as->data[i].as = as;
1408 /* add it to the service queue */
1409 /* increment the active service count */
1410 TAILQ_INSERT_TAIL(&serviceq.tailq, as, tq);
1416 * The child. Put our pipes in their advertised locations
1425 * The data stream is stdin in the new process
1427 if (dup2(data_read[0][0], 0) < 0) {
1428 error("dup %d to %d failed: %s\n", data_read[0][0], 0,
1432 aclose(data_read[0][0]);
1433 aclose(data_read[0][1]);
1436 * The reply stream is stdout
1438 if (dup2(data_write[0][1], 1) < 0) {
1439 error("dup %d to %d failed: %s\n", data_write[0][1], 1,
1442 aclose(data_write[0][0]);
1443 aclose(data_write[0][1]);
1445 for (i = 0; i < DATA_FD_COUNT; i++) {
1446 aclose(data_read[i + 1][0]);
1447 aclose(data_write[i + 1][1]);
1451 * Make sure they are not open in the range DATA_FD_OFFSET to
1452 * DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1
1454 for (i = 0; i < DATA_FD_COUNT; i++) {
1455 while(data_read[i + 1][1] >= DATA_FD_OFFSET &&
1456 data_read[i + 1][1] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1457 newfd = dup(data_read[i + 1][1]);
1459 error("Can't dup out off DATA_FD range");
1460 data_read[i + 1][1] = newfd;
1462 while(data_write[i + 1][0] >= DATA_FD_OFFSET &&
1463 data_write[i + 1][0] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1464 newfd = dup(data_write[i + 1][0]);
1466 error("Can't dup out off DATA_FD range");
1467 data_write[i + 1][0] = newfd;
1470 for (i = 0; i < DATA_FD_COUNT*2; i++)
1471 close(DATA_FD_OFFSET + i);
1474 * The rest start at the offset defined in amandad.h, and continue
1475 * through the internal defined.
1477 for (i = 0; i < DATA_FD_COUNT; i++) {
1478 if (dup2(data_read[i + 1][1], i*2 + DATA_FD_OFFSET) < 0) {
1479 error("dup %d to %d failed: %s\n", data_read[i + 1][1],
1480 i + DATA_FD_OFFSET, strerror(errno));
1482 aclose(data_read[i + 1][1]);
1484 if (dup2(data_write[i + 1][0], i*2 + 1 + DATA_FD_OFFSET) < 0) {
1485 error("dup %d to %d failed: %s\n", data_write[i + 1][0],
1486 i + DATA_FD_OFFSET, strerror(errno));
1488 aclose(data_write[i + 1][0]);
1491 /* close all unneeded fd */
1492 safe_fd(DATA_FD_OFFSET, DATA_FD_COUNT*2);
1495 execle(cmd, cmd, "amandad", auth, (char *)NULL, safe_env());
1496 error("could not exec service %s: %s\n", cmd, strerror(errno));
1503 * Unallocate a service instance
1507 struct active_service * as)
1510 struct datafd_handle *dh;
1512 amandad_debug(1, ("%s: closing service: %s\n",
1513 debug_prefix_time(NULL),
1514 (as->cmd)?as->cmd:"??UNKONWN??"));
1518 assert(as->cmd != NULL);
1521 assert(as->arguments != NULL);
1522 amfree(as->arguments);
1524 if (as->reqfd != -1)
1526 if (as->repfd != -1)
1529 if (as->ev_repfd != NULL)
1530 event_release(as->ev_repfd);
1531 if (as->ev_reptimeout != NULL)
1532 event_release(as->ev_reptimeout);
1534 for (i = 0; i < DATA_FD_COUNT; i++) {
1537 aclose(dh->fd_read);
1538 aclose(dh->fd_write);
1540 if (dh->netfd != NULL)
1541 security_stream_close(dh->netfd);
1543 if (dh->ev_read != NULL)
1544 event_release(dh->ev_read);
1545 if (dh->ev_write != NULL)
1546 event_release(dh->ev_write);
1549 if (as->security_handle != NULL)
1550 security_close(as->security_handle);
1552 assert(as->pid > 0);
1553 kill(as->pid, SIGTERM);
1554 waitpid(as->pid, NULL, WNOHANG);
1556 TAILQ_REMOVE(&serviceq.tailq, as, tq);
1557 assert(serviceq.qlength > 0);
1561 amfree(as->arguments);
1563 amfree(as->rep_pkt.body);
1566 if(exit_on_qlength == 0 && serviceq.qlength == 0) {
1573 * Like 'fullwrite', but does the work in a child process so pipelines
1578 struct active_service * as,
1585 switch (pid=fork()) {
1590 waitpid(pid, NULL, WNOHANG);
1591 return 0; /* this is the parent */
1593 case 0: /* this is the child */
1595 writesize = fullwrite(as->reqfd, bufp, size);
1596 exit(writesize != (ssize_t)size);
1604 security_handle_t * handle,
1607 dbprintf(("%s: sending %s pkt:\n<<<<<\n%s>>>>>\n",
1608 debug_prefix_time(NULL), pkt_type2str(pkt->type), pkt->body));
1610 return security_sendpkt(handle, pkt);
1616 * Convert a state into a string
1622 static const struct {
1626 #define X(state) { state, stringize(state) }
1636 for (i = 0; i < (int)(sizeof(states) / sizeof(states[0])); i++)
1637 if (state == states[i].state)
1638 return (states[i].str);
1639 return ("INVALID STATE");
1643 * Convert an action into a string
1649 static const struct {
1653 #define X(action) { action, stringize(action) }
1666 for (i = 0; i < (int)(sizeof(actions) / sizeof(actions[0])); i++)
1667 if (action == actions[i].action)
1668 return (actions[i].str);
1669 return ("UNKNOWN ACTION");