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)
34 char gnuserv_version[] = "gnuserv version" GNUSERV_VERSION;
38 #include <bsd/sgtty.h>
45 #include <sys/select.h>
50 #include <sys/types.h>
55 #endif /* HAVE_UNISTD_H */
59 #endif /* HAVE_STRING_H */
61 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
62 !defined(INTERNET_DOMAIN_SOCKETS)
66 "Sorry, the Emacs server is only supported on systems that have\n");
68 "Unix Domain sockets, Internet Domain sockets or System V IPC\n");
71 #else /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
75 int ipc_qid = 0; /* ipc message queue id */
76 pid_t ipc_wpid = 0; /* watchdog task pid */
79 ipc_exit -- clean up the queue id and queue, then kill the watchdog task
80 if it exists. exit with the given status.
82 void ipc_exit(int stat)
84 msgctl(ipc_qid, IPC_RMID, 0);
87 kill(ipc_wpid, SIGKILL);
93 ipc_handle_signal -- catch the signal given and clean up.
95 void ipc_handle_signal(int sig)
98 } /* ipc_handle_signal */
101 ipc_spawn_watchdog -- spawn a watchdog task to clean up the message queue should the
104 void ipc_spawn_watchdog(void)
106 if ((ipc_wpid = fork()) == 0) { /* child process */
107 pid_t ppid = getppid(); /* parent's process id */
109 setpgrp(); /* gnu kills process group on exit */
112 if (kill(ppid, 0) < 0) { /* ppid is no longer valid, parent
117 sleep(10); /* have another go later */
121 } /* ipc_spawn_watchdog */
124 ipc_init -- initialize server, setting the global msqid that can be listened on.
126 void ipc_init(struct msgbuf **msgpp)
128 key_t key; /* messge key */
129 char buf[GSERV_BUFSZ]; /* pathname for key */
131 sprintf(buf, "%s/gsrv%d", tmpdir, (int)geteuid());
135 if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
137 fprintf(stderr, "%s: unable to create msg queue\n", progname);
141 ipc_spawn_watchdog();
143 signal(SIGTERM, ipc_handle_signal);
144 signal(SIGINT, ipc_handle_signal);
146 if ((*msgpp = (struct msgbuf *)
147 malloc(sizeof **msgpp + GSERV_BUFSZ)) == NULL) {
149 "%s: unable to allocate space for message buffer\n",
156 handle_ipc_request -- accept a request from a client, pass the request on
157 to the GNU Emacs process, then wait for its reply and
158 pass that on to the client.
160 void handle_ipc_request(struct msgbuf *msgp)
162 struct msqid_ds msg_st; /* message status */
163 char buf[GSERV_BUFSZ];
164 int len; /* length of message / read */
165 int s, result_len; /* tag fields on the response from emacs */
167 int total = 1; /* # bytes that will actually be sent off */
169 if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
171 fprintf(stderr, "%s: unable to receive\n", progname);
175 msgctl(ipc_qid, IPC_STAT, &msg_st);
176 strncpy(buf, msgp->mtext, len);
177 buf[len] = '\0'; /* terminate */
179 printf("%d %s", ipc_qid, buf);
182 /* now for the response from gnu */
183 msgp->mtext[0] = '\0';
186 if ((len = read(0, buf, GSERV_BUFSZ - 1)) < 0) {
188 fprintf(stderr, "%s: unable to read\n", progname);
192 sscanf(buf, "%d:%[^\n]\n", &junk, msgp->mtext);
195 /* read in "n/m:" (n=client fd, m=message length) */
197 while (offset < (GSERV_BUFSZ - 1) &&
198 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
204 fprintf(stderr, "%s: unable to read\n", progname);
208 /* parse the response from emacs, getting client fd & result length */
210 sscanf(buf, "%d/%d", &s, &result_len);
212 while (result_len > 0) {
213 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1))) < 0) {
215 fprintf(stderr, "%s: unable to read\n", progname);
219 /* Send this string off, but only if we have enough space */
221 if (GSERV_BUFSZ > total) {
222 if (total + len <= GSERV_BUFSZ)
225 buf[GSERV_BUFSZ - total] = 0;
228 total += strlen(buf);
234 /* eat the newline */
235 while ((len = read(0, buf, 1)) == 0) ;
238 fprintf(stderr, "%s: unable to read\n", progname);
241 if (buf[0] != '\n') {
242 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
248 /* Send a response back to the client. */
250 msgp->mtype = msg_st.msg_lspid;
251 if (msgsnd(ipc_qid, msgp, strlen(msgp->mtext) + 1, 0) < 0)
252 perror("msgsend(gnuserv)");
254 } /* handle_ipc_request */
255 #endif /* SYSV_IPC */
257 #if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
259 echo_request -- read request from a given socket descriptor, and send the information
260 to stdout (the gnu process).
262 static void echo_request(int s)
264 char buf[GSERV_BUFSZ];
269 /* read until we get a newline or no characters */
270 while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
274 if (buf[len - 1] == EOT_CHR) {
276 break; /* end of message */
283 fprintf(stderr, "%s: unable to recv\n", progname);
290 handle_response -- accept a response from stdin (the gnu process) and pass the
291 information on to the relevant client.
293 static void handle_response(void)
295 char buf[GSERV_BUFSZ + 1];
301 /* read in "n/m:" (n=client fd, m=message length) */
302 while (offset < GSERV_BUFSZ &&
303 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
309 fprintf(stderr, "%s: unable to read\n", progname);
313 /* parse the response from emacs, getting client fd & result length */
315 sscanf(buf, "%d/%d", &s, &result_len);
317 while (result_len > 0) {
318 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
320 fprintf(stderr, "%s: unable to read\n", progname);
328 /* eat the newline */
329 while ((len = read(0, buf, 1)) == 0) ;
332 fprintf(stderr, "%s: unable to read\n", progname);
335 if (buf[0] != '\n') {
336 fprintf(stderr, "%s: garbage after result\n", progname);
339 /* send the newline */
344 } /* handle_response */
345 #endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
347 #ifdef INTERNET_DOMAIN_SOCKETS
349 unsigned long host_addr;
353 struct entry *permitted_hosts[TABLE_SIZE];
355 #ifdef AUTH_MAGIC_COOKIE
357 # include <X11/Xauth.h>
359 static Xauth *server_xauth = NULL;
362 static int timed_read(int fd, char *buf, int max, int timeout, int one_line)
365 struct timeval tv; /* = {timeout, 0}; */
377 r = select(fd + 1, &rmask, NULL, NULL, &tv);
380 if (read(fd, &c, 1) == 1) {
384 printf("read error on socket\004\n");
388 printf("read timed out\004\n");
391 printf("error in select\004\n");
394 } while ((nbytes < max) && !(one_line && (c == '\n')));
397 if (one_line && *buf == '\n') {
405 permitted -- return whether a given host is allowed to connect to the server.
407 static int permitted(unsigned long host_addr, int fd)
412 char auth_protocol[128];
417 /* we are checking permission on a real connection */
419 /* Read auth protocol name */
421 if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1)
425 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
426 strcmp(auth_protocol, MCOOKIE_NAME)) {
428 ("authentication protocol (%s) from client is invalid...\n",
431 ("... Was the client an old version of gnuclient/gnudoit?\004\n");
436 if (!strcmp(auth_protocol, MCOOKIE_NAME)) {
439 * doing magic cookie auth
442 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
445 auth_data_len = atoi(buf);
447 if (auth_data_len <= 0
448 || auth_data_len > (int)sizeof(buf)) {
452 if (timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0)
456 #ifdef AUTH_MAGIC_COOKIE
457 if (server_xauth && server_xauth->data) {
458 /* Do a compare without comprising info about
459 the size of the cookie */
461 int auth_mismatches =
462 (auth_data_len ^ server_xauth->data_length);
464 for (auth_data_pos = 0;
465 auth_data_pos < auth_data_len;
468 (buf[auth_data_pos] ^ server_xauth->
470 server_xauth->data_length]);
472 if (auth_mismatches == 0)
475 for (; rand() % 1000;) ;
479 ("client tried Xauth, but server is not compiled with Xauth\n");
483 * auth failed, but allow this to fall through to the GNU_SECURE
488 ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");
492 /* Other auth protocols go here, and should execute only if the
493 * auth_protocol name matches.
498 /* Now, try the old GNU_SECURE stuff... */
500 /* First find the hash key */
501 key = HASH(host_addr) % TABLE_SIZE;
503 /* Now check the chain for that hash key */
504 for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next)
505 if (host_addr == entry->host_addr)
513 add_host -- add the given host to the list of permitted hosts, provided it isn't
516 static void add_host(unsigned long host_addr)
519 struct entry *new_entry;
521 if (!permitted(host_addr, -1)) {
523 (struct entry *)malloc(sizeof(struct entry))) == NULL) {
525 "%s: unable to malloc space for permitted host entry\n",
530 new_entry->host_addr = host_addr;
531 key = HASH(host_addr) % TABLE_SIZE;
532 new_entry->next = permitted_hosts[key];
533 permitted_hosts[key] = new_entry;
539 setup_table -- initialize the table of hosts allowed to contact the server,
540 by reading from the file specified by the GNU_SECURE
542 Put in the local machine, and, if a security file is specifed,
543 add each host that is named in the file.
544 Return the number of hosts added.
546 static int setup_table(void)
550 char hostname[HOSTNAMSZ];
551 unsigned int host_addr;
555 /* Make sure every entry is null */
556 for (i = 0; i < TABLE_SIZE; i++)
557 permitted_hosts[i] = NULL;
559 gethostname(hostname, HOSTNAMSZ);
561 if ((t = internet_addr(hostname)) == -1) {
563 "%s: unable to find %s in /etc/hosts or from YP",
570 #ifdef AUTH_MAGIC_COOKIE
572 server_xauth = XauGetAuthByAddr(FamilyInternet,
573 sizeof(host_addr), (char *)&host_addr,
574 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
575 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
578 #endif /* AUTH_MAGIC_COOKIE */
580 #if 0 /* Don't even want to allow access from the local host by default */
581 add_host(host_addr); /* add local host */
584 if (((file_name = getenv("GNU_SECURE")) != NULL && /* security file */
585 (host_file = fopen(file_name, "r")) != NULL)) { /* opened ok */
586 while ((fscanf(host_file, "%s", hostname) != EOF)) { /* find a host */
587 t = internet_addr(hostname);
588 if (t != -1) { /* get its addr */
590 add_host(host_addr); /* add the addr */
601 internet_init -- initialize server, returning an internet socket that can
604 static int internet_init(void)
606 int ls; /* socket descriptor */
607 struct servent *sp; /* pointer to service information */
608 struct sockaddr_in server; /* for local socket address */
609 char *ptr; /* ptr to return from getenv */
611 if (setup_table() == 0)
614 /* clear out address structure */
615 memset(&server, '\0', sizeof(server));
617 /* Set up address structure for the listen socket. */
618 server.sin_family = AF_INET;
619 server.sin_addr.s_addr = INADDR_ANY;
621 /* Find the information for the gnu server
622 * in order to get the needed port number.
624 if ((ptr = getenv("GNU_PORT")) != NULL)
625 server.sin_port = htons(atoi(ptr));
626 else if ((sp = getservbyname("gnuserv", "tcp")) == NULL)
627 server.sin_port = htons(DEFAULT_PORT + getuid());
629 server.sin_port = sp->s_port;
631 /* Create the listen socket. */
632 if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
634 fprintf(stderr, "%s: unable to create socket\n", progname);
639 /* Bind the listen address to the socket. */
640 if (bind(ls, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) ==
643 fprintf(stderr, "%s: unable to bind socket\n", progname);
648 /* Initiate the listen on the socket so remote users
651 if (listen(ls, 20) == -1) {
653 fprintf(stderr, "%s: unable to listen\n", progname);
659 } /* internet_init */
662 handle_internet_request -- accept a request from a client and send the information
663 to stdout (the gnu process).
665 static void handle_internet_request(int ls)
668 socklen_t addrlen = sizeof(struct sockaddr_in);
669 struct sockaddr_in peer; /* for peer socket address */
671 memset(&peer, '\0', sizeof(peer));
673 if ((s = accept(ls, (struct sockaddr *)&peer, &addrlen)) == -1) {
675 fprintf(stderr, "%s: unable to accept\n", progname);
680 /* Check that access is allowed - if not return crud to the client */
681 if (!permitted(peer.sin_addr.s_addr, s)) {
683 "gnudoit: Connection refused\ngnudoit: unable to connect to remote");
686 printf("Refused connection from %s\004\n",
687 inet_ntoa(peer.sin_addr));
693 } /* handle_internet_request */
694 #endif /* INTERNET_DOMAIN_SOCKETS */
696 #ifdef UNIX_DOMAIN_SOCKETS
698 unix_init -- initialize server, returning an unix-domain socket that can
701 static int unix_init(void)
703 int ls; /* socket descriptor */
704 struct sockaddr_un server; /* unix socket address */
707 if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
709 fprintf(stderr, "%s: unable to create socket\n", progname);
714 /* Set up address structure for the listen socket. */
715 #ifdef HIDE_UNIX_SOCKET
716 sprintf(server.sun_path, "%s/gsrvdir%d", tmpdir, (int)geteuid());
717 if (mkdir(server.sun_path, 0700) < 0) {
718 /* assume it already exists, and try to set perms */
719 if (chmod(server.sun_path, 0700) < 0) {
721 fprintf(stderr, "%s: can't set permissions on %s\n",
722 progname, server.sun_path);
726 strcat(server.sun_path, "/gsrv");
727 unlink(server.sun_path); /* remove old file if it exists */
728 #else /* HIDE_UNIX_SOCKET */
729 sprintf(server.sun_path, "%s/gsrv%d", tmpdir, (int)geteuid());
730 unlink(server.sun_path); /* remove old file if it exists */
731 #endif /* HIDE_UNIX_SOCKET */
733 server.sun_family = AF_UNIX;
734 #ifdef HAVE_SOCKADDR_SUN_LEN
735 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
737 bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
738 + strlen(server.sun_path) + 1);
739 server.sun_len = bindlen;
741 bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
744 if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
746 fprintf(stderr, "%s: unable to bind socket\n", progname);
750 chmod(server.sun_path, 0700); /* only this user can send commands */
752 if (listen(ls, 20) < 0) {
754 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);
769 signal(SIGPIPE, SIG_IGN); /* in case user kills client */
777 handle_unix_request -- accept a request from a client and send the information
778 to stdout (the gnu process).
780 static void handle_unix_request(int ls)
783 socklen_t len = sizeof(struct sockaddr_un);
784 struct sockaddr_un server; /* for unix socket address */
786 server.sun_family = AF_UNIX;
788 if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
790 fprintf(stderr, "%s: unable to accept\n", progname);
795 } /* handle_unix_request */
796 #endif /* UNIX_DOMAIN_SOCKETS */
798 int main(int argc, char *argv[])
800 int chan; /* temporary channel number */
802 struct msgbuf *msgp; /* message buffer */
804 int ils = -1; /* internet domain listen socket */
805 int uls = -1; /* unix domain listen socket */
806 #endif /* SYSV_IPC */
810 for (chan = 3; chan < _NFILE; close(chan++)) /* close unwanted channels */
814 tmpdir = getenv("TMPDIR");
820 /* this is to allow ^D to pass to emacs */
822 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
827 ipc_init(&msgp); /* get a msqid to listen on, and a message buffer */
828 #endif /* SYSV_IPC */
830 #ifdef INTERNET_DOMAIN_SOCKETS
831 ils = internet_init(); /* get an internet domain socket to listen on */
832 #endif /* INTERNET_DOMAIN_SOCKETS */
834 #ifdef UNIX_DOMAIN_SOCKETS
835 uls = unix_init(); /* get a unix domain socket to listen on */
836 #endif /* UNIX_DOMAIN_SOCKETS */
840 handle_ipc_request(msgp);
841 #else /* NOT SYSV_IPC */
844 FD_SET(fileno(stdin), &rmask);
850 if (select(max2(fileno(stdin), max2(uls, ils)) + 1, &rmask,
851 (fd_set *) NULL, (fd_set *) NULL,
852 (struct timeval *)NULL) < 0) {
854 fprintf(stderr, "%s: unable to select\n", progname);
858 #ifdef UNIX_DOMAIN_SOCKETS
859 if (uls > 0 && FD_ISSET(uls, &rmask))
860 handle_unix_request(uls);
863 #ifdef INTERNET_DOMAIN_SOCKETS
864 if (ils > 0 && FD_ISSET(ils, &rmask))
865 handle_internet_request(ils);
866 #endif /* INTERNET_DOMAIN_SOCKETS */
868 if (FD_ISSET(fileno(stdin), &rmask)) /* from stdin (gnu process) */
870 #endif /* NOT SYSV_IPC */
874 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */