Fix the fix to really close 181
[sxemacs] / lib-src / gnuserv.c
1 /* -*-C-*-
2  Server code for handling requests from clients and forwarding them
3  on to the GNU Emacs process.
4
5  This file is part of GNU Emacs.
6
7  Copying is permitted under those conditions described by the GNU
8  General Public License.
9
10  Copyright (C) 1989 Free Software Foundation, Inc.
11
12  Author: Andy Norman (ange@hplb.hpl.hp.com), based on 'etc/server.c'
13          from the 18.52 GNU Emacs distribution.
14
15  Please mail bugs and suggestions to the author at the above address.
16 */
17
18 /* HISTORY
19  * 11-Nov-1990          bristor@simba
20  *    Added EOT stuff.
21  */
22
23 /*
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.
27  *
28  * (If gnuserv came bundled with your emacs, the README file is probably
29  * ../etc/gnuserv.README relative to the directory containing this file)
30  */
31
32 #include "gnuserv.h"
33 #include <assert.h>
34
35 char gnuserv_version[] = "gnuserv version" GNUSERV_VERSION;
36
37 #ifdef USE_LITOUT
38 #ifdef linux
39 #include <bsd/sgtty.h>
40 #else
41 #include <sgtty.h>
42 #endif
43 #endif
44
45 #ifdef AIX
46 #include <sys/select.h>
47 #endif
48
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif                          /* HAVE_UNISTD_H */
57
58 #ifdef HAVE_STRING_H
59 #include <string.h>
60 #endif                          /* HAVE_STRING_H */
61
62 #define xstrncpy(d_,s_,l_)                      \
63         do {                                    \
64                 char* dst_=d_;                  \
65                 dst_[0]='\0';                   \
66                 strncat((dst_),(s_),(l_)-1);    \
67         } while(0)
68
69
70 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
71     !defined(INTERNET_DOMAIN_SOCKETS)
72 int
73 main(void)
74 {
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);
77         return 1;
78 }
79 #else  /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
80
81 # ifdef SYSV_IPC
82
83 /* ipc message queue id */
84 int ipc_qid = 0;
85 /* watchdog task pid */
86 pid_t ipc_wpid = 0;
87
88 /** ipc_exit
89  * clean up the queue id and queue, then kill the watchdog task
90  * if it exists. exit with the given status. **/
91 static void
92 __attribute__((noreturn))
93 ipc_exit(int stat)
94 {
95         msgctl(ipc_qid, IPC_RMID, 0);
96
97         if (ipc_wpid != 0) {
98                 kill(ipc_wpid, SIGKILL);
99         }
100         exit(stat);
101 }
102
103 /** ipc_handle_signal
104  * catch the signal given and clean up. **/
105 static void
106 ipc_handle_signal(int sig)
107 {
108         ipc_exit(0);
109 }
110
111 /** ipc_spawn_watchdog
112  * spawn a watchdog task to clean up the message queue should the
113  * server process die. **/
114 static void
115 ipc_spawn_watchdog(void)
116 {
117         /* child process */
118         if ((ipc_wpid = fork()) == 0) {
119                 /* parent's process id */
120                 pid_t ppid = getppid();
121
122                 /* gnu kills process group on exit */
123                 setpgrp();
124
125                 while (1) {
126                         /* ppid is no longer valid, parent may have died */
127                         if (kill(ppid, 0) < 0) {
128                                 ipc_exit(0);
129                         }
130                         /* else, have another go later */
131                         sleep(10);
132                 }
133         }
134         return;
135 }
136
137 /** ipc_init
138  * initialize server, setting the global msqid that can be listened on. **/
139 static void
140 ipc_init(struct msgbuf **msgpp)
141 {
142         /* messge key */
143         key_t key;
144         /* pathname for key */
145         char buf[GSERV_BUFSZ];
146         int sz;
147
148         SNPRINTF(sz, buf, sizeof(buf),"%s/gsrv%d", tmpdir, (int)geteuid());
149         creat(buf, 0600);
150         key = ftok(buf, 1);
151
152         if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
153                 perror(progname);
154                 fprintf(stderr, "%s: unable to create msg queue\n", progname);
155                 ipc_exit(1);
156         }
157         ipc_spawn_watchdog();
158
159         signal(SIGTERM, ipc_handle_signal);
160         signal(SIGINT, ipc_handle_signal);
161
162         *msgpp = (struct msgbuf*)malloc(sizeof **msgpp + GSERV_BUFSZ);
163         if (*msgpp == NULL) {
164                 fprintf(stderr,
165                         "%s: unable to allocate space for message buffer\n",
166                         progname);
167                 ipc_exit(1);
168         }
169         return;
170 }
171
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. **/
175 static void
176 handle_ipc_request(struct msgbuf *msgp)
177 {
178         /* message status */
179         struct msqid_ds msg_st;
180         char buf[GSERV_BUFSZ];
181         /* length of message / read */
182         ssize_t len;
183         /* tag fields on the response from emacs */
184         int s, result_len;
185         int offset = 0;
186         /* # bytes that will actually be sent off */
187         int total = 1;
188
189         if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
190                 perror(progname);
191                 fprintf(stderr, "%s: unable to receive\n", progname);
192                 ipc_exit(1);
193         }
194         /* if */
195         msgctl(ipc_qid, IPC_STAT, &msg_st);
196         xstrncpy(buf, msgp->mtext, sizeof(buf));
197
198         printf("%d %s", ipc_qid, buf);
199         fflush(stdout);
200
201         /* now for the response from gnu */
202         msgp->mtext[0] = '\0';
203
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] != ':') {
207                 offset += len;
208         }
209
210         if (len < 0) {
211                 perror(progname);
212                 fprintf(stderr, "%s: unable to read\n", progname);
213                 exit(1);
214         }
215
216         /* parse the response from emacs, getting client fd & result length */
217         buf[offset] = '\0';
218         sscanf(buf, "%d/%d", &s, &result_len);
219
220         while (result_len > 0) {
221                 len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1));
222                 if (len < 0) {
223                         perror(progname);
224                         fprintf(stderr, "%s: unable to read\n", progname);
225                         exit(1);
226                 }
227
228                 /* Send this string off, but only if we have enough space */
229                 if (GSERV_BUFSZ > total) {
230                         if (total + len <= GSERV_BUFSZ) {
231                                 buf[len] = 0;
232                         } else {
233                                 buf[GSERV_BUFSZ - total] = 0;
234                         }
235                         send_string(s, buf);
236                         total += strlen(buf);
237                 }
238
239                 result_len -= len;
240         }
241
242         /* eat the newline */
243         while ((len = read(0, buf, 1)) == 0);
244
245         if (len < 0) {
246                 perror(progname);
247                 fprintf(stderr, "%s: unable to read\n", progname);
248                 exit(1);
249         }
250         if (buf[0] != '\n') {
251                 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
252                         buf[0]);
253                 exit(1);
254         }
255
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)");
260         }
261         return;
262 }
263 # endif  /* SYSV_IPC */
264
265 # if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
266 /** echo_request
267  * read request from a given socket descriptor, and send the information
268  * to stdout (the gnu process). **/
269 static void
270 echo_request(int s)
271 {
272         char buf[GSERV_BUFSZ];
273         ssize_t len;
274
275         printf("%d ", s);
276
277         /* read until we get a newline or no characters */
278         while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
279                 buf[len] = '\0';
280                 printf("%s", buf);
281
282                 if (buf[len - 1] == EOT_CHR) {
283                         /* end of message */
284                         fflush(stdout);
285                         break;
286                 }
287         }
288
289         if (len < 0) {
290                 perror(progname);
291                 fprintf(stderr, "%s: unable to recv\n", progname);
292                 exit(1);
293         }
294         return;
295 }
296
297 /** handle_response
298  * accept a response from stdin (the gnu process) and pass the
299  * information on to the relevant client. **/
300 static void
301 handle_response(void)
302 {
303         char buf[GSERV_BUFSZ + 1];
304         int offset = 0;
305         int s;
306         int len = 0;
307         int result_len;
308
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] != ':') {
312                 offset += len;
313         }
314
315         if (len < 0) {
316                 perror(progname);
317                 fprintf(stderr, "%s: unable to read\n", progname);
318                 exit(1);
319         }
320
321         /* parse the response from emacs, getting client fd & result length */
322         buf[offset] = '\0';
323         sscanf(buf, "%d/%d", &s, &result_len);
324
325         while (result_len > 0) {
326                 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
327                         perror(progname);
328                         fprintf(stderr, "%s: unable to read\n", progname);
329                         exit(1);
330                 }
331                 buf[len] = '\0';
332                 send_string(s, buf);
333                 result_len -= len;
334         }
335
336         /* eat the newline */
337         while ((len = read(0, buf, 1)) == 0) ;
338         if (len < 0) {
339                 perror(progname);
340                 fprintf(stderr, "%s: unable to read\n", progname);
341                 exit(1);
342         }
343         if (buf[0] != '\n') {
344                 fprintf(stderr, "%s: garbage after result\n", progname);
345                 exit(1);
346         }
347         /* send the newline */
348         buf[1] = '\0';
349         send_string(s, buf);
350         close(s);
351         return;
352 }
353 # endif  /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
354
355 # ifdef INTERNET_DOMAIN_SOCKETS
356 struct entry {
357         unsigned long host_addr;
358         struct entry *next;
359 };
360
361 struct entry *permitted_hosts[TABLE_SIZE];
362
363 #  ifdef AUTH_MAGIC_COOKIE
364 #   include <X11/X.h>
365 #   include <X11/Xauth.h>
366
367 static Xauth *server_xauth = NULL;
368 #  endif  /* AUTH_MAGIC_COOKIE */
369
370 static ssize_t
371 timed_read(int fd, char *buf, int max, int timeout, int one_line)
372 {
373         fd_set rmask;
374         /* = {timeout, 0}; */
375         struct timeval tv;
376         char c = 0;
377         ssize_t nbytes = 0;
378         int r;
379
380         tv.tv_sec = timeout;
381         tv.tv_usec = 0;
382
383         FD_ZERO(&rmask);
384         FD_SET(fd, &rmask);
385
386         do {
387                 r = select(fd + 1, &rmask, NULL, NULL, &tv);
388
389                 if (r > 0) {
390                         if (read(fd, &c, 1) == 1) {
391                                 *buf++ = c;
392                                 ++nbytes;
393                         } else {
394                                 printf("read error on socket\004\n");
395                                 return -1;
396                         }
397                 } else if (r == 0) {
398                         printf("read timed out\004\n");
399                         return -1;
400                 } else {
401                         printf("error in select\004\n");
402                         return -1;
403                 }
404         } while ((nbytes < max) && !(one_line && (c == '\n')));
405
406         --buf;
407         if (one_line && *buf == '\n') {
408                 *buf = 0;
409         }
410         return nbytes;
411 }
412
413 /** permitted
414  * return whether a given host is allowed to connect to the server. **/
415 static int
416 permitted(unsigned long host_addr, int fd)
417 {
418         int key;
419         struct entry *entry;
420
421         char auth_protocol[128];
422         char buf[1024];
423
424         if (fd > 0) {
425                 /* we are checking permission on a real connection */
426                 ssize_t len;
427                 long int auth_data_len;
428
429                 /* Read auth protocol name */
430                 if ((len = timed_read(
431                              fd, auth_protocol,
432                              AUTH_NAMESZ, AUTH_TIMEOUT, 1)) <= 0) {
433                         return FALSE;
434                 }
435
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);
441                         return FALSE;
442                 }
443
444                 if (strcmp(auth_protocol, MCOOKIE_NAME)) {
445                         /*break;*/
446                         goto old_stuff;
447                 }
448                 /*
449                  * doing magic cookie auth
450                  */
451
452                 if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0) {
453                         return FALSE;
454                 }
455                 auth_data_len = strtol(buf, NULL, 10);
456
457                 if (auth_data_len <= 0 || (size_t)auth_data_len > sizeof(buf)) {
458                         return FALSE;
459                 }
460
461                 len = timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0);
462                 if (len != auth_data_len) {
463                         return FALSE;
464                 }
465
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 */
470                         int auth_data_pos;
471                         int auth_mismatches =
472                                 (auth_data_len ^ server_xauth->data_length);
473
474                         for (auth_data_pos = 0;
475                              auth_data_pos < auth_data_len;
476                              ++auth_data_pos) {
477                                 auth_mismatches |=
478                                         (buf[auth_data_pos] ^ server_xauth->
479                                          data[auth_data_pos %
480                                               server_xauth->data_length]);
481                         }
482                         if (auth_mismatches == 0) {
483                                 return TRUE;
484                         }
485                         for (; rand() % 1000;);
486                 }
487 #else  /* !AUTH_MAGIC_COOKIE */
488                 fputs("\
489 client tried Xauth, but server is not compiled with Xauth\n", stdout);
490 #endif  /* AUTH_MAGIC_COOKIE */
491
492                 /*
493                  * auth failed, but allow this to fall through to the GNU_SECURE
494                  * protocol....
495                  */
496                 fputs("\
497 Xauth authentication failed, trying GNU_SECURE auth...\n", stdout);
498         }
499
500 old_stuff:
501         /* Now, try the old GNU_SECURE stuff... */
502
503         /* First find the hash key */
504         key = HASH(host_addr) % TABLE_SIZE;
505
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) {
509                         return TRUE;
510                 }
511         }
512         return FALSE;
513 }
514
515 /** add_host
516  * add the given host to the list of permitted hosts, provided it isn't
517  * already there. **/
518 static void
519 add_host(unsigned long host_addr)
520 {
521         int key;
522         struct entry *new_entry;
523
524         if (!permitted(host_addr, -1)) {
525                 new_entry = (struct entry *)malloc(sizeof(struct entry));
526                 if (new_entry == NULL) {
527                         fprintf(stderr, "\
528 %s: unable to malloc space for permitted host entry\n", progname);
529                         exit(1);
530                 }
531                 /* if */
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;
536         }
537         return;
538 }
539
540 /** setup_table
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. **/
547 static int
548 setup_table(void)
549 {
550         FILE *host_file;
551         char *file_name;
552         char hostname[HOSTNAMSZ];
553         unsigned int host_addr;
554         int i, hosts = 0;
555         int t;
556
557         /* Make sure every entry is null */
558         for (i = 0; i < TABLE_SIZE; i++) {
559                 permitted_hosts[i] = NULL;
560         }
561         gethostname(hostname, HOSTNAMSZ);
562
563         if ((t = internet_addr(hostname)) == -1) {
564                 fprintf(stderr, "\
565 %s: unable to find %s in /etc/hosts or from YP\n", progname, hostname);
566                 exit(1);
567         } else {
568                 host_addr = t;
569         }
570
571 #ifdef AUTH_MAGIC_COOKIE
572         server_xauth = XauGetAuthByAddr(
573                 FamilyInternet,
574                 sizeof(host_addr), (char *)&host_addr,
575                 strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
576                 strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
577         hosts++;
578
579 #endif  /* AUTH_MAGIC_COOKIE */
580
581         if ((file_name = getenv("GNU_SECURE")) == NULL) {
582                 /* security file not given */
583                 ;
584         } else if ((host_file = fopen(file_name, "r")) == NULL) {
585                 /* host file didn't open/exist */
586                 ;
587         } else {
588                 /* find a host */
589                 while ((fscanf(host_file, "%s", hostname) != EOF)) {
590                         t = internet_addr(hostname);
591                         /* get its addr */
592                         if (t != -1) {
593                                 host_addr = t;
594                                 /* add the addr */
595                                 add_host(host_addr);
596                                 hosts++;
597                         }
598                 }
599                 fclose(host_file);
600         }
601         return hosts;
602 }
603
604 /** internet_init
605  * initialize server, returning an internet socket that can be listened on. **/
606 static int
607 internet_init(void)
608 {
609         /* socket descriptor */
610         int ls;
611         /* pointer to service information */
612         struct servent *sp;
613         /* for local socket address */
614         struct sockaddr_in server;
615         /* ptr to return from getenv */
616         char *ptr;
617
618         if (setup_table() == 0) {
619                 return -1;
620         }
621
622         /* clear out address structure */
623         memset(&server, '\0', sizeof(server));
624
625         /* Set up address structure for the listen socket. */
626         server.sin_family = AF_INET;
627         server.sin_addr.s_addr = INADDR_ANY;
628
629         /* Find the information for the gnu server
630          * in order to get the needed port number.
631          */
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());
636         } else {
637                 server.sin_port = sp->s_port;
638         }
639         /* Create the listen socket. */
640         if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
641                 perror(progname);
642                 fprintf(stderr, "%s: unable to create socket\n", progname);
643                 exit(1);
644         }
645
646         /* Bind the listen address to the socket. */
647         if (bind(ls, (struct sockaddr*)&server, sizeof(server)) < 0) {
648                 perror(progname);
649                 fprintf(stderr, "%s: unable to bind socket\n", progname);
650                 exit(1);
651         }
652
653         /* Initiate the listen on the socket so remote users
654          * can connect. */
655         if (listen(ls, 20) == -1) {
656                 perror(progname);
657                 fprintf(stderr, "%s: unable to listen\n", progname);
658                 exit(1);
659         }
660         return ls;
661 }
662
663 /** handle_internet_request
664  * accept a request from a client and send the information
665  * to stdout (the gnu process). **/
666 static void
667 handle_internet_request(int ls)
668 {
669         int s;
670         socklen_t addrlen = sizeof(struct sockaddr_in);
671         /* for peer socket address */
672         struct sockaddr_in peer;
673
674         memset(&peer, '\0', sizeof(peer));
675
676         if ((s = accept(ls, (struct sockaddr*)&peer, &addrlen)) == -1) {
677                 perror(progname);
678                 fprintf(stderr, "%s: unable to accept\n", progname);
679                 exit(1);
680         }
681
682         /* Check that access is allowed - if not return crud to the client */
683         if (!permitted(peer.sin_addr.s_addr, s)) {
684                 send_string(s, "\
685 gnuclient: Connection refused\ngnuclient: unable to connect to remote");
686                 close(s);
687
688                 printf("Refused connection from %s\n",
689                        inet_ntoa(peer.sin_addr));
690                 return;
691         }
692         echo_request(s);
693 }
694 # endif  /* INTERNET_DOMAIN_SOCKETS */
695
696 # ifdef UNIX_DOMAIN_SOCKETS
697 /** unix_init
698  * initialize server, returning an unix-domain socket
699  * that can be listened on. **/
700 static int
701 unix_init(void)
702 {
703         /* socket descriptor */
704         int ls;
705         /* unix socket address */
706         struct sockaddr_un server;
707         socklen_t bindlen;
708         int sz;
709
710         if ((ls = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
711                 perror(progname);
712                 fprintf(stderr, "%s: unable to create socket\n", progname);
713                 exit(1);
714         }
715
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) {
723                         perror(progname);
724                         fprintf(stderr, "%s: can't set permissions on %s\n",
725                                 progname, server.sun_path);
726                         exit(1);
727                 }
728         }
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 */
738
739         server.sun_family = AF_UNIX;
740 #  ifdef HAVE_SOCKADDR_SUN_LEN
741         /* See W. R. Stevens "Advanced Programming in the Unix Environment"
742            p. 502 */
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 */
749
750         if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
751                 perror(progname);
752                 fprintf(stderr, "%s: unable to bind socket\n", progname);
753                 exit(1);
754         }
755         /* only this user can send commands */
756         chmod(server.sun_path, 0700);
757
758         if (listen(ls, 20) < 0) {
759                 perror(progname);
760                 fprintf(stderr, "%s: unable to listen\n", progname);
761                 exit(1);
762         }
763
764         /* #### there are also better ways of dealing with this when
765            sigvec() is present. */
766 #  if  defined (HAVE_SIGPROCMASK)
767         {
768                 sigset_t _mask;
769                 sigemptyset(&_mask);
770                 sigaddset(&_mask, SIGPIPE);
771                 sigprocmask(SIG_BLOCK, &_mask, NULL);
772         }
773 #  else  /* !HAVE_SIGPROCMASK */
774         signal(SIGPIPE, SIG_IGN);       /* in case user kills client */
775 #  endif  /* HAVE_SIGPROCMASK */
776         return ls;
777 }
778
779 /** handle_unix_request
780  * accept a request from a client and send the information
781  * to stdout (the gnu process). **/
782 static void
783 handle_unix_request(int ls)
784 {
785         int s;
786         socklen_t len = sizeof(struct sockaddr_un);
787         /* for unix socket address */
788         struct sockaddr_un server;
789
790         server.sun_family = AF_UNIX;
791
792         if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
793                 perror(progname);
794                 fprintf(stderr, "%s: unable to accept\n", progname);
795                 /* Nothing more we can do here... */
796                 return;
797         }
798         echo_request(s);
799         return;
800 }
801 # endif  /* UNIX_DOMAIN_SOCKETS */
802
803 \f
804 int
805 main(int argc, char *argv[])
806 {
807         /* temporary channel number */
808         int chan;
809 #  ifdef SYSV_IPC
810         /* message buffer */
811         struct msgbuf *msgp;
812 #  else  /* !SYSV_IPC */
813         /* internet domain listen socket */
814         int ils = -1;
815         /* unix domain listen socket */
816         int uls = -1;
817 #  endif  /* SYSV_IPC */
818
819         if (argc >= 0) {
820                 progname = argv[0];
821         }
822
823         /* close unwanted channels */
824         for (chan = 3; chan < _NFILE; close(chan++));
825
826 #ifdef USE_TMPDIR
827         tmpdir = getenv("TMPDIR");
828 #endif  /* USE_TMPDIR */
829         if (!tmpdir) {
830                 tmpdir = "/tmp";
831         }
832
833 #ifdef USE_LITOUT
834         {
835                 /* this is to allow ^D to pass to emacs */
836                 int d = LLITOUT;
837                 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
838         }
839 #endif  /* USE_LITOUT */
840
841 #ifdef SYSV_IPC
842         /* get a msqid to listen on, and a message buffer */
843         ipc_init(&msgp);
844 #endif  /* SYSV_IPC */
845
846 #ifdef INTERNET_DOMAIN_SOCKETS
847         /* get an internet domain socket to listen on */
848         ils = internet_init();
849 #endif  /* INTERNET_DOMAIN_SOCKETS */
850
851 #ifdef UNIX_DOMAIN_SOCKETS
852         /* get a unix domain socket to listen on */
853         uls = unix_init();
854 #endif  /* UNIX_DOMAIN_SOCKETS */
855
856         while (1) {
857 # ifdef SYSV_IPC
858                 handle_ipc_request(msgp);
859 # else  /* !SYSV_IPC */
860                 fd_set rmask;
861                 int max_socks;
862
863                 FD_ZERO(&rmask);
864                 FD_SET(fileno(stdin), &rmask);
865
866                 if (uls >= 0) {
867                         FD_SET(uls, &rmask);
868                 }
869                 if (ils >= 0) {
870                         FD_SET(ils, &rmask);
871                 }
872
873                 max_socks = max2(fileno(stdin), max2(uls, ils));
874                 if (select(max_socks + 1, &rmask, NULL, NULL, NULL) < 0) {
875                         perror(progname);
876                         fprintf(stderr, "%s: unable to select\n", progname);
877                         return 1;
878                 }
879 # ifdef UNIX_DOMAIN_SOCKETS
880                 if (uls > 0 && FD_ISSET(uls, &rmask)) {
881                         handle_unix_request(uls);
882                 }
883 # endif  /* UNIX_DOMAIN_SOCKETS */
884
885 # ifdef INTERNET_DOMAIN_SOCKETS
886                 if (ils > 0 && FD_ISSET(ils, &rmask)) {
887                         handle_internet_request(ils);
888                 }
889 # endif  /* INTERNET_DOMAIN_SOCKETS */
890
891                 /* from stdin (gnu process) */
892                 if (FD_ISSET(fileno(stdin), &rmask)) {
893                         handle_response();
894                 }
895 # endif  /* NOT SYSV_IPC */
896         }
897         /* not reached */
898         return 0;
899 }
900
901 #endif  /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */