2 Server code for handling requests from clients and forwarding them
3 on to the GNU Emacs process.
5 This file is part of GNU Emacs.
7 Copying is permitted under those conditions described by the GNU
8 General Public License.
10 Copyright (C) 1989 Free Software Foundation, Inc.
12 Author: Andy Norman (ange@hplb.hpl.hp.com), based on 'etc/server.c'
13 from the 18.52 GNU Emacs distribution.
15 Please mail bugs and suggestions to the author at the above address.
19 * 11-Nov-1990 bristor@simba
24 * This file incorporates new features added by Bob Weiner <weiner@mot.com>,
25 * Darrell Kindred <dkindred@cmu.edu> and Arup Mukherjee <arup@cmu.edu>.
26 * Please see the note at the end of the README file for details.
28 * (If gnuserv came bundled with your emacs, the README file is probably
29 * ../etc/gnuserv.README relative to the directory containing this file)
35 char gnuserv_version[] = "gnuserv version" GNUSERV_VERSION;
39 #include <bsd/sgtty.h>
46 #include <sys/select.h>
51 #include <sys/types.h>
56 #endif /* HAVE_UNISTD_H */
60 #endif /* HAVE_STRING_H */
62 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
63 !defined(INTERNET_DOMAIN_SOCKETS)
67 "Sorry, the Emacs server is only supported on systems that have\n");
69 "Unix Domain sockets, Internet Domain sockets or System V IPC\n");
72 #else /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
76 int ipc_qid = 0; /* ipc message queue id */
77 pid_t ipc_wpid = 0; /* watchdog task pid */
80 ipc_exit -- clean up the queue id and queue, then kill the watchdog task
81 if it exists. exit with the given status.
83 void ipc_exit(int stat)
85 msgctl(ipc_qid, IPC_RMID, 0);
88 kill(ipc_wpid, SIGKILL);
94 ipc_handle_signal -- catch the signal given and clean up.
96 void ipc_handle_signal(int sig)
99 } /* ipc_handle_signal */
102 ipc_spawn_watchdog -- spawn a watchdog task to clean up the message queue should the
105 void ipc_spawn_watchdog(void)
107 if ((ipc_wpid = fork()) == 0) { /* child process */
108 pid_t ppid = getppid(); /* parent's process id */
110 setpgrp(); /* gnu kills process group on exit */
113 if (kill(ppid, 0) < 0) { /* ppid is no longer valid, parent
118 sleep(10); /* have another go later */
122 } /* ipc_spawn_watchdog */
125 ipc_init -- initialize server, setting the global msqid that can be listened on.
127 void ipc_init(struct msgbuf **msgpp)
129 key_t key; /* messge key */
130 char buf[GSERV_BUFSZ]; /* pathname for key */
132 int sz = snprintf(buf, sizeof(buf),"%s/gsrv%d", tmpdir, (int)geteuid());
133 assert(sz>=0 && sz<sizeof(buf));
137 if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
139 fprintf(stderr, "%s: unable to create msg queue\n", progname);
143 ipc_spawn_watchdog();
145 signal(SIGTERM, ipc_handle_signal);
146 signal(SIGINT, ipc_handle_signal);
148 if ((*msgpp = (struct msgbuf *)
149 malloc(sizeof **msgpp + GSERV_BUFSZ)) == NULL) {
151 "%s: unable to allocate space for message buffer\n",
158 handle_ipc_request -- accept a request from a client, pass the request on
159 to the GNU Emacs process, then wait for its reply and
160 pass that on to the client.
162 void handle_ipc_request(struct msgbuf *msgp)
164 struct msqid_ds msg_st; /* message status */
165 char buf[GSERV_BUFSZ];
166 int len; /* length of message / read */
167 int s, result_len; /* tag fields on the response from emacs */
169 int total = 1; /* # bytes that will actually be sent off */
171 if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
173 fprintf(stderr, "%s: unable to receive\n", progname);
177 msgctl(ipc_qid, IPC_STAT, &msg_st);
178 strncpy(buf, msgp->mtext, len);
179 buf[len] = '\0'; /* terminate */
181 printf("%d %s", ipc_qid, buf);
184 /* now for the response from gnu */
185 msgp->mtext[0] = '\0';
188 if ((len = read(0, buf, GSERV_BUFSZ - 1)) < 0) {
190 fprintf(stderr, "%s: unable to read\n", progname);
194 sscanf(buf, "%d:%[^\n]\n", &junk, msgp->mtext);
197 /* read in "n/m:" (n=client fd, m=message length) */
199 while (offset < (GSERV_BUFSZ - 1) &&
200 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
206 fprintf(stderr, "%s: unable to read\n", progname);
210 /* parse the response from emacs, getting client fd & result length */
212 sscanf(buf, "%d/%d", &s, &result_len);
214 while (result_len > 0) {
215 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1))) < 0) {
217 fprintf(stderr, "%s: unable to read\n", progname);
221 /* Send this string off, but only if we have enough space */
223 if (GSERV_BUFSZ > total) {
224 if (total + len <= GSERV_BUFSZ)
227 buf[GSERV_BUFSZ - total] = 0;
230 total += strlen(buf);
236 /* eat the newline */
237 while ((len = read(0, buf, 1)) == 0) ;
240 fprintf(stderr, "%s: unable to read\n", progname);
243 if (buf[0] != '\n') {
244 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
250 /* Send a response back to the client. */
252 msgp->mtype = msg_st.msg_lspid;
253 if (msgsnd(ipc_qid, msgp, strlen(msgp->mtext) + 1, 0) < 0)
254 perror("msgsend(gnuserv)");
256 } /* handle_ipc_request */
257 #endif /* SYSV_IPC */
259 #if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
261 echo_request -- read request from a given socket descriptor, and send the information
262 to stdout (the gnu process).
264 static void echo_request(int s)
266 char buf[GSERV_BUFSZ];
271 /* read until we get a newline or no characters */
272 while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
276 if (buf[len - 1] == EOT_CHR) {
278 break; /* end of message */
285 fprintf(stderr, "%s: unable to recv\n", progname);
292 handle_response -- accept a response from stdin (the gnu process) and pass the
293 information on to the relevant client.
295 static void handle_response(void)
297 char buf[GSERV_BUFSZ + 1];
303 /* read in "n/m:" (n=client fd, m=message length) */
304 while (offset < GSERV_BUFSZ &&
305 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
311 fprintf(stderr, "%s: unable to read\n", progname);
315 /* parse the response from emacs, getting client fd & result length */
317 sscanf(buf, "%d/%d", &s, &result_len);
319 while (result_len > 0) {
320 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
322 fprintf(stderr, "%s: unable to read\n", progname);
330 /* eat the newline */
331 while ((len = read(0, buf, 1)) == 0) ;
334 fprintf(stderr, "%s: unable to read\n", progname);
337 if (buf[0] != '\n') {
338 fprintf(stderr, "%s: garbage after result\n", progname);
341 /* send the newline */
346 } /* handle_response */
347 #endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
349 #ifdef INTERNET_DOMAIN_SOCKETS
351 unsigned long host_addr;
355 struct entry *permitted_hosts[TABLE_SIZE];
357 #ifdef AUTH_MAGIC_COOKIE
359 # include <X11/Xauth.h>
361 static Xauth *server_xauth = NULL;
364 static int timed_read(int fd, char *buf, int max, int timeout, int one_line)
367 struct timeval tv; /* = {timeout, 0}; */
379 r = select(fd + 1, &rmask, NULL, NULL, &tv);
382 if (read(fd, &c, 1) == 1) {
386 printf("read error on socket\004\n");
390 printf("read timed out\004\n");
393 printf("error in select\004\n");
396 } while ((nbytes < max) && !(one_line && (c == '\n')));
399 if (one_line && *buf == '\n') {
407 permitted -- return whether a given host is allowed to connect to the server.
409 static int permitted(unsigned long host_addr, int fd)
414 char auth_protocol[128];
419 /* we are checking permission on a real connection */
421 /* Read auth protocol name */
423 if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1)
427 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
428 strcmp(auth_protocol, MCOOKIE_NAME)) {
430 ("authentication protocol (%s) from client is invalid...\n",
433 ("... Was the client an old version of gnuclient/gnudoit?\004\n");
438 if (!strcmp(auth_protocol, MCOOKIE_NAME)) {
441 * doing magic cookie auth
444 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
447 auth_data_len = atoi(buf);
449 if (auth_data_len <= 0
450 || auth_data_len > (int)sizeof(buf)) {
454 if (timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0)
458 #ifdef AUTH_MAGIC_COOKIE
459 if (server_xauth && server_xauth->data) {
460 /* Do a compare without comprising info about
461 the size of the cookie */
463 int auth_mismatches =
464 (auth_data_len ^ server_xauth->data_length);
466 for (auth_data_pos = 0;
467 auth_data_pos < auth_data_len;
470 (buf[auth_data_pos] ^ server_xauth->
472 server_xauth->data_length]);
474 if (auth_mismatches == 0)
477 for (; rand() % 1000;) ;
481 ("client tried Xauth, but server is not compiled with Xauth\n");
485 * auth failed, but allow this to fall through to the GNU_SECURE
490 ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");
494 /* Other auth protocols go here, and should execute only if the
495 * auth_protocol name matches.
500 /* Now, try the old GNU_SECURE stuff... */
502 /* First find the hash key */
503 key = HASH(host_addr) % TABLE_SIZE;
505 /* Now check the chain for that hash key */
506 for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next)
507 if (host_addr == entry->host_addr)
515 add_host -- add the given host to the list of permitted hosts, provided it isn't
518 static void add_host(unsigned long host_addr)
521 struct entry *new_entry;
523 if (!permitted(host_addr, -1)) {
525 (struct entry *)malloc(sizeof(struct entry))) == NULL) {
527 "%s: unable to malloc space for permitted host entry\n",
532 new_entry->host_addr = host_addr;
533 key = HASH(host_addr) % TABLE_SIZE;
534 new_entry->next = permitted_hosts[key];
535 permitted_hosts[key] = new_entry;
541 setup_table -- initialize the table of hosts allowed to contact the server,
542 by reading from the file specified by the GNU_SECURE
544 Put in the local machine, and, if a security file is specifed,
545 add each host that is named in the file.
546 Return the number of hosts added.
548 static int setup_table(void)
552 char hostname[HOSTNAMSZ];
553 unsigned int host_addr;
557 /* Make sure every entry is null */
558 for (i = 0; i < TABLE_SIZE; i++)
559 permitted_hosts[i] = NULL;
561 gethostname(hostname, HOSTNAMSZ);
563 if ((t = internet_addr(hostname)) == -1) {
565 "%s: unable to find %s in /etc/hosts or from YP",
572 #ifdef AUTH_MAGIC_COOKIE
574 server_xauth = XauGetAuthByAddr(FamilyInternet,
575 sizeof(host_addr), (char *)&host_addr,
576 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
577 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
580 #endif /* AUTH_MAGIC_COOKIE */
582 #if 0 /* Don't even want to allow access from the local host by default */
583 add_host(host_addr); /* add local host */
586 if (((file_name = getenv("GNU_SECURE")) != NULL && /* security file */
587 (host_file = fopen(file_name, "r")) != NULL)) { /* opened ok */
588 while ((fscanf(host_file, "%s", hostname) != EOF)) { /* find a host */
589 t = internet_addr(hostname);
590 if (t != -1) { /* get its addr */
592 add_host(host_addr); /* add the addr */
603 internet_init -- initialize server, returning an internet socket that can
606 static int internet_init(void)
608 int ls; /* socket descriptor */
609 struct servent *sp; /* pointer to service information */
610 struct sockaddr_in server; /* for local socket address */
611 char *ptr; /* ptr to return from getenv */
613 if (setup_table() == 0)
616 /* clear out address structure */
617 memset(&server, '\0', sizeof(server));
619 /* Set up address structure for the listen socket. */
620 server.sin_family = AF_INET;
621 server.sin_addr.s_addr = INADDR_ANY;
623 /* Find the information for the gnu server
624 * in order to get the needed port number.
626 if ((ptr = getenv("GNU_PORT")) != NULL)
627 server.sin_port = htons(atoi(ptr));
628 else if ((sp = getservbyname("gnuserv", "tcp")) == NULL)
629 server.sin_port = htons(DEFAULT_PORT + getuid());
631 server.sin_port = sp->s_port;
633 /* Create the listen socket. */
634 if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
636 fprintf(stderr, "%s: unable to create socket\n", progname);
641 /* Bind the listen address to the socket. */
642 if (bind(ls, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) ==
645 fprintf(stderr, "%s: unable to bind socket\n", progname);
650 /* Initiate the listen on the socket so remote users
653 if (listen(ls, 20) == -1) {
655 fprintf(stderr, "%s: unable to listen\n", progname);
661 } /* internet_init */
664 handle_internet_request -- accept a request from a client and send the information
665 to stdout (the gnu process).
667 static void handle_internet_request(int ls)
670 socklen_t addrlen = sizeof(struct sockaddr_in);
671 struct sockaddr_in peer; /* for peer socket address */
673 memset(&peer, '\0', sizeof(peer));
675 if ((s = accept(ls, (struct sockaddr *)&peer, &addrlen)) == -1) {
677 fprintf(stderr, "%s: unable to accept\n", progname);
682 /* Check that access is allowed - if not return crud to the client */
683 if (!permitted(peer.sin_addr.s_addr, s)) {
685 "gnudoit: Connection refused\ngnudoit: unable to connect to remote");
688 printf("Refused connection from %s\004\n",
689 inet_ntoa(peer.sin_addr));
695 } /* handle_internet_request */
696 #endif /* INTERNET_DOMAIN_SOCKETS */
698 #ifdef UNIX_DOMAIN_SOCKETS
700 unix_init -- initialize server, returning an unix-domain socket that can
703 static int unix_init(void)
705 int ls; /* socket descriptor */
706 struct sockaddr_un server; /* unix socket address */
710 if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
712 fprintf(stderr, "%s: unable to create socket\n", progname);
717 /* Set up address structure for the listen socket. */
718 #ifdef HIDE_UNIX_SOCKET
719 sz = snprintf(server.sun_path, sizeof(server.sun_path),
720 "%s/gsrvdir%d", tmpdir, (int)geteuid());
721 assert(sz>=0 && sz<sizeof(server.sun_path));
722 if (mkdir(server.sun_path, 0700) < 0) {
723 /* assume it already exists, and try to set perms */
724 if (chmod(server.sun_path, 0700) < 0) {
726 fprintf(stderr, "%s: can't set permissions on %s\n",
727 progname, server.sun_path);
731 strcat(server.sun_path, "/gsrv");
732 unlink(server.sun_path); /* remove old file if it exists */
733 #else /* HIDE_UNIX_SOCKET */
734 sz = snprintf(server.sun_path, sizeof(server.sun_path),
735 "%s/gsrv%d", tmpdir, (int)geteuid());
736 assert(sz>=0 && sz<sizeof(server.sun_path));
737 unlink(server.sun_path); /* remove old file if it exists */
738 #endif /* HIDE_UNIX_SOCKET */
740 server.sun_family = AF_UNIX;
741 #ifdef HAVE_SOCKADDR_SUN_LEN
742 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
744 bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
745 + strlen(server.sun_path) + 1);
746 server.sun_len = bindlen;
748 bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
751 if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
753 fprintf(stderr, "%s: unable to bind socket\n", progname);
757 chmod(server.sun_path, 0700); /* only this user can send commands */
759 if (listen(ls, 20) < 0) {
761 fprintf(stderr, "%s: unable to listen\n", progname);
766 /* #### there are also better ways of dealing with this when
767 sigvec() is present. */
768 #if defined (HAVE_SIGPROCMASK)
772 sigaddset(&_mask, SIGPIPE);
773 sigprocmask(SIG_BLOCK, &_mask, NULL);
776 signal(SIGPIPE, SIG_IGN); /* in case user kills client */
784 handle_unix_request -- accept a request from a client and send the information
785 to stdout (the gnu process).
787 static void handle_unix_request(int ls)
790 socklen_t len = sizeof(struct sockaddr_un);
791 struct sockaddr_un server; /* for unix socket address */
793 server.sun_family = AF_UNIX;
795 if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
797 fprintf(stderr, "%s: unable to accept\n", progname);
802 } /* handle_unix_request */
803 #endif /* UNIX_DOMAIN_SOCKETS */
805 int main(int argc, char *argv[])
807 int chan; /* temporary channel number */
809 struct msgbuf *msgp; /* message buffer */
811 int ils = -1; /* internet domain listen socket */
812 int uls = -1; /* unix domain listen socket */
813 #endif /* SYSV_IPC */
817 for (chan = 3; chan < _NFILE; close(chan++)) /* close unwanted channels */
821 tmpdir = getenv("TMPDIR");
827 /* this is to allow ^D to pass to emacs */
829 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
834 ipc_init(&msgp); /* get a msqid to listen on, and a message buffer */
835 #endif /* SYSV_IPC */
837 #ifdef INTERNET_DOMAIN_SOCKETS
838 ils = internet_init(); /* get an internet domain socket to listen on */
839 #endif /* INTERNET_DOMAIN_SOCKETS */
841 #ifdef UNIX_DOMAIN_SOCKETS
842 uls = unix_init(); /* get a unix domain socket to listen on */
843 #endif /* UNIX_DOMAIN_SOCKETS */
847 handle_ipc_request(msgp);
848 #else /* NOT SYSV_IPC */
851 FD_SET(fileno(stdin), &rmask);
857 if (select(max2(fileno(stdin), max2(uls, ils)) + 1, &rmask,
858 (fd_set *) NULL, (fd_set *) NULL,
859 (struct timeval *)NULL) < 0) {
861 fprintf(stderr, "%s: unable to select\n", progname);
865 #ifdef UNIX_DOMAIN_SOCKETS
866 if (uls > 0 && FD_ISSET(uls, &rmask))
867 handle_unix_request(uls);
870 #ifdef INTERNET_DOMAIN_SOCKETS
871 if (ils > 0 && FD_ISSET(ils, &rmask))
872 handle_internet_request(ils);
873 #endif /* INTERNET_DOMAIN_SOCKETS */
875 if (FD_ISSET(fileno(stdin), &rmask)) /* from stdin (gnu process) */
877 #endif /* NOT SYSV_IPC */
881 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */