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;
150 static kencrypt_type amandad_kencrypt = KENCRYPT_NONE;
152 int main(int argc, char **argv);
154 static int allocstream(struct active_service *, int);
155 static void exit_check(void *);
156 static void protocol_accept(security_handle_t *, pkt_t *);
157 static void state_machine(struct active_service *, action_t, pkt_t *);
159 static action_t s_sendack(struct active_service *, action_t, pkt_t *);
160 static action_t s_repwait(struct active_service *, action_t, pkt_t *);
161 static action_t s_processrep(struct active_service *, action_t, pkt_t *);
162 static action_t s_sendrep(struct active_service *, action_t, pkt_t *);
163 static action_t s_ackwait(struct active_service *, action_t, pkt_t *);
165 static void repfd_recv(void *);
166 static void timeout_repfd(void *);
167 static void protocol_recv(void *, pkt_t *, security_status_t);
168 static void process_readnetfd(void *);
169 static void process_writenetfd(void *, void *, ssize_t);
170 static struct active_service *service_new(security_handle_t *,
171 const char *, const char *);
172 static void service_delete(struct active_service *);
173 static int writebuf(struct active_service *, const void *, size_t);
174 static ssize_t do_sendpkt(security_handle_t *handle, pkt_t *pkt);
175 static char *amandad_get_security_conf (char *, void *);
177 static const char *state2str(state_t);
178 static const char *action2str(action_t);
188 const security_driver_t *secdrv;
190 char *pgm = "amandad"; /* in case argv[0] is not set */
191 #if defined(USE_REUSEADDR)
197 * Configure program for internationalization:
198 * 1) Only set the message locale for now.
199 * 2) Set textdomain for all amanda related programs to "amanda"
200 * We don't want to be forced to support dozens of message catalogs.
202 setlocale(LC_MESSAGES, "C");
203 textdomain("amanda");
209 * When called via inetd, it is not uncommon to forget to put the
210 * argv[0] value on the config line. On some systems (e.g. Solaris)
211 * this causes argv and/or argv[0] to be NULL, so we have to be
212 * careful getting our name.
214 if ((argv == NULL) || (argv[0] == NULL)) {
215 pgm = "amandad"; /* in case argv[0] is not set */
217 pgm = basename(argv[0]); /* Strip of leading path get debug name */
220 dbopen(DBG_SUBDIR_AMANDAD);
223 error(_("argv == NULL\n"));
227 /* Don't die when child closes pipe */
228 signal(SIGPIPE, SIG_IGN);
230 config_init(CONFIG_INIT_CLIENT, NULL);
232 if (geteuid() == 0) {
233 check_running_as(RUNNING_AS_ROOT);
234 initgroups(CLIENT_LOGIN, get_client_gid());
235 setgid(get_client_gid());
236 setegid(get_client_gid());
237 seteuid(get_client_uid());
239 check_running_as(RUNNING_AS_CLIENT_LOGIN);
242 erroutput_type = (ERR_INTERACTIVE|ERR_SYSLOG);
245 * ad-hoc argument parsing
247 * We accept -auth=[authentication type]
251 * We also add a list of services that amandad can launch
254 in = 0; out = 1; /* default to stdin/stdout */
256 for (i = 1; i < argc; i++) {
258 * accept -krb4 as an alias for -auth=krb4 (for compatibility)
260 if (strcmp(argv[i], "-krb4") == 0) {
261 argv[i] = "-auth=krb4";
267 * Get a driver for a security type specified after -auth=
269 else if (strncmp(argv[i], "-auth=", strlen("-auth=")) == 0) {
270 argv[i] += strlen("-auth=");
271 secdrv = security_getdriver(argv[i]);
273 if (secdrv == NULL) {
274 error(_("no driver for security type '%s'\n"), argv[i]);
281 * If -no-exit is specified, always run even after requests have
284 else if (strcmp(argv[i], "-no-exit") == 0) {
290 * Allow us to directly bind to a udp port for debugging.
291 * This may only apply to some security types.
293 else if (strncmp(argv[i], "-udp=", strlen("-udp=")) == 0) {
295 struct sockaddr_in6 sin;
297 struct sockaddr_in sin;
300 argv[i] += strlen("-udp=");
302 in = out = socket(AF_INET6, SOCK_DGRAM, 0);
304 in = out = socket(AF_INET, SOCK_DGRAM, 0);
307 error(_("can't create dgram socket: %s\n"), strerror(errno));
311 r = setsockopt(in, SOL_SOCKET, SO_REUSEADDR,
312 (void *)&on, (socklen_t_equiv)sizeof(on));
314 dbprintf(_("amandad: setsockopt(SO_REUSEADDR) failed: %s\n"),
320 sin.sin6_family = (sa_family_t)AF_INET6;
321 sin.sin6_addr = in6addr_any;
322 sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
324 sin.sin_family = (sa_family_t)AF_INET;
325 sin.sin_addr.s_addr = INADDR_ANY;
326 sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
328 if (bind(in, (struct sockaddr *)&sin, (socklen_t_equiv)sizeof(sin)) < 0) {
329 error(_("can't bind to port %d: %s\n"), atoi(argv[i]),
335 * Ditto for tcp ports.
337 else if (strncmp(argv[i], "-tcp=", strlen("-tcp=")) == 0) {
339 struct sockaddr_in6 sin;
341 struct sockaddr_in sin;
346 argv[i] += strlen("-tcp=");
348 sock = socket(AF_INET6, SOCK_STREAM, 0);
350 sock = socket(AF_INET, SOCK_STREAM, 0);
353 error(_("can't create tcp socket: %s\n"), strerror(errno));
357 r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
358 (void *)&on, (socklen_t_equiv)sizeof(on));
360 dbprintf(_("amandad: setsockopt(SO_REUSEADDR) failed: %s\n"),
365 sin.sin6_family = (sa_family_t)AF_INET6;
366 sin.sin6_addr = in6addr_any;
367 sin.sin6_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
369 sin.sin_family = (sa_family_t)AF_INET;
370 sin.sin_addr.s_addr = INADDR_ANY;
371 sin.sin_port = (in_port_t)htons((in_port_t)atoi(argv[i]));
373 if (bind(sock, (struct sockaddr *)&sin, (socklen_t_equiv)sizeof(sin)) < 0) {
374 error(_("can't bind to port %d: %s\n"), atoi(argv[i]),
379 n = (socklen_t_equiv)sizeof(sin);
380 in = out = accept(sock, (struct sockaddr *)&sin, &n);
383 * It must be a service name
386 /* clear all services */
388 for (j = 0; j < (int)NSERVICES; j++)
389 services[j].active = 0;
393 if(strcmp(argv[i],"amdump") == 0) {
394 services[0].active = 1;
395 services[1].active = 1;
396 services[2].active = 1;
397 services[3].active = 1;
400 for (j = 0; j < (int)NSERVICES; j++)
401 if (strcmp(services[j].name, argv[i]) == 0)
403 if (j == (int)NSERVICES) {
404 dbprintf(_("%s: invalid service\n"), argv[i]);
407 services[j].active = 1;
413 * If no security type specified, use BSD
415 if (secdrv == NULL) {
416 secdrv = security_getdriver("BSD");
418 if (secdrv == NULL) {
419 error(_("no driver for default security type 'BSD'\n"));
424 if(strcasecmp(auth, "rsh") == 0 ||
425 strcasecmp(auth, "ssh") == 0 ||
426 strcasecmp(auth, "bsdtcp") == 0) {
432 if (strcasecmp(auth, "krb5") != 0) {
433 error(_("Amanda must be run as user '%s' when using '%s' authetication"),
437 if (strcasecmp(auth, "krb5") == 0) {
438 error(_("Amanda must be run as user 'root' when using 'krb5' authetication"));
447 dbprintf(_("version %s\n"), version());
448 for (i = 0; version_info[i] != NULL; i++) {
449 dbprintf(" %s", version_info[i]);
452 if (! (argc >= 1 && argv != NULL && argv[0] != NULL)) {
453 dbprintf(_("WARNING: argv[0] not defined: check inetd.conf\n"));
456 /* krb5 require the euid to be 0 */
457 if (strcasecmp(auth, "krb5") == 0) {
462 * Schedule to call protocol_accept() when new security handles
463 * are created on stdin.
465 security_accept(secdrv, amandad_get_security_conf, in, out, protocol_accept, NULL);
468 * Schedule an event that will try to exit every 30 seconds if there
469 * are no requests outstanding.
472 (void)event_register((event_id_t)30, EV_TIME, exit_check, &no_exit);
475 * Call event_loop() with an arg of 0, telling it to block until all
476 * events are completed.
487 * This runs periodically and checks to see if we have any active services
488 * still running. If we don't, then we quit.
496 assert(cookie != NULL);
497 no_exit = *(int *)cookie;
500 * If things are still running, then don't exit.
502 if (serviceq.qlength > 0)
506 * If the caller asked us to never exit, then we're done
516 * Handles new incoming protocol handles. This is a callback for
517 * security_accept(), which gets called when new handles are detected.
521 security_handle_t * handle,
525 struct active_service *as;
526 char *pktbody, *tok, *service, *arguments;
527 char *service_path = NULL;
533 * If handle is NULL, then the connection is closed.
540 * If pkt is NULL, then there was a problem with the new connection.
543 dbprintf(_("accept error: %s\n"), security_geterror(handle));
544 pkt_init(&pkt_out, P_NAK, "ERROR %s\n", security_geterror(handle));
545 do_sendpkt(handle, &pkt_out);
546 amfree(pkt_out.body);
547 security_close(handle);
551 dbprintf(_("accept recv %s pkt:\n<<<<<\n%s>>>>>\n"),
552 pkt_type2str(pkt->type), pkt->body);
555 * If this is not a REQ packet, just forget about it.
557 if (pkt->type != P_REQ) {
558 dbprintf(_("received unexpected %s packet:\n<<<<<\n%s>>>>>\n\n"),
559 pkt_type2str(pkt->type), pkt->body);
560 security_close(handle);
564 pktbody = service = arguments = NULL;
568 * Parse out the service and arguments
571 pktbody = stralloc(pkt->body);
573 tok = strtok(pktbody, " ");
576 if (strcmp(tok, "SERVICE") != 0)
579 tok = strtok(NULL, " \n");
582 service = stralloc(tok);
584 /* we call everything else 'arguments' */
585 tok = strtok(NULL, "");
588 arguments = stralloc(tok);
590 /* see if it's one we allow */
591 for (i = 0; i < (int)NSERVICES; i++)
592 if (services[i].active == 1 && strcmp(services[i].name, service) == 0)
594 if (i == (int)NSERVICES) {
595 dbprintf(_("%s: invalid service\n"), service);
596 pkt_init(&pkt_out, P_NAK, _("ERROR %s: invalid service, add '%s' as argument to amandad\n"), service, service);
600 service_path = vstralloc(amlibexecdir, "/", service, versionsuffix(), NULL);
601 if (access(service_path, X_OK) < 0) {
602 dbprintf(_("can't execute %s: %s\n"), service_path, strerror(errno));
603 pkt_init(&pkt_out, P_NAK,
604 _("ERROR execute access to \"%s\" denied\n"),
609 /* see if its already running */
610 for (as = TAILQ_FIRST(&serviceq.tailq); as != NULL;
611 as = TAILQ_NEXT(as, tq)) {
612 if (strcmp(as->cmd, service_path) == 0 &&
613 strcmp(as->arguments, arguments) == 0) {
614 dbprintf(_("%s %s: already running, acking req\n"),
616 pkt_init_empty(&pkt_out, P_ACK);
617 goto send_pkt_out_no_delete;
622 * create a new service instance, and send the arguments down
625 dbprintf(_("creating new service: %s\n%s\n"), service, arguments);
626 as = service_new(handle, service_path, arguments);
627 if (writebuf(as, arguments, strlen(arguments)) < 0) {
628 const char *errmsg = strerror(errno);
629 dbprintf(_("error sending arguments to %s: %s\n"), service, errmsg);
630 pkt_init(&pkt_out, P_NAK, _("ERROR error writing arguments to %s: %s\n"),
638 amfree(service_path);
642 * Move to the sendack state, and start up the state
645 as->state = s_sendack;
646 state_machine(as, A_START, NULL);
650 pkt_init(&pkt_out, P_NAK, _("ERROR invalid REQ\n"));
651 dbprintf(_("received invalid %s packet:\n<<<<<\n%s>>>>>\n\n"),
652 pkt_type2str(pkt->type), pkt->body);
657 send_pkt_out_no_delete:
659 amfree(service_path);
662 do_sendpkt(handle, &pkt_out);
663 security_close(handle);
664 amfree(pkt_out.body);
668 * Handles incoming protocol packets. Routes responses to the proper
673 struct active_service * as,
681 amandad_debug(1, _("state_machine: %p entering\n"), as);
683 curstate = as->state;
684 amandad_debug(1, _("state_machine: %p curstate=%s action=%s\n"), as,
685 state2str(curstate), action2str(action));
686 retaction = (*curstate)(as, action, pkt);
687 amandad_debug(1, _("state_machine: %p curstate=%s returned %s (nextstate=%s)\n"),
688 as, state2str(curstate), action2str(retaction),
689 state2str(as->state));
693 * State has queued up and is now blocking on input.
696 amandad_debug(1, _("state_machine: %p leaving (A_PENDING)\n"), as);
700 * service has switched states. Loop.
706 * state has determined that the packet it received was bogus.
707 * Send a nak, and return.
710 dbprintf(_("received unexpected %s packet\n"),
711 pkt_type2str(pkt->type));
712 dbprintf(_("<<<<<\n%s----\n\n"), pkt->body);
713 pkt_init(&nak, P_NAK, _("ERROR unexpected packet type %s\n"),
714 pkt_type2str(pkt->type));
715 do_sendpkt(as->security_handle, &nak);
717 security_recvpkt(as->security_handle, protocol_recv, as, -1);
718 amandad_debug(1, _("state_machine: %p leaving (A_SENDNAK)\n"), as);
722 * Service is done. Remove it and finish.
725 amandad_debug(1, _("state_machine: %p leaving (A_FINISH)\n"), as);
738 * This state just sends an ack. After that, we move to the repwait
739 * state to wait for REP data to arrive from the subprocess.
743 struct active_service * as,
749 (void)action; /* Quiet unused parameter warning */
750 (void)pkt; /* Quiet unused parameter warning */
752 pkt_init_empty(&ack, P_ACK);
753 if (do_sendpkt(as->security_handle, &ack) < 0) {
754 dbprintf(_("error sending ACK: %s\n"),
755 security_geterror(as->security_handle));
762 * move to the repwait state
763 * Setup a listener for data on the reply fd, but also
764 * listen for packets over the wire, as the server may
765 * poll us if we take a long time.
766 * Setup a timeout that will fire if it takes too long to
769 as->state = s_repwait;
770 as->ev_repfd = event_register((event_id_t)as->repfd, EV_READFD, repfd_recv, as);
771 as->ev_reptimeout = event_register(REP_TIMEOUT, EV_TIME,
773 security_recvpkt(as->security_handle, protocol_recv, as, -1);
778 * This is the repwait state. We have responded to the initial REQ with
779 * an ACK, and we are now waiting for the process we spawned to pass us
780 * data to send in a REP.
784 struct active_service * as,
798 * We normally shouldn't receive any packets while waiting
799 * for our REP data, but in some cases we do.
801 if (action == A_RECVPKT) {
804 * Another req for something that's running. Just send an ACK
805 * and go back and wait for more data.
807 if (pkt->type == P_REQ) {
808 dbprintf(_("received dup P_REQ packet, ACKing it\n"));
809 amfree(as->rep_pkt.body);
810 pkt_init_empty(&as->rep_pkt, P_ACK);
811 do_sendpkt(as->security_handle, &as->rep_pkt);
812 security_recvpkt(as->security_handle, protocol_recv, as, -1);
815 /* something unexpected. Nak it */
819 if (action == A_TIMEOUT) {
820 amfree(as->rep_pkt.body);
821 pkt_init(&as->rep_pkt, P_NAK, _("ERROR timeout on reply pipe\n"));
822 dbprintf(_("%s timed out waiting for REP data\n"), as->cmd);
823 do_sendpkt(as->security_handle, &as->rep_pkt);
827 assert(action == A_RECVREP);
828 if(as->bufsize == 0) {
829 as->bufsize = NETWORK_BLOCK_BYTES;
830 as->repbuf = alloc(as->bufsize);
834 n = read(as->repfd, as->repbuf + as->repbufsize,
835 as->bufsize - as->repbufsize - 1);
836 } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
838 const char *errstr = strerror(errno);
839 dbprintf(_("read error on reply pipe: %s\n"), errstr);
840 amfree(as->rep_pkt.body);
841 pkt_init(&as->rep_pkt, P_NAK, _("ERROR read error on reply pipe: %s\n"),
843 do_sendpkt(as->security_handle, &as->rep_pkt);
847 /* If end of service, wait for process status */
850 pid = waitpid(as->pid, &retstat, WNOHANG);
851 while (t<5 && pid == 0) {
854 pid = waitpid(as->pid, &retstat, WNOHANG);
859 if (! WIFEXITED(retstat)) {
861 code = WTERMSIG(retstat);
862 } else if (WEXITSTATUS(retstat) != 0) {
864 code = WEXITSTATUS(retstat);
867 dbprintf(_("service %s failed: pid %u exited with %s %d\n"),
868 (as->cmd)?as->cmd:_("??UNKONWN??"),
872 _("ERROR service %s failed: pid %u exited with %s %d\n"),
873 (as->cmd)?as->cmd:_("??UNKONWN??"), (unsigned)as->pid,
875 if (as->repbufsize + strlen(msg) >= (as->bufsize - 1)) {
877 repbuf_temp = alloc(as->bufsize);
878 memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
880 as->repbuf = repbuf_temp;
882 strcpy(as->repbuf + as->repbufsize, msg);
883 as->repbufsize += strlen(msg);
889 * If we got some data, go back and wait for more, or EOF. Nul terminate
892 as->repbuf[n + as->repbufsize] = '\0';
895 if(as->repbufsize >= (as->bufsize - 1)) {
897 repbuf_temp = alloc(as->bufsize);
898 memcpy(repbuf_temp, as->repbuf, as->repbufsize + 1);
900 as->repbuf = repbuf_temp;
902 else if(as->send_partial_reply) {
903 amfree(as->rep_pkt.body);
904 pkt_init(&as->rep_pkt, P_PREP, "%s", as->repbuf);
905 do_sendpkt(as->security_handle, &as->rep_pkt);
906 amfree(as->rep_pkt.body);
907 pkt_init_empty(&as->rep_pkt, P_REP);
914 * If we got 0, then we hit EOF. Process the data and release
919 assert(as->ev_repfd != NULL);
920 event_release(as->ev_repfd);
923 assert(as->ev_reptimeout != NULL);
924 event_release(as->ev_reptimeout);
925 as->ev_reptimeout = NULL;
927 as->state = s_processrep;
933 * After we have read in all of the rep data, we process it and send
934 * it out as a REP packet.
938 struct active_service * as,
944 (void)action; /* Quiet unused parameter warning */
945 (void)pkt; /* Quiet unused parameter warning */
948 * Copy the rep lines into the outgoing packet.
950 * If this line is a CONNECT, translate it
951 * Format is "CONNECT <tag> <handle> <tag> <handle> etc...
954 * CONNECT DATA 4 MESG 5 INDEX 6
956 * The tags are arbitrary. The handles are in the DATA_FD pool.
957 * We need to map these to security streams and pass them back
958 * to the amanda server. If the handle is -1, then we don't map.
960 if (strncmp_const(as->repbuf,"KENCRYPT\n") == 0) {
961 amandad_kencrypt = KENCRYPT_WILL_DO;
962 repbuf = stralloc(as->repbuf + 9);
964 repbuf = stralloc(as->repbuf);
966 amfree(as->rep_pkt.body);
967 pkt_init_empty(&as->rep_pkt, P_REP);
968 tok = strtok(repbuf, " ");
971 if (strcmp(tok, "CONNECT") == 0) {
972 char *line, *nextbuf;
974 /* Save the entire line */
975 line = strtok(NULL, "\n");
976 /* Save the buf following the line */
977 nextbuf = strtok(NULL, "");
979 if (line == NULL || nextbuf == NULL)
982 pkt_cat(&as->rep_pkt, "CONNECT");
984 /* loop over the id/handle pairs */
987 tok = strtok(line, " ");
988 line = NULL; /* keep working from line */
991 pkt_cat(&as->rep_pkt, " %s", tok);
994 tok = strtok(NULL, " \n");
997 /* convert the handle into something the server can process */
998 pkt_cat(&as->rep_pkt, " %d", allocstream(as, atoi(tok)));
1000 pkt_cat(&as->rep_pkt, "\n%s", nextbuf);
1003 pkt_cat(&as->rep_pkt, "%s", as->repbuf);
1007 * We've setup our REP packet in as->rep_pkt. Now move to the transmission
1010 as->state = s_sendrep;
1011 as->repretry = getconf_int(CNF_REP_TRIES);
1013 return (A_CONTINUE);
1017 * This is the state where we send the REP we just collected from our child.
1021 struct active_service * as,
1025 (void)action; /* Quiet unused parameter warning */
1026 (void)pkt; /* Quiet unused parameter warning */
1029 * Transmit it and move to the ack state.
1031 do_sendpkt(as->security_handle, &as->rep_pkt);
1032 security_recvpkt(as->security_handle, protocol_recv, as, ACK_TIMEOUT);
1033 as->state = s_ackwait;
1038 * This is the state in which we wait for the server to ACK the REP
1043 struct active_service * as,
1047 struct datafd_handle *dh;
1051 * If we got a timeout, try again, but eventually give up.
1053 if (action == A_TIMEOUT) {
1054 if (--as->repretry > 0) {
1055 as->state = s_sendrep;
1056 return (A_CONTINUE);
1058 dbprintf(_("timeout waiting for ACK for our REP\n"));
1061 amandad_debug(1, _("received ACK, now opening streams\n"));
1063 assert(action == A_RECVPKT);
1065 if (pkt->type == P_REQ) {
1066 dbprintf(_("received dup P_REQ packet, resending REP\n"));
1067 as->state = s_sendrep;
1068 return (A_CONTINUE);
1071 if (pkt->type != P_ACK)
1074 if (amandad_kencrypt == KENCRYPT_WILL_DO) {
1075 amandad_kencrypt = KENCRYPT_YES;
1079 * Got the ack, now open the pipes
1081 for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1082 if (dh->netfd == NULL)
1084 if (security_stream_accept(dh->netfd) < 0) {
1085 dbprintf(_("stream %td accept failed: %s\n"),
1086 dh - &as->data[0], security_geterror(as->security_handle));
1087 security_stream_close(dh->netfd);
1091 /* setup an event for reads from it */
1092 dh->ev_read = event_register((event_id_t)dh->fd_read, EV_READFD,
1093 process_readnetfd, dh);
1095 security_stream_read(dh->netfd, process_writenetfd, dh);
1100 * Pipes are open, so auth them. Count them at the same time.
1102 for (npipes = 0, dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1103 if (dh->netfd == NULL)
1105 if (security_stream_auth(dh->netfd) < 0) {
1106 security_stream_close(dh->netfd);
1108 event_release(dh->ev_read);
1109 event_release(dh->ev_write);
1111 dh->ev_write = NULL;
1118 * If no pipes are open, then we're done. Otherwise, just start running.
1119 * The event handlers on all of the pipes will take it from here.
1121 amandad_debug(1, _("at end of s_ackwait, npipes is %d\n"), npipes);
1125 security_close(as->security_handle);
1126 as->security_handle = NULL;
1132 * Called when a repfd has received data
1138 struct active_service *as = cookie;
1141 assert(as->ev_repfd != NULL);
1143 state_machine(as, A_RECVREP, NULL);
1147 * Called when a repfd has timed out
1153 struct active_service *as = cookie;
1156 assert(as->ev_reptimeout != NULL);
1158 state_machine(as, A_TIMEOUT, NULL);
1162 * Called when a handle has received data
1168 security_status_t status)
1170 struct active_service *as = cookie;
1176 dbprintf(_("received %s pkt:\n<<<<<\n%s>>>>>\n"),
1177 pkt_type2str(pkt->type), pkt->body);
1178 state_machine(as, A_RECVPKT, pkt);
1181 dbprintf(_("timeout\n"));
1182 state_machine(as, A_TIMEOUT, NULL);
1185 dbprintf(_("receive error: %s\n"),
1186 security_geterror(as->security_handle));
1192 * This is a generic relay function that just reads data from one of
1193 * the process's pipes and passes it up the equivalent security_stream_t
1200 struct datafd_handle *dh = cookie;
1201 struct active_service *as = dh->as;
1207 n = read(dh->fd_read, as->databuf, SIZEOF(as->databuf));
1208 } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
1214 pkt_init(&nak, P_NAK, _("A ERROR data descriptor %d broken: %s\n"),
1215 dh->fd_read, strerror(errno));
1219 * Process has closed the pipe. Just remove this event handler.
1220 * If all pipes are closed, shut down this service.
1223 event_release(dh->ev_read);
1225 if(dh->ev_write == NULL) {
1226 security_stream_close(dh->netfd);
1229 for (dh = &as->data[0]; dh < &as->data[DATA_FD_COUNT]; dh++) {
1230 if (dh->netfd != NULL)
1236 if (security_stream_write(dh->netfd, as->databuf, (size_t)n) < 0) {
1237 /* stream has croaked */
1238 pkt_init(&nak, P_NAK, _("ERROR write error on stream %d: %s\n"),
1239 security_stream_id(dh->netfd),
1240 security_stream_geterror(dh->netfd));
1246 do_sendpkt(as->security_handle, &nak);
1252 * This is a generic relay function that just read data from one of
1253 * the security_stream_t and passes it up the equivalent process's pipes
1261 struct datafd_handle *dh;
1263 assert(cookie != NULL);
1266 if (dh->fd_write <= 0) {
1267 dbprintf(_("process_writenetfd: dh->fd_write <= 0\n"));
1268 } else if (size > 0) {
1269 fullwrite(dh->fd_write, buf, (size_t)size);
1270 security_stream_read(dh->netfd, process_writenetfd, dh);
1273 aclose(dh->fd_write);
1279 * Convert a local stream handle (DATA_FD...) into something that
1280 * can be sent to the amanda server.
1282 * Returns a number that should be sent to the server in the REP packet.
1286 struct active_service * as,
1289 struct datafd_handle *dh;
1291 /* if the handle is -1, then we don't bother */
1295 /* make sure the handle's kosher */
1296 if (handle < DATA_FD_OFFSET || handle >= DATA_FD_OFFSET + DATA_FD_COUNT)
1299 /* get a pointer into our handle array */
1300 dh = &as->data[handle - DATA_FD_OFFSET];
1302 /* make sure we're not already using the net handle */
1303 if (dh->netfd != NULL)
1306 /* allocate a stream from the security layer and return */
1307 dh->netfd = security_stream_server(as->security_handle);
1308 if (dh->netfd == NULL) {
1309 dbprintf(_("couldn't open stream to server: %s\n"),
1310 security_geterror(as->security_handle));
1315 * convert the stream into a numeric id that can be sent to the
1318 return (security_stream_id(dh->netfd));
1322 * Create a new service instance
1324 static struct active_service *
1326 security_handle_t * security_handle,
1328 const char * arguments)
1331 int data_read[DATA_FD_COUNT + 1][2];
1332 int data_write[DATA_FD_COUNT + 1][2];
1333 struct active_service *as;
1337 assert(security_handle != NULL);
1338 assert(cmd != NULL);
1339 assert(arguments != NULL);
1341 /* a plethora of pipes */
1342 for (i = 0; i < DATA_FD_COUNT + 1; i++) {
1343 if (pipe(data_read[i]) < 0) {
1344 error(_("pipe: %s\n"), strerror(errno));
1347 if (pipe(data_write[i]) < 0) {
1348 error(_("pipe: %s\n"), strerror(errno));
1353 switch(pid = fork()) {
1355 error(_("could not fork service %s: %s\n"), cmd, strerror(errno));
1359 * The parent. Close the far ends of our pipes and return.
1361 as = alloc(SIZEOF(*as));
1362 as->cmd = stralloc(cmd);
1363 as->arguments = stralloc(arguments);
1364 as->security_handle = security_handle;
1367 as->send_partial_reply = 0;
1368 if(strcmp(cmd+(strlen(cmd)-8), "sendsize") == 0) {
1369 g_option_t *g_options;
1370 char *option_str, *p;
1372 option_str = stralloc(as->arguments+8);
1373 p = strchr(option_str,'\n');
1376 g_options = parse_g_options(option_str, 1);
1377 if(am_has_feature(g_options->features, fe_partial_estimate)) {
1378 as->send_partial_reply = 1;
1380 free_g_options(g_options);
1384 /* write to the request pipe */
1385 aclose(data_read[0][0]);
1386 as->reqfd = data_read[0][1];
1389 * read from the reply pipe
1391 as->repfd = data_write[0][0];
1392 aclose(data_write[0][1]);
1393 as->ev_repfd = NULL;
1398 as->rep_pkt.body = NULL;
1401 * read from the rest of the general-use pipes
1402 * (netfds are opened as the client requests them)
1404 for (i = 0; i < DATA_FD_COUNT; i++) {
1405 aclose(data_read[i + 1][1]);
1406 aclose(data_write[i + 1][0]);
1407 as->data[i].fd_read = data_read[i + 1][0];
1408 as->data[i].fd_write = data_write[i + 1][1];
1409 as->data[i].ev_read = NULL;
1410 as->data[i].ev_write = NULL;
1411 as->data[i].netfd = NULL;
1412 as->data[i].as = as;
1415 /* add it to the service queue */
1416 /* increment the active service count */
1417 TAILQ_INSERT_TAIL(&serviceq.tailq, as, tq);
1423 * The child. Put our pipes in their advertised locations
1428 * The data stream is stdin in the new process
1430 if (dup2(data_read[0][0], 0) < 0) {
1431 error(_("dup %d to %d failed: %s\n"), data_read[0][0], 0,
1435 aclose(data_read[0][0]);
1436 aclose(data_read[0][1]);
1439 * The reply stream is stdout
1441 if (dup2(data_write[0][1], 1) < 0) {
1442 error(_("dup %d to %d failed: %s\n"), data_write[0][1], 1,
1445 aclose(data_write[0][0]);
1446 aclose(data_write[0][1]);
1448 for (i = 0; i < DATA_FD_COUNT; i++) {
1449 aclose(data_read[i + 1][0]);
1450 aclose(data_write[i + 1][1]);
1454 * Make sure they are not open in the range DATA_FD_OFFSET to
1455 * DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1
1457 for (i = 0; i < DATA_FD_COUNT; i++) {
1458 while(data_read[i + 1][1] >= DATA_FD_OFFSET &&
1459 data_read[i + 1][1] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1460 newfd = dup(data_read[i + 1][1]);
1462 error(_("Can't dup out off DATA_FD range"));
1463 data_read[i + 1][1] = newfd;
1465 while(data_write[i + 1][0] >= DATA_FD_OFFSET &&
1466 data_write[i + 1][0] <= DATA_FD_OFFSET + DATA_FD_COUNT*2 - 1) {
1467 newfd = dup(data_write[i + 1][0]);
1469 error(_("Can't dup out off DATA_FD range"));
1470 data_write[i + 1][0] = newfd;
1473 for (i = 0; i < DATA_FD_COUNT*2; i++)
1474 close(DATA_FD_OFFSET + i);
1477 * The rest start at the offset defined in amandad.h, and continue
1478 * through the internal defined.
1480 for (i = 0; i < DATA_FD_COUNT; i++) {
1481 if (dup2(data_read[i + 1][1], i*2 + DATA_FD_OFFSET) < 0) {
1482 error(_("dup %d to %d failed: %s\n"), data_read[i + 1][1],
1483 i + DATA_FD_OFFSET, strerror(errno));
1485 aclose(data_read[i + 1][1]);
1487 if (dup2(data_write[i + 1][0], i*2 + 1 + DATA_FD_OFFSET) < 0) {
1488 error(_("dup %d to %d failed: %s\n"), data_write[i + 1][0],
1489 i + DATA_FD_OFFSET, strerror(errno));
1491 aclose(data_write[i + 1][0]);
1494 /* close all unneeded fd */
1495 close(STDERR_FILENO);
1496 debug_dup_stderr_to_debug();
1497 safe_fd(DATA_FD_OFFSET, DATA_FD_COUNT*2);
1499 execle(cmd, cmd, "amandad", auth, (char *)NULL, safe_env());
1500 error(_("could not exec service %s: %s\n"), cmd, strerror(errno));
1507 * Unallocate a service instance
1511 struct active_service * as)
1514 struct datafd_handle *dh;
1516 amandad_debug(1, _("closing service: %s\n"),
1517 (as->cmd)?as->cmd:_("??UNKONWN??"));
1521 assert(as->cmd != NULL);
1524 assert(as->arguments != NULL);
1525 amfree(as->arguments);
1527 if (as->reqfd != -1)
1529 if (as->repfd != -1)
1532 if (as->ev_repfd != NULL)
1533 event_release(as->ev_repfd);
1534 if (as->ev_reptimeout != NULL)
1535 event_release(as->ev_reptimeout);
1537 for (i = 0; i < DATA_FD_COUNT; i++) {
1540 aclose(dh->fd_read);
1541 aclose(dh->fd_write);
1543 if (dh->netfd != NULL)
1544 security_stream_close(dh->netfd);
1546 if (dh->ev_read != NULL)
1547 event_release(dh->ev_read);
1548 if (dh->ev_write != NULL)
1549 event_release(dh->ev_write);
1552 if (as->security_handle != NULL)
1553 security_close(as->security_handle);
1555 assert(as->pid > 0);
1556 kill(as->pid, SIGTERM);
1557 waitpid(as->pid, NULL, WNOHANG);
1559 TAILQ_REMOVE(&serviceq.tailq, as, tq);
1560 assert(serviceq.qlength > 0);
1564 amfree(as->arguments);
1566 amfree(as->rep_pkt.body);
1569 if(exit_on_qlength == 0 && serviceq.qlength == 0) {
1576 * Like 'fullwrite', but does the work in a child process so pipelines
1581 struct active_service * as,
1588 switch (pid=fork()) {
1593 waitpid(pid, NULL, WNOHANG);
1594 return 0; /* this is the parent */
1596 case 0: /* this is the child */
1598 writesize = fullwrite(as->reqfd, bufp, size);
1599 exit(writesize != (ssize_t)size);
1607 security_handle_t * handle,
1610 dbprintf(_("sending %s pkt:\n<<<<<\n%s>>>>>\n"),
1611 pkt_type2str(pkt->type), pkt->body);
1613 return security_sendpkt(handle, pkt);
1619 * Convert a state into a string
1625 static const struct {
1629 #define X(state) { state, stringize(state) }
1639 for (i = 0; i < (int)(sizeof(states) / sizeof(states[0])); i++)
1640 if (state == states[i].state)
1641 return (states[i].str);
1642 return (_("INVALID STATE"));
1646 * Convert an action into a string
1652 static const struct {
1656 #define X(action) { action, stringize(action) }
1669 for (i = 0; i < (int)(sizeof(actions) / sizeof(actions[0])); i++)
1670 if (action == actions[i].action)
1671 return (actions[i].str);
1672 return (_("UNKNOWN ACTION"));
1676 amandad_get_security_conf(
1680 (void)arg; /* Quiet unused parameter warning */
1682 if (!string || !*string)
1685 if (strcmp(string, "kencrypt")==0) {
1686 if (amandad_kencrypt == KENCRYPT_YES)