Fix if/else scope in yow.c from Rudi
[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 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
63     !defined(INTERNET_DOMAIN_SOCKETS)
64 main()
65 {
66         fprintf(stderr,
67                 "Sorry, the Emacs server is only supported on systems that have\n");
68         fprintf(stderr,
69                 "Unix Domain sockets, Internet Domain sockets or System V IPC\n");
70         exit(1);
71 }                               /* main */
72 #else                           /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
73
74 #ifdef SYSV_IPC
75
76 int ipc_qid = 0;                /* ipc message queue id */
77 pid_t ipc_wpid = 0;             /* watchdog task pid */
78
79 /*
80   ipc_exit -- clean up the queue id and queue, then kill the watchdog task
81               if it exists. exit with the given status.
82 */
83 void ipc_exit(int stat)
84 {
85         msgctl(ipc_qid, IPC_RMID, 0);
86
87         if (ipc_wpid != 0)
88                 kill(ipc_wpid, SIGKILL);
89
90         exit(stat);
91 }                               /* ipc_exit */
92
93 /*
94   ipc_handle_signal -- catch the signal given and clean up.
95 */
96 void ipc_handle_signal(int sig)
97 {
98         ipc_exit(0);
99 }                               /* ipc_handle_signal */
100
101 /*
102   ipc_spawn_watchdog -- spawn a watchdog task to clean up the message queue should the
103                         server process die.
104 */
105 void ipc_spawn_watchdog(void)
106 {
107         if ((ipc_wpid = fork()) == 0) { /* child process */
108                 pid_t ppid = getppid(); /* parent's process id */
109
110                 setpgrp();      /* gnu kills process group on exit */
111
112                 while (1) {
113                         if (kill(ppid, 0) < 0) {        /* ppid is no longer valid, parent
114                                                            may have died */
115                                 ipc_exit(0);
116                         }
117                         /* if */
118                         sleep(10);      /* have another go later */
119                 }               /* while */
120         }
121         /* if */
122 }                               /* ipc_spawn_watchdog */
123
124 /*
125   ipc_init -- initialize server, setting the global msqid that can be listened on.
126 */
127 void ipc_init(struct msgbuf **msgpp)
128 {
129         key_t key;              /* messge key */
130         char buf[GSERV_BUFSZ];  /* pathname for key */
131
132         int sz = snprintf(buf, sizeof(buf),"%s/gsrv%d", tmpdir, (int)geteuid());
133         assert(sz>=0 && sz<sizeof(buf));
134         creat(buf, 0600);
135         key = ftok(buf, 1);
136
137         if ((ipc_qid = msgget(key, 0600 | IPC_CREAT)) == -1) {
138                 perror(progname);
139                 fprintf(stderr, "%s: unable to create msg queue\n", progname);
140                 ipc_exit(1);
141         }
142         /* if */
143         ipc_spawn_watchdog();
144
145         signal(SIGTERM, ipc_handle_signal);
146         signal(SIGINT, ipc_handle_signal);
147
148         if ((*msgpp = (struct msgbuf *)
149              malloc(sizeof **msgpp + GSERV_BUFSZ)) == NULL) {
150                 fprintf(stderr,
151                         "%s: unable to allocate space for message buffer\n",
152                         progname);
153                 ipc_exit(1);
154         }                       /* if */
155 }                               /* ipc_init */
156
157 /*
158   handle_ipc_request -- accept a request from a client, pass the request on
159                         to the GNU Emacs process, then wait for its reply and
160                         pass that on to the client.
161 */
162 void handle_ipc_request(struct msgbuf *msgp)
163 {
164         struct msqid_ds msg_st; /* message status */
165         char buf[GSERV_BUFSZ];
166         int len;                /* length of message / read */
167         int s, result_len;      /* tag fields on the response from emacs */
168         int offset = 0;
169         int total = 1;          /* # bytes that will actually be sent off */
170
171         if ((len = msgrcv(ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) {
172                 perror(progname);
173                 fprintf(stderr, "%s: unable to receive\n", progname);
174                 ipc_exit(1);
175         }
176         /* if */
177         msgctl(ipc_qid, IPC_STAT, &msg_st);
178         strncpy(buf, msgp->mtext, len);
179         buf[len] = '\0';        /* terminate */
180
181         printf("%d %s", ipc_qid, buf);
182         fflush(stdout);
183
184         /* now for the response from gnu */
185         msgp->mtext[0] = '\0';
186
187 #if 0
188         if ((len = read(0, buf, GSERV_BUFSZ - 1)) < 0) {
189                 perror(progname);
190                 fprintf(stderr, "%s: unable to read\n", progname);
191                 ipc_exit(1);
192         }
193         /* if */
194         sscanf(buf, "%d:%[^\n]\n", &junk, msgp->mtext);
195 #else
196
197         /* read in "n/m:" (n=client fd, m=message length) */
198
199         while (offset < (GSERV_BUFSZ - 1) &&
200                ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
201                 offset += len;
202         }
203
204         if (len < 0) {
205                 perror(progname);
206                 fprintf(stderr, "%s: unable to read\n", progname);
207                 exit(1);
208         }
209
210         /* parse the response from emacs, getting client fd & result length */
211         buf[offset] = '\0';
212         sscanf(buf, "%d/%d", &s, &result_len);
213
214         while (result_len > 0) {
215                 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ - 1))) < 0) {
216                         perror(progname);
217                         fprintf(stderr, "%s: unable to read\n", progname);
218                         exit(1);
219                 }
220
221                 /* Send this string off, but only if we have enough space */
222
223                 if (GSERV_BUFSZ > total) {
224                         if (total + len <= GSERV_BUFSZ)
225                                 buf[len] = 0;
226                         else
227                                 buf[GSERV_BUFSZ - total] = 0;
228
229                         send_string(s, buf);
230                         total += strlen(buf);
231                 }
232
233                 result_len -= len;
234         }
235
236         /* eat the newline */
237         while ((len = read(0, buf, 1)) == 0) ;
238         if (len < 0) {
239                 perror(progname);
240                 fprintf(stderr, "%s: unable to read\n", progname);
241                 exit(1);
242         }
243         if (buf[0] != '\n') {
244                 fprintf(stderr, "%s: garbage after result [%c]\n", progname,
245                         buf[0]);
246                 exit(1);
247         }
248 #endif
249
250         /* Send a response back to the client. */
251
252         msgp->mtype = msg_st.msg_lspid;
253         if (msgsnd(ipc_qid, msgp, strlen(msgp->mtext) + 1, 0) < 0)
254                 perror("msgsend(gnuserv)");
255
256 }                               /* handle_ipc_request */
257 #endif                          /* SYSV_IPC */
258
259 #if defined(INTERNET_DOMAIN_SOCKETS) || defined(UNIX_DOMAIN_SOCKETS)
260 /*
261   echo_request -- read request from a given socket descriptor, and send the information
262                   to stdout (the gnu process).
263 */
264 static void echo_request(int s)
265 {
266         char buf[GSERV_BUFSZ];
267         int len;
268
269         printf("%d ", s);
270
271         /* read until we get a newline or no characters */
272         while ((len = recv(s, buf, GSERV_BUFSZ - 1, 0)) > 0) {
273                 buf[len] = '\0';
274                 printf("%s", buf);
275
276                 if (buf[len - 1] == EOT_CHR) {
277                         fflush(stdout);
278                         break;  /* end of message */
279                 }
280
281         }                       /* while */
282
283         if (len < 0) {
284                 perror(progname);
285                 fprintf(stderr, "%s: unable to recv\n", progname);
286                 exit(1);
287         }
288         /* if */
289 }                               /* echo_request */
290
291 /*
292   handle_response -- accept a response from stdin (the gnu process) and pass the
293                      information on to the relevant client.
294 */
295 static void handle_response(void)
296 {
297         char buf[GSERV_BUFSZ + 1];
298         int offset = 0;
299         int s;
300         int len = 0;
301         int result_len;
302
303         /* read in "n/m:" (n=client fd, m=message length) */
304         while (offset < GSERV_BUFSZ &&
305                ((len = read(0, buf + offset, 1)) > 0) && buf[offset] != ':') {
306                 offset += len;
307         }
308
309         if (len < 0) {
310                 perror(progname);
311                 fprintf(stderr, "%s: unable to read\n", progname);
312                 exit(1);
313         }
314
315         /* parse the response from emacs, getting client fd & result length */
316         buf[offset] = '\0';
317         sscanf(buf, "%d/%d", &s, &result_len);
318
319         while (result_len > 0) {
320                 if ((len = read(0, buf, min2(result_len, GSERV_BUFSZ))) < 0) {
321                         perror(progname);
322                         fprintf(stderr, "%s: unable to read\n", progname);
323                         exit(1);
324                 }
325                 buf[len] = '\0';
326                 send_string(s, buf);
327                 result_len -= len;
328         }
329
330         /* eat the newline */
331         while ((len = read(0, buf, 1)) == 0) ;
332         if (len < 0) {
333                 perror(progname);
334                 fprintf(stderr, "%s: unable to read\n", progname);
335                 exit(1);
336         }
337         if (buf[0] != '\n') {
338                 fprintf(stderr, "%s: garbage after result\n", progname);
339                 exit(1);
340         }
341         /* send the newline */
342         buf[1] = '\0';
343         send_string(s, buf);
344         close(s);
345
346 }                               /* handle_response */
347 #endif                          /* INTERNET_DOMAIN_SOCKETS || UNIX_DOMAIN_SOCKETS */
348
349 #ifdef INTERNET_DOMAIN_SOCKETS
350 struct entry {
351         unsigned long host_addr;
352         struct entry *next;
353 };
354
355 struct entry *permitted_hosts[TABLE_SIZE];
356
357 #ifdef AUTH_MAGIC_COOKIE
358 # include <X11/X.h>
359 # include <X11/Xauth.h>
360
361 static Xauth *server_xauth = NULL;
362 #endif
363
364 static int timed_read(int fd, char *buf, int max, int timeout, int one_line)
365 {
366         fd_set rmask;
367         struct timeval tv;      /* = {timeout, 0}; */
368         char c = 0;
369         int nbytes = 0;
370         int r;
371
372         tv.tv_sec = timeout;
373         tv.tv_usec = 0;
374
375         FD_ZERO(&rmask);
376         FD_SET(fd, &rmask);
377
378         do {
379                 r = select(fd + 1, &rmask, NULL, NULL, &tv);
380
381                 if (r > 0) {
382                         if (read(fd, &c, 1) == 1) {
383                                 *buf++ = c;
384                                 ++nbytes;
385                         } else {
386                                 printf("read error on socket\004\n");
387                                 return -1;
388                         }
389                 } else if (r == 0) {
390                         printf("read timed out\004\n");
391                         return -1;
392                 } else {
393                         printf("error in select\004\n");
394                         return -1;
395                 }
396         } while ((nbytes < max) && !(one_line && (c == '\n')));
397
398         --buf;
399         if (one_line && *buf == '\n') {
400                 *buf = 0;
401         }
402
403         return nbytes;
404 }
405
406 /*
407   permitted -- return whether a given host is allowed to connect to the server.
408 */
409 static int permitted(unsigned long host_addr, int fd)
410 {
411         int key;
412         struct entry *entry;
413
414         char auth_protocol[128];
415         char buf[1024];
416         int auth_data_len;
417
418         if (fd > 0) {
419                 /* we are checking permission on a real connection */
420
421                 /* Read auth protocol name */
422
423                 if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1)
424                     <= 0)
425                         return FALSE;
426
427                 if (strcmp(auth_protocol, DEFAUTH_NAME) &&
428                     strcmp(auth_protocol, MCOOKIE_NAME)) {
429                         printf
430                             ("authentication protocol (%s) from client is invalid...\n",
431                              auth_protocol);
432                         printf
433                             ("... Was the client an old version of gnuclient/gnudoit?\004\n");
434
435                         return FALSE;
436                 }
437
438                 if (!strcmp(auth_protocol, MCOOKIE_NAME)) {
439
440                         /*
441                          * doing magic cookie auth
442                          */
443
444                         if (timed_read(fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
445                                 return FALSE;
446
447                         auth_data_len = atoi(buf);
448
449                         if (auth_data_len <= 0
450                             || auth_data_len > (int)sizeof(buf)) {
451                                 return FALSE;
452                         }
453
454                         if (timed_read(fd, buf, auth_data_len, AUTH_TIMEOUT, 0)
455                             != auth_data_len)
456                                 return FALSE;
457
458 #ifdef AUTH_MAGIC_COOKIE
459                         if (server_xauth && server_xauth->data) {
460                                 /* Do a compare without comprising info about
461                                    the size of the cookie */
462                                 int auth_data_pos;
463                                 int auth_mismatches =
464                                     (auth_data_len ^ server_xauth->data_length);
465
466                                 for (auth_data_pos = 0;
467                                      auth_data_pos < auth_data_len;
468                                      ++auth_data_pos)
469                                         auth_mismatches |=
470                                             (buf[auth_data_pos] ^ server_xauth->
471                                              data[auth_data_pos %
472                                                   server_xauth->data_length]);
473
474                                 if (auth_mismatches == 0)
475                                         return TRUE;
476
477                                 for (; rand() % 1000;) ;
478                         }
479 #else
480                         printf
481                             ("client tried Xauth, but server is not compiled with Xauth\n");
482 #endif
483
484                         /*
485                          * auth failed, but allow this to fall through to the GNU_SECURE
486                          * protocol....
487                          */
488
489                         printf
490                             ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");
491
492                 }
493
494                 /* Other auth protocols go here, and should execute only if the
495                  * auth_protocol name matches.
496                  */
497
498         }
499
500         /* Now, try the old GNU_SECURE stuff... */
501
502         /* First find the hash key */
503         key = HASH(host_addr) % TABLE_SIZE;
504
505         /* Now check the chain for that hash key */
506         for (entry = permitted_hosts[key]; entry != NULL; entry = entry->next)
507                 if (host_addr == entry->host_addr)
508                         return (TRUE);
509
510         return (FALSE);
511
512 }                               /* permitted */
513
514 /*
515   add_host -- add the given host to the list of permitted hosts, provided it isn't
516               already there.
517 */
518 static void add_host(unsigned long host_addr)
519 {
520         int key;
521         struct entry *new_entry;
522
523         if (!permitted(host_addr, -1)) {
524                 if ((new_entry =
525                      (struct entry *)malloc(sizeof(struct entry))) == NULL) {
526                         fprintf(stderr,
527                                 "%s: unable to malloc space for permitted host entry\n",
528                                 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         /* if */
538 }                               /* add_host */
539
540 /*
541   setup_table -- 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 */
548 static int 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",
566                         progname, hostname);
567                 exit(1);
568         } else {
569                 host_addr = t;
570         }                       /* if */
571
572 #ifdef AUTH_MAGIC_COOKIE
573
574         server_xauth = XauGetAuthByAddr(FamilyInternet,
575                                         sizeof(host_addr), (char *)&host_addr,
576                                         strlen(MCOOKIE_SCREEN), MCOOKIE_SCREEN,
577                                         strlen(MCOOKIE_X_NAME), MCOOKIE_X_NAME);
578         hosts++;
579
580 #endif                          /* AUTH_MAGIC_COOKIE */
581
582 #if 0                           /* Don't even want to allow access from the local host by default */
583         add_host(host_addr);    /* add local host */
584 #endif
585
586         if (((file_name = getenv("GNU_SECURE")) != NULL &&      /* security file  */
587              (host_file = fopen(file_name, "r")) != NULL)) {    /* opened ok */
588                 while ((fscanf(host_file, "%s", hostname) != EOF)) {    /* find a host */
589                         t = internet_addr(hostname);
590                         if (t != -1) {  /* get its addr */
591                                 host_addr = t;
592                                 add_host(host_addr);    /* add the addr */
593                                 hosts++;
594                         }
595                 }
596                 fclose(host_file);
597         }
598         /* if */
599         return hosts;
600 }                               /* setup_table */
601
602 /*
603   internet_init -- initialize server, returning an internet socket that can
604                     be listened on.
605 */
606 static int internet_init(void)
607 {
608         int ls;                 /* socket descriptor */
609         struct servent *sp;     /* pointer to service information */
610         struct sockaddr_in server;      /* for local socket address */
611         char *ptr;              /* ptr to return from getenv */
612
613         if (setup_table() == 0)
614                 return -1;
615
616         /* clear out address structure */
617         memset(&server, '\0', sizeof(server));
618
619         /* Set up address structure for the listen socket. */
620         server.sin_family = AF_INET;
621         server.sin_addr.s_addr = INADDR_ANY;
622
623         /* Find the information for the gnu server
624          * in order to get the needed port number.
625          */
626         if ((ptr = getenv("GNU_PORT")) != NULL)
627                 server.sin_port = htons(atoi(ptr));
628         else if ((sp = getservbyname("gnuserv", "tcp")) == NULL)
629                 server.sin_port = htons(DEFAULT_PORT + getuid());
630         else
631                 server.sin_port = sp->s_port;
632
633         /* Create the listen socket. */
634         if ((ls = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
635                 perror(progname);
636                 fprintf(stderr, "%s: unable to create socket\n", progname);
637                 exit(1);
638         }
639
640         /* if */
641         /* Bind the listen address to the socket. */
642         if (bind(ls, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) ==
643             -1) {
644                 perror(progname);
645                 fprintf(stderr, "%s: unable to bind socket\n", progname);
646                 exit(1);
647         }
648
649         /* if */
650         /* Initiate the listen on the socket so remote users
651          * can connect.
652          */
653         if (listen(ls, 20) == -1) {
654                 perror(progname);
655                 fprintf(stderr, "%s: unable to listen\n", progname);
656                 exit(1);
657         }
658         /* if */
659         return (ls);
660
661 }                               /* internet_init */
662
663 /*
664   handle_internet_request -- accept a request from a client and send the information
665                              to stdout (the gnu process).
666 */
667 static void handle_internet_request(int ls)
668 {
669         int s;
670         socklen_t addrlen = sizeof(struct sockaddr_in);
671         struct sockaddr_in peer;        /* for peer socket address */
672
673         memset(&peer, '\0', sizeof(peer));
674
675         if ((s = accept(ls, (struct sockaddr *)&peer, &addrlen)) == -1) {
676                 perror(progname);
677                 fprintf(stderr, "%s: unable to accept\n", progname);
678                 exit(1);
679         }
680
681         /* if */
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                             "gnudoit: Connection refused\ngnudoit: unable to connect to remote");
686                 close(s);
687
688                 printf("Refused connection from %s\004\n",
689                        inet_ntoa(peer.sin_addr));
690                 return;
691         }
692         /* if */
693         echo_request(s);
694
695 }                               /* handle_internet_request */
696 #endif                          /* INTERNET_DOMAIN_SOCKETS */
697
698 #ifdef UNIX_DOMAIN_SOCKETS
699 /*
700   unix_init -- initialize server, returning an unix-domain socket that can
701                be listened on.
702 */
703 static int unix_init(void)
704 {
705         int ls;                 /* socket descriptor */
706         struct sockaddr_un server;      /* unix socket address */
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         /* if */
717         /* Set up address structure for the listen socket. */
718 #ifdef HIDE_UNIX_SOCKET
719         sz = snprintf(server.sun_path, sizeof(server.sun_path),
720                       "%s/gsrvdir%d", tmpdir, (int)geteuid());
721         assert(sz>=0 && (size_t)sz<sizeof(server.sun_path));
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) {
725                         perror(progname);
726                         fprintf(stderr, "%s: can't set permissions on %s\n",
727                                 progname, server.sun_path);
728                         exit(1);
729                 }
730         }
731         strcat(server.sun_path, "/gsrv");
732         unlink(server.sun_path);        /* remove old file if it exists */
733 #else                           /* HIDE_UNIX_SOCKET */
734         sz = snprintf(server.sun_path, sizeof(server.sun_path),
735                       "%s/gsrv%d", tmpdir, (int)geteuid());
736         assert(sz>=0 && sz<sizeof(server.sun_path));
737         unlink(server.sun_path);        /* remove old file if it exists */
738 #endif                          /* HIDE_UNIX_SOCKET */
739
740         server.sun_family = AF_UNIX;
741 #ifdef HAVE_SOCKADDR_SUN_LEN
742         /* See W. R. Stevens "Advanced Programming in the Unix Environment"
743            p. 502 */
744         bindlen = (sizeof(server.sun_len) + sizeof(server.sun_family)
745                    + strlen(server.sun_path) + 1);
746         server.sun_len = bindlen;
747 #else
748         bindlen = strlen(server.sun_path) + sizeof(server.sun_family);
749 #endif
750
751         if (bind(ls, (struct sockaddr *)&server, bindlen) < 0) {
752                 perror(progname);
753                 fprintf(stderr, "%s: unable to bind socket\n", progname);
754                 exit(1);
755         }
756         /* if */
757         chmod(server.sun_path, 0700);   /* only this user can send commands */
758
759         if (listen(ls, 20) < 0) {
760                 perror(progname);
761                 fprintf(stderr, "%s: unable to listen\n", progname);
762                 exit(1);
763         }
764
765         /* if */
766         /* #### there are also better ways of dealing with this when
767            sigvec() is present. */
768 #if  defined (HAVE_SIGPROCMASK)
769         {
770                 sigset_t _mask;
771                 sigemptyset(&_mask);
772                 sigaddset(&_mask, SIGPIPE);
773                 sigprocmask(SIG_BLOCK, &_mask, NULL);
774         }
775 #else
776         signal(SIGPIPE, SIG_IGN);       /* in case user kills client */
777 #endif
778
779         return (ls);
780
781 }                               /* unix_init */
782
783 /*
784   handle_unix_request -- accept a request from a client and send the information
785                          to stdout (the gnu process).
786 */
787 static void handle_unix_request(int ls)
788 {
789         int s;
790         socklen_t len = sizeof(struct sockaddr_un);
791         struct sockaddr_un server;      /* for unix socket address */
792
793         server.sun_family = AF_UNIX;
794
795         if ((s = accept(ls, (struct sockaddr *)&server, &len)) < 0) {
796                 perror(progname);
797                 fprintf(stderr, "%s: unable to accept\n", progname);
798         }
799         /* if */
800         echo_request(s);
801
802 }                               /* handle_unix_request */
803 #endif                          /* UNIX_DOMAIN_SOCKETS */
804
805 int main(int argc, char *argv[])
806 {
807         int chan;               /* temporary channel number */
808 #ifdef SYSV_IPC
809         struct msgbuf *msgp;    /* message buffer */
810 #else
811         int ils = -1;           /* internet domain listen socket */
812         int uls = -1;           /* unix domain listen socket */
813 #endif                          /* SYSV_IPC */
814
815         progname = argv[0];
816
817         for (chan = 3; chan < _NFILE; close(chan++))    /* close unwanted channels */
818                 ;
819
820 #ifdef USE_TMPDIR
821         tmpdir = getenv("TMPDIR");
822 #endif
823         if (!tmpdir)
824                 tmpdir = "/tmp";
825 #ifdef USE_LITOUT
826         {
827                 /* this is to allow ^D to pass to emacs */
828                 int d = LLITOUT;
829                 (void)ioctl(fileno(stdout), TIOCLBIS, &d);
830         }
831 #endif
832
833 #ifdef SYSV_IPC
834         ipc_init(&msgp);        /* get a msqid to listen on, and a message buffer */
835 #endif                          /* SYSV_IPC */
836
837 #ifdef INTERNET_DOMAIN_SOCKETS
838         ils = internet_init();  /* get an internet domain socket to listen on */
839 #endif                          /* INTERNET_DOMAIN_SOCKETS */
840
841 #ifdef UNIX_DOMAIN_SOCKETS
842         uls = unix_init();      /* get a unix domain socket to listen on */
843 #endif                          /* UNIX_DOMAIN_SOCKETS */
844
845         while (1) {
846 #ifdef SYSV_IPC
847                 handle_ipc_request(msgp);
848 #else                           /* NOT SYSV_IPC */
849                 fd_set rmask;
850                 FD_ZERO(&rmask);
851                 FD_SET(fileno(stdin), &rmask);
852                 if (uls >= 0)
853                         FD_SET(uls, &rmask);
854                 if (ils >= 0)
855                         FD_SET(ils, &rmask);
856
857                 if (select(max2(fileno(stdin), max2(uls, ils)) + 1, &rmask,
858                            (fd_set *) NULL, (fd_set *) NULL,
859                            (struct timeval *)NULL) < 0) {
860                         perror(progname);
861                         fprintf(stderr, "%s: unable to select\n", progname);
862                         return 1;
863                 }
864                 /* if */
865 #ifdef UNIX_DOMAIN_SOCKETS
866                 if (uls > 0 && FD_ISSET(uls, &rmask))
867                         handle_unix_request(uls);
868 #endif
869
870 #ifdef INTERNET_DOMAIN_SOCKETS
871                 if (ils > 0 && FD_ISSET(ils, &rmask))
872                         handle_internet_request(ils);
873 #endif                          /* INTERNET_DOMAIN_SOCKETS */
874
875                 if (FD_ISSET(fileno(stdin), &rmask))    /* from stdin (gnu process) */
876                         handle_response();
877 #endif                          /* NOT SYSV_IPC */
878         }                       /* while (1) */
879 }                               /* main */
880
881 #endif                          /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */