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;
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)
66 fprintf (stderr,"Sorry, the Emacs server is only supported on systems that have\n");
67 fprintf (stderr,"Unix Domain sockets, Internet Domain sockets or System V IPC\n");
70 #else /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
74 int ipc_qid = 0; /* ipc message queue id */
75 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.
85 msgctl (ipc_qid,IPC_RMID,0);
88 kill (ipc_wpid, SIGKILL);
95 ipc_handle_signal -- catch the signal given and clean up.
98 ipc_handle_signal(int sig)
101 } /* ipc_handle_signal */
105 ipc_spawn_watchdog -- spawn a watchdog task to clean up the message queue should the
109 ipc_spawn_watchdog (void)
111 if ((ipc_wpid = fork ()) == 0)
112 { /* child process */
113 pid_t ppid = getppid (); /* parent's process id */
115 setpgrp(); /* gnu kills process group on exit */
119 if (kill (ppid, 0) < 0) /* ppid is no longer valid, parent
125 sleep(10); /* have another go later */
129 } /* ipc_spawn_watchdog */
133 ipc_init -- initialize server, setting the global msqid that can be listened on.
136 ipc_init (struct msgbuf **msgpp)
138 key_t key; /* messge key */
139 char buf[GSERV_BUFSZ]; /* pathname for key */
141 sprintf (buf,"%s/gsrv%d",tmpdir,(int)geteuid ());
145 if ((ipc_qid = msgget (key,0600|IPC_CREAT)) == -1)
148 fprintf (stderr, "%s: unable to create msg queue\n", progname);
152 ipc_spawn_watchdog ();
154 signal (SIGTERM,ipc_handle_signal);
155 signal (SIGINT,ipc_handle_signal);
157 if ((*msgpp = (struct msgbuf *)
158 malloc (sizeof **msgpp + GSERV_BUFSZ)) == NULL)
161 "%s: unable to allocate space for message buffer\n", progname);
168 handle_ipc_request -- accept a request from a client, pass the request on
169 to the GNU Emacs process, then wait for its reply and
170 pass that on to the client.
173 handle_ipc_request (struct msgbuf *msgp)
175 struct msqid_ds msg_st; /* message status */
176 char buf[GSERV_BUFSZ];
177 int len; /* length of message / read */
178 int s, result_len; /* tag fields on the response from emacs */
180 int total = 1; /* # bytes that will actually be sent off */
182 if ((len = msgrcv (ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0)
185 fprintf (stderr, "%s: unable to receive\n", progname);
189 msgctl (ipc_qid, IPC_STAT, &msg_st);
190 strncpy (buf, msgp->mtext, len);
191 buf[len] = '\0'; /* terminate */
193 printf ("%d %s", ipc_qid, buf);
196 /* now for the response from gnu */
197 msgp->mtext[0] = '\0';
200 if ((len = read(0,buf,GSERV_BUFSZ-1)) < 0)
203 fprintf (stderr, "%s: unable to read\n", progname);
207 sscanf (buf, "%d:%[^\n]\n", &junk, msgp->mtext);
210 /* read in "n/m:" (n=client fd, m=message length) */
212 while (offset < (GSERV_BUFSZ-1) &&
213 ((len = read (0, buf + offset, 1)) > 0) &&
222 fprintf (stderr, "%s: unable to read\n", progname);
226 /* parse the response from emacs, getting client fd & result length */
228 sscanf (buf, "%d/%d", &s, &result_len);
230 while (result_len > 0)
232 if ((len = read(0, buf, min2 (result_len, GSERV_BUFSZ - 1))) < 0)
235 fprintf (stderr, "%s: unable to read\n", progname);
239 /* Send this string off, but only if we have enough space */
241 if (GSERV_BUFSZ > total)
243 if (total + len <= GSERV_BUFSZ)
246 buf[GSERV_BUFSZ - total] = 0;
249 total += strlen(buf);
255 /* eat the newline */
256 while ((len = read (0,buf,1)) == 0)
261 fprintf (stderr,"%s: unable to read\n", progname);
266 fprintf (stderr,"%s: garbage after result [%c]\n", progname, buf[0]);
271 /* Send a response back to the client. */
273 msgp->mtype = msg_st.msg_lspid;
274 if (msgsnd (ipc_qid,msgp,strlen(msgp->mtext)+1,0) < 0)
275 perror ("msgsend(gnuserv)");
277 } /* handle_ipc_request */
278 #endif /* SYSV_IPC */
281 #if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
283 echo_request -- read request from a given socket descriptor, and send the information
284 to stdout (the gnu process).
289 char buf[GSERV_BUFSZ];
294 /* read until we get a newline or no characters */
295 while ((len = recv(s,buf,GSERV_BUFSZ-1,0)) > 0) {
299 if (buf[len-1] == EOT_CHR) {
301 break; /* end of message */
308 fprintf(stderr,"%s: unable to recv\n",progname);
316 handle_response -- accept a response from stdin (the gnu process) and pass the
317 information on to the relevant client.
320 handle_response (void)
322 char buf[GSERV_BUFSZ+1];
328 /* read in "n/m:" (n=client fd, m=message length) */
329 while (offset < GSERV_BUFSZ &&
330 ((len = read(0,buf+offset,1)) > 0) &&
331 buf[offset] != ':') {
337 fprintf(stderr,"%s: unable to read\n",progname);
341 /* parse the response from emacs, getting client fd & result length */
343 sscanf(buf,"%d/%d", &s, &result_len);
345 while (result_len > 0) {
346 if ((len = read(0,buf,min2(result_len,GSERV_BUFSZ))) < 0) {
348 fprintf(stderr,"%s: unable to read\n",progname);
356 /* eat the newline */
357 while ((len = read(0,buf,1)) == 0)
362 fprintf(stderr,"%s: unable to read\n",progname);
367 fprintf(stderr,"%s: garbage after result\n",progname);
370 /* send the newline */
375 } /* handle_response */
376 #endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
379 #ifdef INTERNET_DOMAIN_SOCKETS
381 unsigned long host_addr;
385 struct entry *permitted_hosts[TABLE_SIZE];
387 #ifdef AUTH_MAGIC_COOKIE
389 # include <X11/Xauth.h>
391 static Xauth *server_xauth = NULL;
395 timed_read (int fd, char *buf, int max, int timeout, int one_line)
398 struct timeval tv; /* = {timeout, 0}; */
411 r = select(fd + 1, &rmask, NULL, NULL, &tv);
415 if (read (fd, &c, 1) == 1 )
422 printf ("read error on socket\004\n");
428 printf ("read timed out\004\n");
433 printf ("error in select\004\n");
436 } while ((nbytes < max) && !(one_line && (c == '\n')));
439 if (one_line && *buf == '\n')
450 permitted -- return whether a given host is allowed to connect to the server.
453 permitted (unsigned long host_addr, int fd)
458 char auth_protocol[128];
464 /* we are checking permission on a real connection */
466 /* Read auth protocol name */
468 if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1) <= 0)
471 if (strcmp (auth_protocol, DEFAUTH_NAME) &&
472 strcmp (auth_protocol, MCOOKIE_NAME))
474 printf ("authentication protocol (%s) from client is invalid...\n",
476 printf ("... Was the client an old version of gnuclient/gnudoit?\004\n");
481 if (!strcmp(auth_protocol, MCOOKIE_NAME))
485 * doing magic cookie auth
488 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
491 auth_data_len = atoi(buf);
493 if (auth_data_len <= 0 || auth_data_len > (int) sizeof(buf))
498 if (timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0) != auth_data_len)
501 #ifdef AUTH_MAGIC_COOKIE
502 if (server_xauth && server_xauth->data)
504 /* Do a compare without comprising info about
505 the size of the cookie */
507 int auth_mismatches =
509 server_xauth->data_length );
511 for(auth_data_pos=0; auth_data_pos < auth_data_len; ++auth_data_pos)
513 ( buf[auth_data_pos] ^
514 server_xauth->data[auth_data_pos % server_xauth->data_length]);
516 if (auth_mismatches == 0)
519 for(;rand() % 1000;);
523 printf ("client tried Xauth, but server is not compiled with Xauth\n");
527 * auth failed, but allow this to fall through to the GNU_SECURE
531 printf ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");
535 /* Other auth protocols go here, and should execute only if the
536 * auth_protocol name matches.
542 /* Now, try the old GNU_SECURE stuff... */
544 /* First find the hash key */
545 key = HASH(host_addr) % TABLE_SIZE;
547 /* Now check the chain for that hash key */
548 for(entry=permitted_hosts[key]; entry != NULL; entry=entry->next)
549 if (host_addr == entry->host_addr)
558 add_host -- add the given host to the list of permitted hosts, provided it isn't
562 add_host (unsigned long host_addr)
565 struct entry *new_entry;
567 if (!permitted(host_addr, -1))
569 if ((new_entry = (struct entry *) malloc(sizeof(struct entry))) == NULL) {
570 fprintf(stderr,"%s: unable to malloc space for permitted host entry\n",
575 new_entry->host_addr = host_addr;
576 key = HASH(host_addr) % TABLE_SIZE;
577 new_entry->next = permitted_hosts[key];
578 permitted_hosts[key] = new_entry;
585 setup_table -- initialize the table of hosts allowed to contact the server,
586 by reading from the file specified by the GNU_SECURE
588 Put in the local machine, and, if a security file is specifed,
589 add each host that is named in the file.
590 Return the number of hosts added.
597 char hostname[HOSTNAMSZ];
598 unsigned int host_addr;
602 /* Make sure every entry is null */
603 for (i=0; i<TABLE_SIZE; i++)
604 permitted_hosts[i] = NULL;
606 gethostname(hostname,HOSTNAMSZ);
608 if ((t = internet_addr(hostname)) == -1) {
609 fprintf(stderr,"%s: unable to find %s in /etc/hosts or from YP",
616 #ifdef AUTH_MAGIC_COOKIE
618 server_xauth = XauGetAuthByAddr (FamilyInternet,
619 sizeof(host_addr), (char *)&host_addr,
620 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
621 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
624 #endif /* AUTH_MAGIC_COOKIE */
627 #if 0 /* Don't even want to allow access from the local host by default */
628 add_host(host_addr); /* add local host */
631 if (((file_name = getenv("GNU_SECURE")) != NULL && /* security file */
632 (host_file = fopen(file_name,"r")) != NULL)) /* opened ok */
634 while ((fscanf(host_file,"%s",hostname) != EOF)) { /* find a host */
635 t = internet_addr(hostname);
636 if (t != -1)/* get its addr */
639 add_host(host_addr); /* add the addr */
651 internet_init -- initialize server, returning an internet socket that can
657 int ls; /* socket descriptor */
658 struct servent *sp; /* pointer to service information */
659 struct sockaddr_in server; /* for local socket address */
660 char *ptr; /* ptr to return from getenv */
662 if (setup_table() == 0)
665 /* clear out address structure */
666 memset (&server, '\0', sizeof (server));
668 /* Set up address structure for the listen socket. */
669 server.sin_family = AF_INET;
670 server.sin_addr.s_addr = INADDR_ANY;
672 /* Find the information for the gnu server
673 * in order to get the needed port number.
675 if ((ptr=getenv("GNU_PORT")) != NULL)
676 server.sin_port = htons(atoi(ptr));
677 else if ((sp = getservbyname ("gnuserv", "tcp")) == NULL)
678 server.sin_port = htons(DEFAULT_PORT+getuid());
680 server.sin_port = sp->s_port;
682 /* Create the listen socket. */
683 if ((ls = socket (AF_INET,SOCK_STREAM, 0)) == -1)
686 fprintf(stderr,"%s: unable to create socket\n",progname);
690 /* Bind the listen address to the socket. */
691 if (bind(ls,(struct sockaddr *) &server,sizeof(struct sockaddr_in)) == -1)
694 fprintf(stderr,"%s: unable to bind socket\n",progname);
698 /* Initiate the listen on the socket so remote users
701 if (listen(ls,20) == -1)
704 fprintf(stderr,"%s: unable to listen\n",progname);
710 } /* internet_init */
714 handle_internet_request -- accept a request from a client and send the information
715 to stdout (the gnu process).
718 handle_internet_request (int ls)
721 socklen_t addrlen = sizeof (struct sockaddr_in);
722 struct sockaddr_in peer; /* for peer socket address */
724 memset (&peer, '\0', sizeof (peer));
726 if ((s = accept(ls,(struct sockaddr *)&peer, &addrlen)) == -1)
729 fprintf(stderr,"%s: unable to accept\n",progname);
733 /* Check that access is allowed - if not return crud to the client */
734 if (!permitted(peer.sin_addr.s_addr, s))
736 send_string(s,"gnudoit: Connection refused\ngnudoit: unable to connect to remote");
739 printf("Refused connection from %s\004\n", inet_ntoa(peer.sin_addr));
745 } /* handle_internet_request */
746 #endif /* INTERNET_DOMAIN_SOCKETS */
749 #ifdef UNIX_DOMAIN_SOCKETS
751 unix_init -- initialize server, returning an unix-domain socket that can
757 int ls; /* socket descriptor */
758 struct sockaddr_un server; /* unix socket address */
761 if ((ls = socket(AF_UNIX,SOCK_STREAM, 0)) < 0)
764 fprintf(stderr,"%s: unable to create socket\n",progname);
768 /* Set up address structure for the listen socket. */
769 #ifdef HIDE_UNIX_SOCKET
770 sprintf(server.sun_path,"%s/gsrvdir%d",tmpdir,(int)geteuid());
771 if (mkdir(server.sun_path, 0700) < 0)
773 /* assume it already exists, and try to set perms */
774 if (chmod(server.sun_path, 0700) < 0)
777 fprintf(stderr,"%s: can't set permissions on %s\n",
778 progname, server.sun_path);
782 strcat(server.sun_path,"/gsrv");
783 unlink(server.sun_path); /* remove old file if it exists */
784 #else /* HIDE_UNIX_SOCKET */
785 sprintf(server.sun_path,"%s/gsrv%d",tmpdir,(int)geteuid());
786 unlink(server.sun_path); /* remove old file if it exists */
787 #endif /* HIDE_UNIX_SOCKET */
789 server.sun_family = AF_UNIX;
790 #ifdef HAVE_SOCKADDR_SUN_LEN
791 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
793 bindlen = (sizeof (server.sun_len) + sizeof (server.sun_family)
794 + strlen (server.sun_path) + 1);
795 server.sun_len = bindlen;
797 bindlen = strlen (server.sun_path) + sizeof (server.sun_family);
800 if (bind(ls,(struct sockaddr *)&server,bindlen) < 0)
803 fprintf(stderr,"%s: unable to bind socket\n",progname);
807 chmod(server.sun_path,0700); /* only this user can send commands */
809 if (listen(ls,20) < 0) {
811 fprintf(stderr,"%s: unable to listen\n",progname);
815 /* #### there are also better ways of dealing with this when
816 sigvec() is present. */
817 #if defined (HAVE_SIGPROCMASK)
820 sigemptyset (&_mask);
821 sigaddset (&_mask, SIGPIPE);
822 sigprocmask (SIG_BLOCK, &_mask, NULL);
825 signal(SIGPIPE,SIG_IGN); /* in case user kills client */
834 handle_unix_request -- accept a request from a client and send the information
835 to stdout (the gnu process).
838 handle_unix_request (int ls)
841 socklen_t len = sizeof (struct sockaddr_un);
842 struct sockaddr_un server; /* for unix socket address */
844 server.sun_family = AF_UNIX;
846 if ((s = accept(ls,(struct sockaddr *)&server, &len)) < 0)
849 fprintf(stderr,"%s: unable to accept\n",progname);
854 } /* handle_unix_request */
855 #endif /* UNIX_DOMAIN_SOCKETS */
859 main (int argc, char *argv[])
861 int chan; /* temporary channel number */
863 struct msgbuf *msgp; /* message buffer */
865 int ils = -1; /* internet domain listen socket */
866 int uls = -1; /* unix domain listen socket */
867 #endif /* SYSV_IPC */
871 for(chan=3; chan < _NFILE; close(chan++)) /* close unwanted channels */
875 tmpdir = getenv("TMPDIR");
881 /* this is to allow ^D to pass to emacs */
883 (void) ioctl(fileno(stdout), TIOCLBIS, &d);
888 ipc_init(&msgp); /* get a msqid to listen on, and a message buffer */
889 #endif /* SYSV_IPC */
891 #ifdef INTERNET_DOMAIN_SOCKETS
892 ils = internet_init(); /* get an internet domain socket to listen on */
893 #endif /* INTERNET_DOMAIN_SOCKETS */
895 #ifdef UNIX_DOMAIN_SOCKETS
896 uls = unix_init(); /* get a unix domain socket to listen on */
897 #endif /* UNIX_DOMAIN_SOCKETS */
901 handle_ipc_request(msgp);
902 #else /* NOT SYSV_IPC */
905 FD_SET(fileno(stdin), &rmask);
911 if (select(max2(fileno(stdin),max2(uls,ils)) + 1, &rmask,
912 (fd_set *)NULL, (fd_set *)NULL, (struct timeval *)NULL) < 0)
915 fprintf(stderr,"%s: unable to select\n",progname);
919 #ifdef UNIX_DOMAIN_SOCKETS
920 if (uls > 0 && FD_ISSET(uls, &rmask))
921 handle_unix_request(uls);
924 #ifdef INTERNET_DOMAIN_SOCKETS
925 if (ils > 0 && FD_ISSET(ils, &rmask))
926 handle_internet_request(ils);
927 #endif /* INTERNET_DOMAIN_SOCKETS */
929 if (FD_ISSET(fileno(stdin), &rmask)) /* from stdin (gnu process) */
931 #endif /* NOT SYSV_IPC */
935 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */