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 */
63 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
64 !defined(INTERNET_DOMAIN_SOCKETS)
68 fputs("Sorry, the Emacs server is only supported on systems that have\n\
69 Unix Domain sockets, Internet Domain sockets or System V IPC\n", stderr);
72 #else /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
76 /* ipc message queue id */
78 /* watchdog task pid */
82 * clean up the queue id and queue, then kill the watchdog task
83 * if it exists. exit with the given status. **/
85 __attribute__((noreturn))
88 msgctl(ipc_qid, IPC_RMID, 0);
91 kill(ipc_wpid, SIGKILL);
97 * catch the signal given and clean up. **/
99 ipc_handle_signal(int sig)
104 /** ipc_spawn_watchdog
105 * spawn a watchdog task to clean up the message queue should the
106 * server process die. **/
108 ipc_spawn_watchdog(void)
111 if ((ipc_wpid = fork()) == 0) {
112 /* parent's process id */
113 pid_t ppid = getppid();
115 /* gnu kills process group on exit */
119 /* ppid is no longer valid, parent may have died */
120 if (kill(ppid, 0) < 0) {
123 /* else, have another go later */
131 * initialize server, setting the global msqid that can be listened on. **/
133 ipc_init(struct msgbuf **msgpp)
137 /* pathname for key */
138 char buf[GSERV_BUFSZ];
141 SNPRINTF(sz, buf, sizeof(buf),"%s/gsrv%d", tmpdir, (int)geteuid());
145 if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
147 fprintf(stderr, "%s: unable to create msg queue\n", progname);
150 ipc_spawn_watchdog();
152 signal(SIGTERM, ipc_handle_signal);
153 signal(SIGINT, ipc_handle_signal);
155 *msgpp = (struct msgbuf*)malloc(sizeof **msgpp + GSERV_BUFSZ);
156 if (*msgpp == NULL) {
158 "%s: unable to allocate space for message buffer\n",
165 /** handle_ipc_request
166 * accept a request from a client, pass the request on to the GNU Emacs process,
167 * then wait for its reply and pass that on to the client. **/
169 handle_ipc_request(struct msgbuf *msgp)
172 struct msqid_ds msg_st;
173 char buf[GSERV_BUFSZ];
174 /* length of message / read */
176 /* tag fields on the response from emacs */
179 /* # bytes that will actually be sent off */
182 if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
184 fprintf(stderr, "%s: unable to receive\n", progname);
188 msgctl(ipc_qid, IPC_STAT, &msg_st);
189 strncpy(buf, msgp->mtext, len);
193 printf("%d %s", ipc_qid, buf);
196 /* now for the response from gnu */
197 msgp->mtext[0] = '\0';
199 /* read in "n/m:" (n=client fd, m=message length) */
200 while (offset < (GSERV_BUFSZ - 1) &&
201 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
207 fprintf(stderr, "%s: unable to read\n", progname);
211 /* parse the response from emacs, getting client fd & result length */
213 sscanf(buf, "%d/%d", &s, &result_len);
215 while (result_len > 0) {
216 len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1));
219 fprintf(stderr, "%s: unable to read\n", progname);
223 /* Send this string off, but only if we have enough space */
224 if (GSERV_BUFSZ > total) {
225 if (total + len <= GSERV_BUFSZ) {
228 buf[GSERV_BUFSZ - total] = 0;
231 total += strlen(buf);
237 /* eat the newline */
238 while ((len = read(0, buf, 1)) == 0);
242 fprintf(stderr, "%s: unable to read\n", progname);
245 if (buf[0] != '\n') {
246 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
251 /* 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)");
258 # endif /* SYSV_IPC */
260 # if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
262 * read request from a given socket descriptor, and send the information
263 * to stdout (the gnu process). **/
267 char buf[GSERV_BUFSZ];
272 /* read until we get a newline or no characters */
273 while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
277 if (buf[len - 1] == EOT_CHR) {
286 fprintf(stderr, "%s: unable to recv\n", progname);
293 * accept a response from stdin (the gnu process) and pass the
294 * information on to the relevant client. **/
296 handle_response(void)
298 char buf[GSERV_BUFSZ + 1];
304 /* read in "n/m:" (n=client fd, m=message length) */
305 while (offset < GSERV_BUFSZ &&
306 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
312 fprintf(stderr, "%s: unable to read\n", progname);
316 /* parse the response from emacs, getting client fd & result length */
318 sscanf(buf, "%d/%d", &s, &result_len);
320 while (result_len > 0) {
321 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
323 fprintf(stderr, "%s: unable to read\n", progname);
331 /* eat the newline */
332 while ((len = read(0, buf, 1)) == 0) ;
335 fprintf(stderr, "%s: unable to read\n", progname);
338 if (buf[0] != '\n') {
339 fprintf(stderr, "%s: garbage after result\n", progname);
342 /* send the newline */
348 # endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
350 # ifdef INTERNET_DOMAIN_SOCKETS
352 unsigned long host_addr;
356 struct entry *permitted_hosts[TABLE_SIZE];
358 # ifdef AUTH_MAGIC_COOKIE
360 # include <X11/Xauth.h>
362 static Xauth *server_xauth = NULL;
363 # endif /* AUTH_MAGIC_COOKIE */
366 timed_read(int fd, char *buf, int max, int timeout, int one_line)
369 /* = {timeout, 0}; */
382 r = select(fd + 1, &rmask, NULL, NULL, &tv);
385 if (read(fd, &c, 1) == 1) {
389 printf("read error on socket\004\n");
393 printf("read timed out\004\n");
396 printf("error in select\004\n");
399 } while ((nbytes < max) && !(one_line && (c == '\n')));
402 if (one_line && *buf == '\n') {
409 * return whether a given host is allowed to connect to the server. **/
411 permitted(unsigned long host_addr, int fd)
416 char auth_protocol[128];
420 /* we are checking permission on a real connection */
422 long int auth_data_len;
424 /* Read auth protocol name */
425 if ((len = timed_read(
427 AUTH_NAMESZ, AUTH_TIMEOUT, 1)) <= 0) {
431 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
432 strcmp(auth_protocol, MCOOKIE_NAME)) {
433 printf("authentication protocol (%s) \
434 from client is invalid...\n\
435 ... Was the client an old version of gnuclient/gnudoit?\n", auth_protocol);
439 if (strcmp(auth_protocol, MCOOKIE_NAME)) {
444 * doing magic cookie auth
447 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0) {
450 auth_data_len = strtol(buf, NULL, 10);
452 if (auth_data_len <= 0 || (size_t)auth_data_len > sizeof(buf)) {
456 len = timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0);
457 if (len != auth_data_len) {
461 #ifdef AUTH_MAGIC_COOKIE
462 if (server_xauth && server_xauth->data) {
463 /* Do a compare without comprising info about
464 the size of the cookie */
466 int auth_mismatches =
467 (auth_data_len ^ server_xauth->data_length);
469 for (auth_data_pos = 0;
470 auth_data_pos < auth_data_len;
473 (buf[auth_data_pos] ^ server_xauth->
475 server_xauth->data_length]);
477 if (auth_mismatches == 0) {
480 for (; rand() % 1000;);
482 #else /* !AUTH_MAGIC_COOKIE */
484 client tried Xauth, but server is not compiled with Xauth\n", stdout);
485 #endif /* AUTH_MAGIC_COOKIE */
488 * auth failed, but allow this to fall through to the GNU_SECURE
492 Xauth authentication failed, trying GNU_SECURE auth...\n", stdout);
496 /* Now, try the old GNU_SECURE stuff... */
498 /* First find the hash key */
499 key = HASH(host_addr) % TABLE_SIZE;
501 /* Now check the chain for that hash key */
502 for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next) {
503 if (host_addr == entry->host_addr) {
511 * add the given host to the list of permitted hosts, provided it isn't
514 add_host(unsigned long host_addr)
517 struct entry *new_entry;
519 if (!permitted(host_addr, -1)) {
520 new_entry = (struct entry *)malloc(sizeof(struct entry));
521 if (new_entry == NULL) {
523 %s: unable to malloc space for permitted host entry\n", progname);
527 new_entry->host_addr = host_addr;
528 key = HASH(host_addr) % TABLE_SIZE;
529 new_entry->next = permitted_hosts[key];
530 permitted_hosts[key] = new_entry;
536 * initialize the table of hosts allowed to contact the server,
537 * by reading from the file specified by the GNU_SECURE
538 * environment variable
539 * Put in the local machine, and, if a security file is specifed,
540 * add each host that is named in the file.
541 * Return the number of hosts added. **/
547 char hostname[HOSTNAMSZ];
548 unsigned int host_addr;
552 /* Make sure every entry is null */
553 for (i = 0; i < TABLE_SIZE; i++) {
554 permitted_hosts[i] = NULL;
556 gethostname(hostname, HOSTNAMSZ);
558 if ((t = internet_addr(hostname)) == -1) {
560 %s: unable to find %s in /etc/hosts or from YP\n", progname, hostname);
566 #ifdef AUTH_MAGIC_COOKIE
567 server_xauth = XauGetAuthByAddr(
569 sizeof(host_addr), (char *)&host_addr,
570 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
571 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
574 #endif /* AUTH_MAGIC_COOKIE */
576 if ((file_name = getenv("GNU_SECURE")) == NULL) {
577 /* security file not given */
579 } else if ((host_file = fopen(file_name, "r")) == NULL) {
580 /* host file didn't open/exist */
584 while ((fscanf(host_file, "%s", hostname) != EOF)) {
585 t = internet_addr(hostname);
600 * initialize server, returning an internet socket that can be listened on. **/
604 /* socket descriptor */
606 /* pointer to service information */
608 /* for local socket address */
609 struct sockaddr_in server;
610 /* ptr to return from getenv */
613 if (setup_table() == 0) {
617 /* clear out address structure */
618 memset(&server, '\0', sizeof(server));
620 /* Set up address structure for the listen socket. */
621 server.sin_family = AF_INET;
622 server.sin_addr.s_addr = INADDR_ANY;
624 /* Find the information for the gnu server
625 * in order to get the needed port number.
627 if ((ptr = getenv("GNU_PORT")) != NULL) {
628 server.sin_port = htons(atoi(ptr));
629 } else if ((sp = getservbyname("gnuserv", "tcp")) == NULL) {
630 server.sin_port = htons(DEFAULT_PORT + getuid());
632 server.sin_port = sp->s_port;
634 /* Create the listen socket. */
635 if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
637 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(server)) < 0) {
644 fprintf(stderr, "%s: unable to bind socket\n", progname);
648 /* Initiate the listen on the socket so remote users
650 if (listen(ls, 20) == -1) {
652 fprintf(stderr, "%s: unable to listen\n", progname);
658 /** handle_internet_request
659 * accept a request from a client and send the information
660 * to stdout (the gnu process). **/
662 handle_internet_request(int ls)
665 socklen_t addrlen = sizeof(struct sockaddr_in);
666 /* for peer socket address */
667 struct sockaddr_in peer;
669 memset(&peer, '\0', sizeof(peer));
671 if ((s = accept(ls, (struct sockaddr*)&peer, &addrlen)) == -1) {
673 fprintf(stderr, "%s: unable to accept\n", progname);
677 /* Check that access is allowed - if not return crud to the client */
678 if (!permitted(peer.sin_addr.s_addr, s)) {
680 gnudoit: Connection refused\ngnudoit: unable to connect to remote");
683 printf("Refused connection from %s\n",
684 inet_ntoa(peer.sin_addr));
689 # endif /* INTERNET_DOMAIN_SOCKETS */
691 # ifdef UNIX_DOMAIN_SOCKETS
693 * initialize server, returning an unix-domain socket
694 * that can be listened on. **/
698 /* socket descriptor */
700 /* unix socket address */
701 struct sockaddr_un server;
705 if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
707 fprintf(stderr, "%s: unable to create socket\n", progname);
711 /* Set up address structure for the listen socket. */
712 # ifdef HIDE_UNIX_SOCKET
713 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
714 "%s/gsrvdir%d", tmpdir, (int)geteuid());
715 if (mkdir(server.sun_path, 0700) < 0) {
716 /* assume it already exists, and try to set perms */
717 if (chmod(server.sun_path, 0700) < 0) {
719 fprintf(stderr, "%s: can't set permissions on %s\n",
720 progname, server.sun_path);
724 strcat(server.sun_path, "/gsrv");
725 /* remove old file if it exists */
726 unlink(server.sun_path);
727 # else /* !HIDE_UNIX_SOCKET */
728 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
729 "%s/gsrv%d", tmpdir, (int)geteuid());
730 /* remove old file if it exists */
731 unlink(server.sun_path);
732 #endif /* HIDE_UNIX_SOCKET */
734 server.sun_family = AF_UNIX;
735 # ifdef HAVE_SOCKADDR_SUN_LEN
736 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
738 bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
739 + strlen(server.sun_path) + 1);
740 server.sun_len = bindlen;
741 #else /* !HAVE_SOCKADDR_SUN_LEN */
742 bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
743 #endif /* HAVE_SOCKADDR_SUN_LEN */
745 if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
747 fprintf(stderr, "%s: unable to bind socket\n", progname);
750 /* only this user can send commands */
751 chmod(server.sun_path, 0700);
753 if (listen(ls, 20) < 0) {
755 fprintf(stderr, "%s: unable to listen\n", progname);
759 /* #### there are also better ways of dealing with this when
760 sigvec() is present. */
761 # if defined (HAVE_SIGPROCMASK)
765 sigaddset(&_mask, SIGPIPE);
766 sigprocmask(SIG_BLOCK, &_mask, NULL);
768 # else /* !HAVE_SIGPROCMASK */
769 signal(SIGPIPE, SIG_IGN); /* in case user kills client */
770 # endif /* HAVE_SIGPROCMASK */
774 /** handle_unix_request
775 * accept a request from a client and send the information
776 * to stdout (the gnu process). **/
778 handle_unix_request(int ls)
781 socklen_t len = sizeof(struct sockaddr_un);
782 /* for unix socket address */
783 struct sockaddr_un server;
785 server.sun_family = AF_UNIX;
787 if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
789 fprintf(stderr, "%s: unable to accept\n", progname);
794 # endif /* UNIX_DOMAIN_SOCKETS */
798 main(int argc, char *argv[])
800 /* temporary channel number */
805 # else /* !SYSV_IPC */
806 /* internet domain listen socket */
808 /* unix domain listen socket */
810 # endif /* SYSV_IPC */
816 /* close unwanted channels */
817 for (chan = 3; chan < _NFILE; close(chan++));
820 tmpdir = getenv("TMPDIR");
821 #endif /* USE_TMPDIR */
828 /* this is to allow ^D to pass to emacs */
830 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
832 #endif /* USE_LITOUT */
835 /* get a msqid to listen on, and a message buffer */
837 #endif /* SYSV_IPC */
839 #ifdef INTERNET_DOMAIN_SOCKETS
840 /* get an internet domain socket to listen on */
841 ils = internet_init();
842 #endif /* INTERNET_DOMAIN_SOCKETS */
844 #ifdef UNIX_DOMAIN_SOCKETS
845 /* get a unix domain socket to listen on */
847 #endif /* UNIX_DOMAIN_SOCKETS */
851 handle_ipc_request(msgp);
852 # else /* !SYSV_IPC */
857 FD_SET(fileno(stdin), &rmask);
866 max_socks = max2(fileno(stdin), max2(uls, ils));
867 if (select(max_socks + 1, &rmask, NULL, NULL, NULL) < 0) {
869 fprintf(stderr, "%s: unable to select\n", progname);
872 # ifdef UNIX_DOMAIN_SOCKETS
873 if (uls > 0 && FD_ISSET(uls, &rmask)) {
874 handle_unix_request(uls);
876 # endif /* UNIX_DOMAIN_SOCKETS */
878 # ifdef INTERNET_DOMAIN_SOCKETS
879 if (ils > 0 && FD_ISSET(ils, &rmask)) {
880 handle_internet_request(ils);
882 # endif /* INTERNET_DOMAIN_SOCKETS */
884 /* from stdin (gnu process) */
885 if (FD_ISSET(fileno(stdin), &rmask)) {
888 # endif /* NOT SYSV_IPC */
894 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */