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)
33 static char rcsid [] = "!Header: gnuserv.c,v 2.1 95/02/16 11:58:27 arup alpha !";
40 #include <bsd/sgtty.h>
47 #include <sys/select.h>
52 #include <sys/types.h>
57 #endif /* HAVE_UNISTD_H */
61 #endif /* HAVE_STRING_H */
63 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
64 !defined(INTERNET_DOMAIN_SOCKETS)
67 fprintf (stderr,"Sorry, the Emacs server is only supported on systems that have\n");
68 fprintf (stderr,"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 int ipc_wpid = 0; /* watchdog task pid */
80 ipc_exit -- clean up the queue id and queue, then kill the watchdog task
81 if it exists. exit with the given status.
86 msgctl (ipc_qid,IPC_RMID,0);
89 kill (ipc_wpid, SIGKILL);
96 ipc_handle_signal -- catch the signal given and clean up.
99 ipc_handle_signal(int sig)
102 } /* ipc_handle_signal */
106 ipc_spawn_watchdog -- spawn a watchdog task to clean up the message queue should the
110 ipc_spawn_watchdog (void)
112 if ((ipc_wpid = fork ()) == 0)
113 { /* child process */
114 int ppid = getppid (); /* parent's process id */
116 setpgrp(); /* gnu kills process group on exit */
120 if (kill (ppid, 0) < 0) /* ppid is no longer valid, parent
126 sleep(10); /* have another go later */
130 } /* ipc_spawn_watchdog */
134 ipc_init -- initialize server, setting the global msqid that can be listened on.
137 ipc_init (struct msgbuf **msgpp)
139 key_t key; /* messge key */
140 char buf[GSERV_BUFSZ]; /* pathname for key */
142 sprintf (buf,"%s/gsrv%d",tmpdir,(int)geteuid ());
146 if ((ipc_qid = msgget (key,0600|IPC_CREAT)) == -1)
149 fprintf (stderr, "%s: unable to create msg queue\n", progname);
153 ipc_spawn_watchdog ();
155 signal (SIGTERM,ipc_handle_signal);
156 signal (SIGINT,ipc_handle_signal);
158 if ((*msgpp = (struct msgbuf *)
159 malloc (sizeof **msgpp + GSERV_BUFSZ)) == NULL)
162 "%s: unable to allocate space for message buffer\n", progname);
169 handle_ipc_request -- accept a request from a client, pass the request on
170 to the GNU Emacs process, then wait for its reply and
171 pass that on to the client.
174 handle_ipc_request (struct msgbuf *msgp)
176 struct msqid_ds msg_st; /* message status */
177 char buf[GSERV_BUFSZ];
178 int len; /* length of message / read */
179 int s, result_len; /* tag fields on the response from emacs */
181 int total = 1; /* # bytes that will actually be sent off */
183 if ((len = msgrcv (ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0)
186 fprintf (stderr, "%s: unable to receive\n", progname);
190 msgctl (ipc_qid, IPC_STAT, &msg_st);
191 strncpy (buf, msgp->mtext, len);
192 buf[len] = '\0'; /* terminate */
194 printf ("%d %s", ipc_qid, buf);
197 /* now for the response from gnu */
198 msgp->mtext[0] = '\0';
201 if ((len = read(0,buf,GSERV_BUFSZ-1)) < 0)
204 fprintf (stderr, "%s: unable to read\n", progname);
208 sscanf (buf, "%d:%[^\n]\n", &junk, msgp->mtext);
211 /* read in "n/m:" (n=client fd, m=message length) */
213 while (offset < (GSERV_BUFSZ-1) &&
214 ((len = read (0, buf + offset, 1)) > 0) &&
223 fprintf (stderr, "%s: unable to read\n", progname);
227 /* parse the response from emacs, getting client fd & result length */
229 sscanf (buf, "%d/%d", &s, &result_len);
231 while (result_len > 0)
233 if ((len = read(0, buf, min2 (result_len, GSERV_BUFSZ - 1))) < 0)
236 fprintf (stderr, "%s: unable to read\n", progname);
240 /* Send this string off, but only if we have enough space */
242 if (GSERV_BUFSZ > total)
244 if (total + len <= GSERV_BUFSZ)
247 buf[GSERV_BUFSZ - total] = 0;
250 total += strlen(buf);
256 /* eat the newline */
257 while ((len = read (0,buf,1)) == 0)
262 fprintf (stderr,"%s: unable to read\n", progname);
267 fprintf (stderr,"%s: garbage after result [%c]\n", progname, buf[0]);
272 /* Send a response back to the client. */
274 msgp->mtype = msg_st.msg_lspid;
275 if (msgsnd (ipc_qid,msgp,strlen(msgp->mtext)+1,0) < 0)
276 perror ("msgsend(gnuserv)");
278 } /* handle_ipc_request */
279 #endif /* SYSV_IPC */
282 #if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
284 echo_request -- read request from a given socket descriptor, and send the information
285 to stdout (the gnu process).
290 char buf[GSERV_BUFSZ];
295 /* read until we get a newline or no characters */
296 while ((len = recv(s,buf,GSERV_BUFSZ-1,0)) > 0) {
300 if (buf[len-1] == EOT_CHR) {
302 break; /* end of message */
309 fprintf(stderr,"%s: unable to recv\n",progname);
317 handle_response -- accept a response from stdin (the gnu process) and pass the
318 information on to the relevant client.
321 handle_response (void)
323 char buf[GSERV_BUFSZ+1];
329 /* read in "n/m:" (n=client fd, m=message length) */
330 while (offset < GSERV_BUFSZ &&
331 ((len = read(0,buf+offset,1)) > 0) &&
332 buf[offset] != ':') {
338 fprintf(stderr,"%s: unable to read\n",progname);
342 /* parse the response from emacs, getting client fd & result length */
344 sscanf(buf,"%d/%d", &s, &result_len);
346 while (result_len > 0) {
347 if ((len = read(0,buf,min2(result_len,GSERV_BUFSZ))) < 0) {
349 fprintf(stderr,"%s: unable to read\n",progname);
357 /* eat the newline */
358 while ((len = read(0,buf,1)) == 0)
363 fprintf(stderr,"%s: unable to read\n",progname);
368 fprintf(stderr,"%s: garbage after result\n",progname);
371 /* send the newline */
376 } /* handle_response */
377 #endif /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
380 #ifdef INTERNET_DOMAIN_SOCKETS
386 struct entry *permitted_hosts[TABLE_SIZE];
388 #ifdef AUTH_MAGIC_COOKIE
390 # include <X11/Xauth.h>
392 static Xauth *server_xauth = NULL;
396 timed_read (int fd, char *buf, int max, int timeout, int one_line)
399 struct timeval tv; /* = {timeout, 0}; */
412 r = select(fd + 1, &rmask, NULL, NULL, &tv);
416 if (read (fd, &c, 1) == 1 )
423 printf ("read error on socket\004\n");
429 printf ("read timed out\004\n");
434 printf ("error in select\004\n");
437 } while ((nbytes < max) && !(one_line && (c == '\n')));
440 if (one_line && *buf == '\n')
451 permitted -- return whether a given host is allowed to connect to the server.
454 permitted (u_long host_addr, int fd)
459 char auth_protocol[128];
465 /* we are checking permission on a real connection */
467 /* Read auth protocol name */
469 if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1) <= 0)
472 if (strcmp (auth_protocol, DEFAUTH_NAME) &&
473 strcmp (auth_protocol, MCOOKIE_NAME))
475 printf ("authentication protocol (%s) from client is invalid...\n",
477 printf ("... Was the client an old version of gnuclient/gnudoit?\004\n");
482 if (!strcmp(auth_protocol, MCOOKIE_NAME))
486 * doing magic cookie auth
489 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
492 auth_data_len = atoi(buf);
494 if (timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0) != auth_data_len)
497 #ifdef AUTH_MAGIC_COOKIE
498 if (server_xauth && server_xauth->data &&
499 !memcmp(buf, server_xauth->data, auth_data_len))
504 printf ("client tried Xauth, but server is not compiled with Xauth\n");
508 * auth failed, but allow this to fall through to the GNU_SECURE
512 printf ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");
516 /* Other auth protocols go here, and should execute only if the
517 * auth_protocol name matches.
523 /* Now, try the old GNU_SECURE stuff... */
525 /* First find the hash key */
526 key = HASH(host_addr) % TABLE_SIZE;
528 /* Now check the chain for that hash key */
529 for(entry=permitted_hosts[key]; entry != NULL; entry=entry->next)
530 if (host_addr == entry->host_addr)
539 add_host -- add the given host to the list of permitted hosts, provided it isn't
543 add_host (u_long host_addr)
546 struct entry *new_entry;
548 if (!permitted(host_addr, -1))
550 if ((new_entry = (struct entry *) malloc(sizeof(struct entry))) == NULL) {
551 fprintf(stderr,"%s: unable to malloc space for permitted host entry\n",
556 new_entry->host_addr = host_addr;
557 key = HASH(host_addr) % TABLE_SIZE;
558 new_entry->next = permitted_hosts[key];
559 permitted_hosts[key] = new_entry;
566 setup_table -- initialize the table of hosts allowed to contact the server,
567 by reading from the file specified by the GNU_SECURE
569 Put in the local machine, and, if a security file is specifed,
570 add each host that is named in the file.
571 Return the number of hosts added.
578 char hostname[HOSTNAMSZ];
582 /* Make sure every entry is null */
583 for (i=0; i<TABLE_SIZE; i++)
584 permitted_hosts[i] = NULL;
586 gethostname(hostname,HOSTNAMSZ);
588 if ((host_addr = internet_addr(hostname)) == -1)
590 fprintf(stderr,"%s: unable to find %s in /etc/hosts or from YP",
595 #ifdef AUTH_MAGIC_COOKIE
597 server_xauth = XauGetAuthByAddr (FamilyInternet,
598 sizeof(host_addr), (char *)&host_addr,
599 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
600 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
603 #endif /* AUTH_MAGIC_COOKIE */
606 #if 0 /* Don't even want to allow access from the local host by default */
607 add_host(host_addr); /* add local host */
610 if (((file_name = getenv("GNU_SECURE")) != NULL && /* security file */
611 (host_file = fopen(file_name,"r")) != NULL)) /* opened ok */
613 while ((fscanf(host_file,"%s",hostname) != EOF)) /* find a host */
614 if ((host_addr = internet_addr(hostname)) != -1)/* get its addr */
616 add_host(host_addr); /* add the addr */
627 internet_init -- initialize server, returning an internet socket that can
633 int ls; /* socket descriptor */
634 struct servent *sp; /* pointer to service information */
635 struct sockaddr_in server; /* for local socket address */
636 char *ptr; /* ptr to return from getenv */
638 if (setup_table() == 0)
641 /* clear out address structure */
642 memset((char *)&server,0,sizeof(struct sockaddr_in));
644 /* Set up address structure for the listen socket. */
645 server.sin_family = AF_INET;
646 server.sin_addr.s_addr = INADDR_ANY;
648 /* Find the information for the gnu server
649 * in order to get the needed port number.
651 if ((ptr=getenv("GNU_PORT")) != NULL)
652 server.sin_port = htons(atoi(ptr));
653 else if ((sp = getservbyname ("gnuserv", "tcp")) == NULL)
654 server.sin_port = htons(DEFAULT_PORT+getuid());
656 server.sin_port = sp->s_port;
658 /* Create the listen socket. */
659 if ((ls = socket (AF_INET,SOCK_STREAM, 0)) == -1)
662 fprintf(stderr,"%s: unable to create socket\n",progname);
666 /* Bind the listen address to the socket. */
667 if (bind(ls,(struct sockaddr *) &server,sizeof(struct sockaddr_in)) == -1)
670 fprintf(stderr,"%s: unable to bind socket\n",progname);
674 /* Initiate the listen on the socket so remote users
677 if (listen(ls,20) == -1)
680 fprintf(stderr,"%s: unable to listen\n",progname);
686 } /* internet_init */
690 handle_internet_request -- accept a request from a client and send the information
691 to stdout (the gnu process).
694 handle_internet_request (int ls)
697 size_t addrlen = sizeof(struct sockaddr_in);
698 struct sockaddr_in peer; /* for peer socket address */
700 memset((char *)&peer,0,sizeof(struct sockaddr_in));
702 if ((s = accept(ls,(struct sockaddr *)&peer, (void *) &addrlen)) == -1)
705 fprintf(stderr,"%s: unable to accept\n",progname);
709 /* Check that access is allowed - if not return crud to the client */
710 if (!permitted(peer.sin_addr.s_addr, s))
712 send_string(s,"gnudoit: Connection refused\ngnudoit: unable to connect to remote");
715 printf("Refused connection from %s\004\n", inet_ntoa(peer.sin_addr));
721 } /* handle_internet_request */
722 #endif /* INTERNET_DOMAIN_SOCKETS */
725 #ifdef UNIX_DOMAIN_SOCKETS
727 unix_init -- initialize server, returning an unix-domain socket that can
733 int ls; /* socket descriptor */
734 struct sockaddr_un server; /* unix socket address */
737 if ((ls = socket(AF_UNIX,SOCK_STREAM, 0)) < 0)
740 fprintf(stderr,"%s: unable to create socket\n",progname);
744 /* Set up address structure for the listen socket. */
745 #ifdef HIDE_UNIX_SOCKET
746 sprintf(server.sun_path,"%s/gsrvdir%d",tmpdir,(int)geteuid());
747 if (mkdir(server.sun_path, 0700) < 0)
749 /* assume it already exists, and try to set perms */
750 if (chmod(server.sun_path, 0700) < 0)
753 fprintf(stderr,"%s: can't set permissions on %s\n",
754 progname, server.sun_path);
758 strcat(server.sun_path,"/gsrv");
759 unlink(server.sun_path); /* remove old file if it exists */
760 #else /* HIDE_UNIX_SOCKET */
761 sprintf(server.sun_path,"%s/gsrv%d",tmpdir,(int)geteuid());
762 unlink(server.sun_path); /* remove old file if it exists */
763 #endif /* HIDE_UNIX_SOCKET */
765 server.sun_family = AF_UNIX;
766 #ifdef HAVE_SOCKADDR_SUN_LEN
767 /* See W. R. Stevens "Advanced Programming in the Unix Environment"
769 bindlen = (sizeof (server.sun_len) + sizeof (server.sun_family)
770 + strlen (server.sun_path) + 1);
771 server.sun_len = bindlen;
773 bindlen = strlen (server.sun_path) + sizeof (server.sun_family);
776 if (bind(ls,(struct sockaddr *)&server,bindlen) < 0)
779 fprintf(stderr,"%s: unable to bind socket\n",progname);
783 chmod(server.sun_path,0700); /* only this user can send commands */
785 if (listen(ls,20) < 0) {
787 fprintf(stderr,"%s: unable to listen\n",progname);
791 /* #### there are also better ways of dealing with this when
792 sigvec() is present. */
793 #if defined (HAVE_SIGPROCMASK)
796 sigemptyset (&_mask);
797 sigaddset (&_mask, SIGPIPE);
798 sigprocmask (SIG_BLOCK, &_mask, NULL);
801 signal(SIGPIPE,SIG_IGN); /* in case user kills client */
810 handle_unix_request -- accept a request from a client and send the information
811 to stdout (the gnu process).
814 handle_unix_request (int ls)
817 size_t len = sizeof(struct sockaddr_un);
818 struct sockaddr_un server; /* for unix socket address */
820 server.sun_family = AF_UNIX;
822 if ((s = accept(ls,(struct sockaddr *)&server, (void *)&len)) < 0)
825 fprintf(stderr,"%s: unable to accept\n",progname);
830 } /* handle_unix_request */
831 #endif /* UNIX_DOMAIN_SOCKETS */
835 main (int argc, char *argv[])
837 int chan; /* temporary channel number */
839 struct msgbuf *msgp; /* message buffer */
841 int ils = -1; /* internet domain listen socket */
842 int uls = -1; /* unix domain listen socket */
843 #endif /* SYSV_IPC */
847 for(chan=3; chan < _NFILE; close(chan++)) /* close unwanted channels */
851 tmpdir = getenv("TMPDIR");
857 /* this is to allow ^D to pass to emacs */
859 (void) ioctl(fileno(stdout), TIOCLBIS, &d);
864 ipc_init(&msgp); /* get a msqid to listen on, and a message buffer */
865 #endif /* SYSV_IPC */
867 #ifdef INTERNET_DOMAIN_SOCKETS
868 ils = internet_init(); /* get an internet domain socket to listen on */
869 #endif /* INTERNET_DOMAIN_SOCKETS */
871 #ifdef UNIX_DOMAIN_SOCKETS
872 uls = unix_init(); /* get a unix domain socket to listen on */
873 #endif /* UNIX_DOMAIN_SOCKETS */
877 handle_ipc_request(msgp);
878 #else /* NOT SYSV_IPC */
881 FD_SET(fileno(stdin), &rmask);
887 if (select(max2(fileno(stdin),max2(uls,ils)) + 1, &rmask,
888 (fd_set *)NULL, (fd_set *)NULL, (struct timeval *)NULL) < 0)
891 fprintf(stderr,"%s: unable to select\n",progname);
895 #ifdef UNIX_DOMAIN_SOCKETS
896 if (uls > 0 && FD_ISSET(uls, &rmask))
897 handle_unix_request(uls);
900 #ifdef INTERNET_DOMAIN_SOCKETS
901 if (ils > 0 && FD_ISSET(ils, &rmask))
902 handle_internet_request(ils);
903 #endif /* INTERNET_DOMAIN_SOCKETS */
905 if (FD_ISSET(fileno(stdin), &rmask)) /* from stdin (gnu process) */
907 #endif /* NOT SYSV_IPC */
913 #endif /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */