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, sizeof(buf));
198 printf("%d %s", ipc_qid, buf);
201 /* now for the response from gnu */
202 msgp->mtext[0] = '\0';
204 /* read in "n/m:" (n=client fd, m=message length) */
205 while (offset < (GSERV_BUFSZ - 1) &&
206 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
212 fprintf(stderr, "%s: unable to read\n", progname);
216 /* parse the response from emacs, getting client fd & result length */
218 sscanf(buf, "%d/%d", &s, &result_len);
220 while (result_len > 0) {
221 len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1));
224 fprintf(stderr, "%s: unable to read\n", progname);
228 /* Send this string off, but only if we have enough space */
229 if (GSERV_BUFSZ > total) {
230 if (total + len <= GSERV_BUFSZ) {
233 buf[GSERV_BUFSZ - total] = 0;
236 total += strlen(buf);
242 /* eat the newline */
243 while ((len = read(0, buf, 1)) == 0);
247 fprintf(stderr, "%s: unable to read\n", progname);
250 if (buf[0] != '\n') {
251 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
256 /* Send a response back to the client. */
257 msgp->mtype = msg_st.msg_lspid;
258 if (msgsnd(ipc_qid, msgp, strlen(msgp->mtext) + 1, 0) < 0) {
259 perror("msgsend(gnuserv)");
263 # endif /* SYSV_IPC */
265 # if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
267 * read request from a given socket descriptor, and send the information
268 * to stdout (the gnu process). **/
272 char buf[GSERV_BUFSZ];
277 /* read until we get a newline or no characters */
278 while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
282 if (buf[len - 1] == EOT_CHR) {
291 fprintf(stderr, "%s: unable to recv\n", progname);
298 * accept a response from stdin (the gnu process) and pass the
299 * information on to the relevant client. **/
301 handle_response(void)
303 char buf[GSERV_BUFSZ + 1];
309 /* read in "n/m:" (n=client fd, m=message length) */
310 while (offset < GSERV_BUFSZ &&
311 ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
317 fprintf(stderr, "%s: unable to read\n", progname);
321 /* parse the response from emacs, getting client fd & result length */
323 sscanf(buf, "%d/%d", &s, &result_len);
325 while (result_len > 0) {
326 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
328 fprintf(stderr, "%s: unable to read\n", progname);
336 /* eat the newline */
337 while ((len = read(0, buf, 1)) == 0) ;
340 fprintf(stderr, "%s: unable to read\n", progname);
343 if (buf[0] != '\n') {
344 fprintf(stderr, "%s: garbage after result\n", progname);
347 /* send the newline */
353 # endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
355 # ifdef INTERNET_DOMAIN_SOCKETS
357 unsigned long host_addr;
361 struct entry *permitted_hosts[TABLE_SIZE];
363 # ifdef AUTH_MAGIC_COOKIE
365 # include <X11/Xauth.h>
367 static Xauth *server_xauth = NULL;
368 # endif /* AUTH_MAGIC_COOKIE */
371 timed_read(int fd, char *buf, int max, int timeout, int one_line)
374 /* = {timeout, 0}; */
387 r = select(fd + 1, &rmask, NULL, NULL, &tv);
390 if (read(fd, &c, 1) == 1) {
394 printf("read error on socket\004\n");
398 printf("read timed out\004\n");
401 printf("error in select\004\n");
404 } while ((nbytes < max) && !(one_line && (c == '\n')));
407 if (one_line && *buf == '\n') {
414 * return whether a given host is allowed to connect to the server. **/
416 permitted(unsigned long host_addr, int fd)
421 char auth_protocol[128];
425 /* we are checking permission on a real connection */
427 long int auth_data_len;
429 /* Read auth protocol name */
430 if ((len = timed_read(
432 AUTH_NAMESZ, AUTH_TIMEOUT, 1)) <= 0) {
436 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
437 strcmp(auth_protocol, MCOOKIE_NAME)) {
438 printf("authentication protocol (%s) \
439 from client is invalid...\n\
440 ... Was the client an old version of gnuclient?\n", auth_protocol);
444 if (strcmp(auth_protocol, MCOOKIE_NAME)) {
449 * doing magic cookie auth
452 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0) {
455 auth_data_len = strtol(buf, NULL, 10);
457 if (auth_data_len <= 0 || (size_t)auth_data_len > sizeof(buf)) {
461 len = timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0);
462 if (len != auth_data_len) {
466 #ifdef AUTH_MAGIC_COOKIE
467 if (server_xauth && server_xauth->data) {
468 /* Do a compare without comprising info about
469 the size of the cookie */
471 int auth_mismatches =
472 (auth_data_len ^ server_xauth->data_length);
474 for (auth_data_pos = 0;
475 auth_data_pos < auth_data_len;
478 (buf[auth_data_pos] ^ server_xauth->
480 server_xauth->data_length]);
482 if (auth_mismatches == 0) {
485 for (; rand() % 1000;);
487 #else /* !AUTH_MAGIC_COOKIE */
489 client tried Xauth, but server is not compiled with Xauth\n", stdout);
490 #endif /* AUTH_MAGIC_COOKIE */
493 * auth failed, but allow this to fall through to the GNU_SECURE
497 Xauth authentication failed, trying GNU_SECURE auth...\n", stdout);
501 /* Now, try the old GNU_SECURE stuff... */
503 /* First find the hash key */
504 key = HASH(host_addr) % TABLE_SIZE;
506 /* Now check the chain for that hash key */
507 for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next) {
508 if (host_addr == entry->host_addr) {
516 * add the given host to the list of permitted hosts, provided it isn't
519 add_host(unsigned long host_addr)
522 struct entry *new_entry;
524 if (!permitted(host_addr, -1)) {
525 new_entry = (struct entry *)malloc(sizeof(struct entry));
526 if (new_entry == NULL) {
528 %s: unable to malloc space for permitted host entry\n", progname);
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 * initialize the table of hosts allowed to contact the server,
542 * by reading from the file specified by the GNU_SECURE
543 * environment variable
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. **/
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\n", progname, hostname);
571 #ifdef AUTH_MAGIC_COOKIE
572 server_xauth = XauGetAuthByAddr(
574 sizeof(host_addr), (char *)&host_addr,
575 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
576 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
579 #endif /* AUTH_MAGIC_COOKIE */
581 if ((file_name = getenv("GNU_SECURE")) == NULL) {
582 /* security file not given */
584 } else if ((host_file = fopen(file_name, "r")) == NULL) {
585 /* host file didn't open/exist */
589 while ((fscanf(host_file, "%s", hostname) != EOF)) {
590 t = internet_addr(hostname);
605 * initialize server, returning an internet socket that can be listened on. **/
609 /* socket descriptor */
611 /* pointer to service information */
613 /* for local socket address */
614 struct sockaddr_in server;
615 /* ptr to return from getenv */
618 if (setup_table() == 0) {
622 /* clear out address structure */
623 memset(&server, '\0', sizeof(server));
625 /* Set up address structure for the listen socket. */
626 server.sin_family = AF_INET;
627 server.sin_addr.s_addr = INADDR_ANY;
629 /* Find the information for the gnu server
630 * in order to get the needed port number.
632 if ((ptr = getenv("GNU_PORT")) != NULL) {
633 server.sin_port = htons(atoi(ptr));
634 } else if ((sp = getservbyname("gnuserv", "tcp")) == NULL) {
635 server.sin_port = htons(DEFAULT_PORT + getuid());
637 server.sin_port = sp->s_port;
639 /* Create the listen socket. */
640 if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
642 fprintf(stderr, "%s: unable to create socket\n", progname);
646 /* Bind the listen address to the socket. */
647 if (bind(ls, (struct sockaddr*)&server, sizeof(server)) < 0) {
649 fprintf(stderr, "%s: unable to bind socket\n", progname);
653 /* Initiate the listen on the socket so remote users
655 if (listen(ls, 20) == -1) {
657 fprintf(stderr, "%s: unable to listen\n", progname);
663 /** handle_internet_request
664 * accept a request from a client and send the information
665 * to stdout (the gnu process). **/
667 handle_internet_request(int ls)
670 socklen_t addrlen = sizeof(struct sockaddr_in);
671 /* for peer socket address */
672 struct sockaddr_in peer;
674 memset(&peer, '\0', sizeof(peer));
676 if ((s = accept(ls, (struct sockaddr*)&peer, &addrlen)) == -1) {
678 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 gnuclient: Connection refused\ngnuclient: unable to connect to remote");
688 printf("Refused connection from %s\n",
689 inet_ntoa(peer.sin_addr));
694 # endif /* INTERNET_DOMAIN_SOCKETS */
696 # ifdef UNIX_DOMAIN_SOCKETS
698 * initialize server, returning an unix-domain socket
699 * that can be listened on. **/
703 /* socket descriptor */
705 /* unix socket address */
706 struct sockaddr_un server;
710 if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
712 fprintf(stderr, "%s: unable to create socket\n", progname);
716 /* Set up address structure for the listen socket. */
717 # ifdef HIDE_UNIX_SOCKET
718 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
719 "%s/gsrvdir%d", tmpdir, (int)geteuid());
720 if (mkdir(server.sun_path, 0700) < 0) {
721 /* assume it already exists, and try to set perms */
722 if (chmod(server.sun_path, 0700) < 0) {
724 fprintf(stderr, "%s: can't set permissions on %s\n",
725 progname, server.sun_path);
729 strcat(server.sun_path, "/gsrv");
730 /* remove old file if it exists */
731 unlink(server.sun_path);
732 # else /* !HIDE_UNIX_SOCKET */
733 SNPRINTF(sz, server.sun_path, sizeof(server.sun_path),
734 "%s/gsrv%d", tmpdir, (int)geteuid());
735 /* remove old file if it exists */
736 unlink(server.sun_path);
737 #endif /* HIDE_UNIX_SOCKET */
739 server.sun_family = AF_UNIX;
740 # ifdef HAVE_SOCKADDR_SUN_LEN
741 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
743 bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
744 + strlen(server.sun_path) + 1);
745 server.sun_len = bindlen;
746 #else /* !HAVE_SOCKADDR_SUN_LEN */
747 bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
748 #endif /* HAVE_SOCKADDR_SUN_LEN */
750 if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
752 fprintf(stderr, "%s: unable to bind socket\n", progname);
755 /* only this user can send commands */
756 chmod(server.sun_path, 0700);
758 if (listen(ls, 20) < 0) {
760 fprintf(stderr, "%s: unable to listen\n", progname);
764 /* #### there are also better ways of dealing with this when
765 sigvec() is present. */
766 # if defined (HAVE_SIGPROCMASK)
770 sigaddset(&_mask, SIGPIPE);
771 sigprocmask(SIG_BLOCK, &_mask, NULL);
773 # else /* !HAVE_SIGPROCMASK */
774 signal(SIGPIPE, SIG_IGN); /* in case user kills client */
775 # endif /* HAVE_SIGPROCMASK */
779 /** handle_unix_request
780 * accept a request from a client and send the information
781 * to stdout (the gnu process). **/
783 handle_unix_request(int ls)
786 socklen_t len = sizeof(struct sockaddr_un);
787 /* for unix socket address */
788 struct sockaddr_un server;
790 server.sun_family = AF_UNIX;
792 if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
794 fprintf(stderr, "%s: unable to accept\n", progname);
795 /* Nothing more we can do here... */
801 # endif /* UNIX_DOMAIN_SOCKETS */
805 main(int argc, char *argv[])
807 /* temporary channel number */
812 # else /* !SYSV_IPC */
813 /* internet domain listen socket */
815 /* unix domain listen socket */
817 # endif /* SYSV_IPC */
823 /* close unwanted channels */
824 for (chan = 3; chan < _NFILE; close(chan++));
827 tmpdir = getenv("TMPDIR");
828 #endif /* USE_TMPDIR */
835 /* this is to allow ^D to pass to emacs */
837 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
839 #endif /* USE_LITOUT */
842 /* get a msqid to listen on, and a message buffer */
844 #endif /* SYSV_IPC */
846 #ifdef INTERNET_DOMAIN_SOCKETS
847 /* get an internet domain socket to listen on */
848 ils = internet_init();
849 #endif /* INTERNET_DOMAIN_SOCKETS */
851 #ifdef UNIX_DOMAIN_SOCKETS
852 /* get a unix domain socket to listen on */
854 #endif /* UNIX_DOMAIN_SOCKETS */
858 handle_ipc_request(msgp);
859 # else /* !SYSV_IPC */
864 FD_SET(fileno(stdin), &rmask);
873 max_socks = max2(fileno(stdin), max2(uls, ils));
874 if (select(max_socks + 1, &rmask, NULL, NULL, NULL) < 0) {
876 fprintf(stderr, "%s: unable to select\n", progname);
879 # ifdef UNIX_DOMAIN_SOCKETS
880 if (uls > 0 && FD_ISSET(uls, &rmask)) {
881 handle_unix_request(uls);
883 # endif /* UNIX_DOMAIN_SOCKETS */
885 # ifdef INTERNET_DOMAIN_SOCKETS
886 if (ils > 0 && FD_ISSET(ils, &rmask)) {
887 handle_internet_request(ils);
889 # endif /* INTERNET_DOMAIN_SOCKETS */
891 /* from stdin (gnu process) */
892 if (FD_ISSET(fileno(stdin), &rmask)) {
895 # endif /* NOT SYSV_IPC */
901 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */