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 #define xstrncpy(d_,s_,l_) \
66 strncat((dst_),(s_),(l_)-1); \
70 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
71 !defined(INTERNET_DOMAIN_SOCKETS)
75 fputs("Sorry, the Emacs server is only supported on systems that have\n\
76 Unix Domain sockets, Internet Domain sockets or System V IPC\n", stderr);
79 #else /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
83 /* ipc message queue id */
85 /* watchdog task pid */
89 * clean up the queue id and queue, then kill the watchdog task
90 * if it exists. exit with the given status. **/
92 __attribute__((noreturn))
95 msgctl(ipc_qid, IPC_RMID, 0);
98 kill(ipc_wpid, SIGKILL);
103 /** ipc_handle_signal
104 * catch the signal given and clean up. **/
106 ipc_handle_signal(int sig)
111 /** ipc_spawn_watchdog
112 * spawn a watchdog task to clean up the message queue should the
113 * server process die. **/
115 ipc_spawn_watchdog(void)
118 if ((ipc_wpid = fork()) == 0) {
119 /* parent's process id */
120 pid_t ppid = getppid();
122 /* gnu kills process group on exit */
126 /* ppid is no longer valid, parent may have died */
127 if (kill(ppid, 0) < 0) {
130 /* else, have another go later */
138 * initialize server, setting the global msqid that can be listened on. **/
140 ipc_init(struct msgbuf **msgpp)
144 /* pathname for key */
145 char buf[GSERV_BUFSZ];
148 SNPRINTF(sz, buf, sizeof(buf),"%s/gsrv%d", tmpdir, (int)geteuid());
152 if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
154 fprintf(stderr, "%s: unable to create msg queue\n", progname);
157 ipc_spawn_watchdog();
159 signal(SIGTERM, ipc_handle_signal);
160 signal(SIGINT, ipc_handle_signal);
162 *msgpp = (struct msgbuf*)malloc(sizeof **msgpp + GSERV_BUFSZ);
163 if (*msgpp == NULL) {
165 "%s: unable to allocate space for message buffer\n",
172 /** handle_ipc_request
173 * accept a request from a client, pass the request on to the GNU Emacs process,
174 * then wait for its reply and pass that on to the client. **/
176 handle_ipc_request(struct msgbuf *msgp)
179 struct msqid_ds msg_st;
180 char buf[GSERV_BUFSZ];
181 /* length of message / read */
183 /* tag fields on the response from emacs */
186 /* # bytes that will actually be sent off */
189 if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
191 fprintf(stderr, "%s: unable to receive\n", progname);
195 msgctl(ipc_qid, IPC_STAT, &msg_st);
196 xstrncpy(buf, msgp->mtext, len);
200 printf("%d %s", ipc_qid, buf);
203 /* now for the response from gnu */
204 msgp->mtext[0] = '\0';
206 /* read in "n/m:" (n=client fd, m=message length) */
207 while (offset < (GSERV_BUFSZ - 1) &&
208 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
214 fprintf(stderr, "%s: unable to read\n", progname);
218 /* parse the response from emacs, getting client fd & result length */
220 sscanf(buf, "%d/%d", &s, &result_len);
222 while (result_len > 0) {
223 len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1));
226 fprintf(stderr, "%s: unable to read\n", progname);
230 /* Send this string off, but only if we have enough space */
231 if (GSERV_BUFSZ > total) {
232 if (total + len <= GSERV_BUFSZ) {
235 buf[GSERV_BUFSZ - total] = 0;
238 total += strlen(buf);
244 /* eat the newline */
245 while ((len = read(0, buf, 1)) == 0);
249 fprintf(stderr, "%s: unable to read\n", progname);
252 if (buf[0] != '\n') {
253 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
258 /* Send a response back to the client. */
259 msgp->mtype = msg_st.msg_lspid;
260 if (msgsnd(ipc_qid, msgp, strlen(msgp->mtext) + 1, 0) < 0) {
261 perror("msgsend(gnuserv)");
265 # endif /* SYSV_IPC */
267 # if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
269 * read request from a given socket descriptor, and send the information
270 * to stdout (the gnu process). **/
274 char buf[GSERV_BUFSZ];
279 /* read until we get a newline or no characters */
280 while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
284 if (buf[len - 1] == EOT_CHR) {
293 fprintf(stderr, "%s: unable to recv\n", progname);
300 * accept a response from stdin (the gnu process) and pass the
301 * information on to the relevant client. **/
303 handle_response(void)
305 char buf[GSERV_BUFSZ + 1];
311 /* read in "n/m:" (n=client fd, m=message length) */
312 while (offset < GSERV_BUFSZ &&
313 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
319 fprintf(stderr, "%s: unable to read\n", progname);
323 /* parse the response from emacs, getting client fd & result length */
325 sscanf(buf, "%d/%d", &s, &result_len);
327 while (result_len > 0) {
328 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
330 fprintf(stderr, "%s: unable to read\n", progname);
338 /* eat the newline */
339 while ((len = read(0, buf, 1)) == 0) ;
342 fprintf(stderr, "%s: unable to read\n", progname);
345 if (buf[0] != '\n') {
346 fprintf(stderr, "%s: garbage after result\n", progname);
349 /* send the newline */
355 # endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
357 # ifdef INTERNET_DOMAIN_SOCKETS
359 unsigned long host_addr;
363 struct entry *permitted_hosts[TABLE_SIZE];
365 # ifdef AUTH_MAGIC_COOKIE
367 # include <X11/Xauth.h>
369 static Xauth *server_xauth = NULL;
370 # endif /* AUTH_MAGIC_COOKIE */
373 timed_read(int fd, char *buf, int max, int timeout, int one_line)
376 /* = {timeout, 0}; */
389 r = select(fd + 1, &rmask, NULL, NULL, &tv);
392 if (read(fd, &c, 1) == 1) {
396 printf("read error on socket\004\n");
400 printf("read timed out\004\n");
403 printf("error in select\004\n");
406 } while ((nbytes < max) && !(one_line && (c == '\n')));
409 if (one_line && *buf == '\n') {
416 * return whether a given host is allowed to connect to the server. **/
418 permitted(unsigned long host_addr, int fd)
423 char auth_protocol[128];
427 /* we are checking permission on a real connection */
429 long int auth_data_len;
431 /* Read auth protocol name */
432 if ((len = timed_read(
434 AUTH_NAMESZ, AUTH_TIMEOUT, 1)) <= 0) {
438 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
439 strcmp(auth_protocol, MCOOKIE_NAME)) {
440 printf("authentication protocol (%s) \
441 from client is invalid...\n\
442 ... Was the client an old version of gnuclient?\n", auth_protocol);
446 if (strcmp(auth_protocol, MCOOKIE_NAME)) {
451 * doing magic cookie auth
454 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0) {
457 auth_data_len = strtol(buf, NULL, 10);
459 if (auth_data_len <= 0 || (size_t)auth_data_len > sizeof(buf)) {
463 len = timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0);
464 if (len != auth_data_len) {
468 #ifdef AUTH_MAGIC_COOKIE
469 if (server_xauth && server_xauth->data) {
470 /* Do a compare without comprising info about
471 the size of the cookie */
473 int auth_mismatches =
474 (auth_data_len ^ server_xauth->data_length);
476 for (auth_data_pos = 0;
477 auth_data_pos < auth_data_len;
480 (buf[auth_data_pos] ^ server_xauth->
482 server_xauth->data_length]);
484 if (auth_mismatches == 0) {
487 for (; rand() % 1000;);
489 #else /* !AUTH_MAGIC_COOKIE */
491 client tried Xauth, but server is not compiled with Xauth\n", stdout);
492 #endif /* AUTH_MAGIC_COOKIE */
495 * auth failed, but allow this to fall through to the GNU_SECURE
499 Xauth authentication failed, trying GNU_SECURE auth...\n", stdout);
503 /* Now, try the old GNU_SECURE stuff... */
505 /* First find the hash key */
506 key = HASH(host_addr) % TABLE_SIZE;
508 /* Now check the chain for that hash key */
509 for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next) {
510 if (host_addr == entry->host_addr) {
518 * add the given host to the list of permitted hosts, provided it isn't
521 add_host(unsigned long host_addr)
524 struct entry *new_entry;
526 if (!permitted(host_addr, -1)) {
527 new_entry = (struct entry *)malloc(sizeof(struct entry));
528 if (new_entry == NULL) {
530 %s: unable to malloc space for permitted host entry\n", progname);
534 new_entry->host_addr = host_addr;
535 key = HASH(host_addr) % TABLE_SIZE;
536 new_entry->next = permitted_hosts[key];
537 permitted_hosts[key] = new_entry;
543 * initialize the table of hosts allowed to contact the server,
544 * by reading from the file specified by the GNU_SECURE
545 * environment variable
546 * Put in the local machine, and, if a security file is specifed,
547 * add each host that is named in the file.
548 * Return the number of hosts added. **/
554 char hostname[HOSTNAMSZ];
555 unsigned int host_addr;
559 /* Make sure every entry is null */
560 for (i = 0; i < TABLE_SIZE; i++) {
561 permitted_hosts[i] = NULL;
563 gethostname(hostname, HOSTNAMSZ);
565 if ((t = internet_addr(hostname)) == -1) {
567 %s: unable to find %s in /etc/hosts or from YP\n", progname, hostname);
573 #ifdef AUTH_MAGIC_COOKIE
574 server_xauth = XauGetAuthByAddr(
576 sizeof(host_addr), (char *)&host_addr,
577 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
578 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
581 #endif /* AUTH_MAGIC_COOKIE */
583 if ((file_name = getenv("GNU_SECURE")) == NULL) {
584 /* security file not given */
586 } else if ((host_file = fopen(file_name, "r")) == NULL) {
587 /* host file didn't open/exist */
591 while ((fscanf(host_file, "%s", hostname) != EOF)) {
592 t = internet_addr(hostname);
607 * initialize server, returning an internet socket that can be listened on. **/
611 /* socket descriptor */
613 /* pointer to service information */
615 /* for local socket address */
616 struct sockaddr_in server;
617 /* ptr to return from getenv */
620 if (setup_table() == 0) {
624 /* clear out address structure */
625 memset(&server, '\0', sizeof(server));
627 /* Set up address structure for the listen socket. */
628 server.sin_family = AF_INET;
629 server.sin_addr.s_addr = INADDR_ANY;
631 /* Find the information for the gnu server
632 * in order to get the needed port number.
634 if ((ptr = getenv("GNU_PORT")) != NULL) {
635 server.sin_port = htons(atoi(ptr));
636 } else if ((sp = getservbyname("gnuserv", "tcp")) == NULL) {
637 server.sin_port = htons(DEFAULT_PORT + getuid());
639 server.sin_port = sp->s_port;
641 /* Create the listen socket. */
642 if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
644 fprintf(stderr, "%s: unable to create socket\n", progname);
648 /* Bind the listen address to the socket. */
649 if (bind(ls, (struct sockaddr*)&server, sizeof(server)) < 0) {
651 fprintf(stderr, "%s: unable to bind socket\n", progname);
655 /* Initiate the listen on the socket so remote users
657 if (listen(ls, 20) == -1) {
659 fprintf(stderr, "%s: unable to listen\n", progname);
665 /** handle_internet_request
666 * accept a request from a client and send the information
667 * to stdout (the gnu process). **/
669 handle_internet_request(int ls)
672 socklen_t addrlen = sizeof(struct sockaddr_in);
673 /* for peer socket address */
674 struct sockaddr_in peer;
676 memset(&peer, '\0', sizeof(peer));
678 if ((s = accept(ls, (struct sockaddr*)&peer, &addrlen)) == -1) {
680 fprintf(stderr, "%s: unable to accept\n", progname);
684 /* Check that access is allowed - if not return crud to the client */
685 if (!permitted(peer.sin_addr.s_addr, s)) {
687 gnuclient: Connection refused\ngnuclient: unable to connect to remote");
690 printf("Refused connection from %s\n",
691 inet_ntoa(peer.sin_addr));
696 # endif /* INTERNET_DOMAIN_SOCKETS */
698 # ifdef UNIX_DOMAIN_SOCKETS
700 * initialize server, returning an unix-domain socket
701 * that can be listened on. **/
705 /* socket descriptor */
707 /* unix socket address */
708 struct sockaddr_un server;
712 if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
714 fprintf(stderr, "%s: unable to create socket\n", progname);
718 /* Set up address structure for the listen socket. */
719 # ifdef HIDE_UNIX_SOCKET
720 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
721 "%s/gsrvdir%d", tmpdir, (int)geteuid());
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 /* remove old file if it exists */
733 unlink(server.sun_path);
734 # else /* !HIDE_UNIX_SOCKET */
735 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
736 "%s/gsrv%d", tmpdir, (int)geteuid());
737 /* remove old file if it exists */
738 unlink(server.sun_path);
739 #endif /* HIDE_UNIX_SOCKET */
741 server.sun_family = AF_UNIX;
742 # ifdef HAVE_SOCKADDR_SUN_LEN
743 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
745 bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
746 + strlen(server.sun_path) + 1);
747 server.sun_len = bindlen;
748 #else /* !HAVE_SOCKADDR_SUN_LEN */
749 bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
750 #endif /* HAVE_SOCKADDR_SUN_LEN */
752 if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
754 fprintf(stderr, "%s: unable to bind socket\n", progname);
757 /* only this user can send commands */
758 chmod(server.sun_path, 0700);
760 if (listen(ls, 20) < 0) {
762 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);
775 # else /* !HAVE_SIGPROCMASK */
776 signal(SIGPIPE, SIG_IGN); /* in case user kills client */
777 # endif /* HAVE_SIGPROCMASK */
781 /** handle_unix_request
782 * accept a request from a client and send the information
783 * to stdout (the gnu process). **/
785 handle_unix_request(int ls)
788 socklen_t len = sizeof(struct sockaddr_un);
789 /* for unix socket address */
790 struct sockaddr_un server;
792 server.sun_family = AF_UNIX;
794 if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
796 fprintf(stderr, "%s: unable to accept\n", progname);
797 /* Nothing more we can do here... */
803 # endif /* UNIX_DOMAIN_SOCKETS */
807 main(int argc, char *argv[])
809 /* temporary channel number */
814 # else /* !SYSV_IPC */
815 /* internet domain listen socket */
817 /* unix domain listen socket */
819 # endif /* SYSV_IPC */
825 /* close unwanted channels */
826 for (chan = 3; chan < _NFILE; close(chan++));
829 tmpdir = getenv("TMPDIR");
830 #endif /* USE_TMPDIR */
837 /* this is to allow ^D to pass to emacs */
839 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
841 #endif /* USE_LITOUT */
844 /* get a msqid to listen on, and a message buffer */
846 #endif /* SYSV_IPC */
848 #ifdef INTERNET_DOMAIN_SOCKETS
849 /* get an internet domain socket to listen on */
850 ils = internet_init();
851 #endif /* INTERNET_DOMAIN_SOCKETS */
853 #ifdef UNIX_DOMAIN_SOCKETS
854 /* get a unix domain socket to listen on */
856 #endif /* UNIX_DOMAIN_SOCKETS */
860 handle_ipc_request(msgp);
861 # else /* !SYSV_IPC */
866 FD_SET(fileno(stdin), &rmask);
875 max_socks = max2(fileno(stdin), max2(uls, ils));
876 if (select(max_socks + 1, &rmask, NULL, NULL, NULL) < 0) {
878 fprintf(stderr, "%s: unable to select\n", progname);
881 # ifdef UNIX_DOMAIN_SOCKETS
882 if (uls > 0 && FD_ISSET(uls, &rmask)) {
883 handle_unix_request(uls);
885 # endif /* UNIX_DOMAIN_SOCKETS */
887 # ifdef INTERNET_DOMAIN_SOCKETS
888 if (ils > 0 && FD_ISSET(ils, &rmask)) {
889 handle_internet_request(ils);
891 # endif /* INTERNET_DOMAIN_SOCKETS */
893 /* from stdin (gnu process) */
894 if (FD_ISSET(fileno(stdin), &rmask)) {
897 # endif /* NOT SYSV_IPC */
903 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */