Merge branch 'bug/133' into for-steve
[sxemacs] / src / process-unix.c
1 /* Asynchronous subprocess implementation for UNIX
2    Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3    Free Software Foundation, Inc.
4    Copyright (C) 1995 Sun Microsystems, Inc.
5    Copyright (C) 1995, 1996 Ben Wing.
6
7 This file is part of SXEmacs
8
9 SXEmacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 SXEmacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program.  If not, see <http://www.gnu.org/licenses/>. */
21
22
23 /* This file has been Mule-ized except for `start-process-internal',
24    `open-network-stream-internal' and `open-multicast-group-internal'. */
25
26 /* This file has been split into process.c and process-unix.c by
27    Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
28    the original author(s) */
29
30 /* The IPv6 support is derived from the code for GNU Emacs-20.3
31    written by Wolfgang S. Rupprecht */
32
33 #include <config.h>
34
35 #if !defined (NO_SUBPROCESSES)
36
37 /* The entire file is within this conditional */
38
39 #include "lisp.h"
40
41 #include "buffer.h"
42 #include "events/events.h"
43 #include "ui/frame.h"
44 #include "hash.h"
45 #include "lstream.h"
46 #include "opaque.h"
47 #include "process.h"
48 #include "procimpl.h"
49 #include "sysdep.h"
50 #include "ui/window.h"
51 #ifdef FILE_CODING
52 #include "mule/file-coding.h"
53 #endif
54
55 #include <setjmp.h>
56 #include "sysfile.h"
57 #include "sysproc.h"
58 #include "systime.h"
59 #include "syssignal.h"          /* Always include before systty.h */
60 #include "ui/systty.h"
61 #include "syswait.h"
62
63 #ifdef HPUX
64 #include <grp.h>                /* See grantpt fixups for HPUX below. */
65 #endif
66
67 #if defined(HAVE_OPENSSL) && defined(OPENSSL_SSL)
68 #include "openssl.h"
69 #endif
70
71
72 /*
73  * Implementation-specific data. Pointed to by Lisp_Process->process_data
74  */
75
76 struct unix_process_data {
77         /* Always 0.  Used to be for tooltalk only. */
78         int connected_via_filedesc_p;
79         /* Descriptor by which we read from this process.  -1 for dead process */
80         int infd;
81         /* Descriptor for the tty which this process is using.
82            -1 if we didn't record it (on some systems, there's no need).  */
83         int subtty;
84         /* Name of subprocess terminal. */
85         Lisp_Object tty_name;
86         /* Non-false if communicating through a pty.  */
87         char pty_flag;
88 };
89
90
91 extern struct hash_table *usid_to_process;
92
93
94 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
95 \f
96 /**********************************************************************/
97 /*                    Static helper routines                          */
98 /**********************************************************************/
99
100 static SIGTYPE close_safely_handler(int signo)
101 {
102         EMACS_REESTABLISH_SIGNAL(signo, close_safely_handler);
103         SIGRETURN;
104 }
105
106 static void close_safely(int fd)
107 {
108         stop_interrupts();
109         signal(SIGALRM, close_safely_handler);
110         alarm(1);
111         close(fd);
112         alarm(0);
113         start_interrupts();
114 }
115
116 static void close_descriptor_pair(int in, int out)
117 {
118         if (in >= 0)
119                 close(in);
120         if (out != in && out >= 0)
121                 close(out);
122 }
123
124 /* Close all descriptors currently in use for communication
125    with subprocess.  This is used in a newly-forked subprocess
126    to get rid of irrelevant descriptors.  */
127
128 static int
129 close_process_descs_mapfun(const void *key, void *contents, void *arg)
130 {
131         Lisp_Object proc;
132         CVOID_TO_LISP(proc, contents);
133         event_stream_delete_stream_pair(XPROCESS(proc)->pipe_instream,
134                                         XPROCESS(proc)->pipe_outstream);
135         return 0;
136 }
137
138 /* #### This function is currently called from child_setup
139    in callproc.c. It should become static though - kkm */
140 void close_process_descs(void)
141 {
142         maphash(close_process_descs_mapfun, usid_to_process, 0);
143 }
144
145 /* connect to an existing file descriptor.  This is very similar to
146    open-network-stream except that it assumes that the connection has
147    already been initialized.  It is currently used for ToolTalk
148    communication. */
149
150 /* This function used to be visible on the Lisp level, but there is no
151    real point in doing that.  Here is the doc string:
152
153   "Connect to an existing file descriptor.
154 Return a subprocess-object to represent the connection.
155 Input and output work as for subprocesses; `delete-process' closes it.
156 Args are NAME BUFFER INFD OUTFD.
157 NAME is name for process.  It is modified if necessary to make it unique.
158 BUFFER is the buffer (or buffer-name) to associate with the process.
159  Process output goes at end of that buffer, unless you specify
160  an output stream or filter function to handle the output.
161  BUFFER may also be nil, meaning that this process is not associated
162  with any buffer.
163 INFD and OUTFD specify the file descriptors to use for input and
164  output, respectively."
165 */
166
167 Lisp_Object
168 connect_to_file_descriptor(Lisp_Object name, Lisp_Object buffer,
169                            Lisp_Object infd, Lisp_Object outfd)
170 {
171         /* This function can GC */
172         Lisp_Object proc;
173         EMACS_INT inch, outch;
174
175         CHECK_STRING(name);
176         CHECK_INT(infd);
177         CHECK_INT(outfd);
178
179         inch = XINT(infd);
180         outch = XINT(outfd);
181         if (get_process_from_usid(FD_TO_USID(inch)))
182                 invalid_operation("There is already a process connected to fd",
183                                   infd);
184         if (!NILP(buffer))
185                 buffer = Fget_buffer_create(buffer);
186         proc = make_process_internal(name);
187
188         XPROCESS(proc)->pid = Fcons(infd, name);
189         XPROCESS(proc)->buffer = buffer;
190         init_process_io_handles(XPROCESS(proc), (void*)inch, (void*)outch, 0);
191         UNIX_DATA(XPROCESS(proc))->connected_via_filedesc_p = 1;
192
193         event_stream_select_process(XPROCESS(proc));
194
195         return proc;
196 }
197
198 #ifdef HAVE_PTYS
199 static int allocate_pty_the_old_fashioned_way(void);
200
201 /* The file name of the (slave) pty opened by allocate_pty().  */
202 #ifndef MAX_PTYNAME_LEN
203 #define MAX_PTYNAME_LEN 64
204 #endif
205 static char pty_name[MAX_PTYNAME_LEN];
206
207 /* Open an available pty, returning a file descriptor.
208    Return -1 on failure.
209    The file name of the terminal corresponding to the pty
210    is left in the variable `pty_name'.  */
211
212 static int allocate_pty(void)
213 {
214         /* Unix98 standardized grantpt, unlockpt, and ptsname, but not the
215            functions required to open a master pty in the first place :-(
216
217            Modern Unix systems all seems to have convenience methods to open
218            a master pty fd in one function call, but there is little
219            agreement on how to do it.
220
221            allocate_pty() tries all the different known easy ways of opening
222            a pty.  In case of failure, we resort to the old BSD-style pty
223            grovelling code in allocate_pty_the_old_fashioned_way(). */
224 #ifndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY
225         int master_fd = -1;
226         const char *slave_name = NULL;
227         const char *_clone_ = NULL;
228         static const char *const clones[] = {
229                 /* Different pty master clone devices */
230                 "/dev/ptmx",    /* Various systems */
231                 "/dev/ptm/clone",       /* HPUX */
232                 "/dev/ptc",     /* AIX */
233                 "/dev/ptmx_bsd" /* Tru64 */
234         };
235
236 #ifdef HAVE_GETPT               /* glibc */
237         master_fd = getpt();
238         if (master_fd >= 0)
239                 goto have_master;
240 #endif                          /* HAVE_GETPT */
241
242 #if defined(HAVE_OPENPTY)       /* BSD, Tru64, glibc */
243         {
244                 int slave_fd = -1;
245                 int rc;
246                 EMACS_BLOCK_SIGNAL(SIGCHLD);
247                 rc = openpty(&master_fd, &slave_fd, NULL, NULL, NULL);
248                 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
249                 if (rc == 0) {
250                         slave_name = ttyname(slave_fd);
251                         close(slave_fd);
252                         goto have_slave_name;
253                 } else {
254                         if (master_fd >= 0)
255                                 close(master_fd);
256                         if (slave_fd >= 0)
257                                 close(slave_fd);
258                 }
259         }
260 #endif                          /* HAVE_OPENPTY */
261
262 #if defined(HAVE__GETPTY) && defined (O_NDELAY) /* SGI */
263         master_fd = -1;
264         EMACS_BLOCK_SIGNAL(SIGCHLD);
265         slave_name = _getpty(&master_fd, O_RDWR | O_NDELAY, 0600, 0);
266         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
267         if (master_fd >= 0 && slave_name != NULL)
268                 goto have_slave_name;
269 #endif                          /* HAVE__GETPTY */
270
271         /* Master clone devices are available on most systems */
272         {
273                 int i;
274                 for (i = 0; i < countof(clones); i++) {
275                         _clone_ = clones[i];
276                         master_fd =
277                             open(_clone_, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
278                         if (master_fd >= 0)
279                                 goto have_master;
280                 }
281                 _clone_ = NULL;
282         }
283
284         goto lose;
285
286       have_master:
287
288 #if defined (HAVE_PTSNAME)
289         slave_name = ptsname(master_fd);
290         if (slave_name)
291                 goto have_slave_name;
292 #endif
293
294         /* AIX docs say to use ttyname, not ptsname, to get slave_name */
295         if (_clone_ && !strcmp(_clone_, "/dev/ptc")
296             && (slave_name = ttyname(master_fd)) != NULL)
297                 goto have_slave_name;
298
299         goto lose;
300
301       have_slave_name:
302         strncpy(pty_name, slave_name, sizeof(pty_name));
303         pty_name[sizeof(pty_name) - 1] = '\0';
304         setup_pty(master_fd);
305
306         /* We jump through some hoops to frob the pty.
307            It's not obvious that checking the return code here is useful. */
308
309         /* "The grantpt() function will fail if it is unable to successfully
310            invoke the setuid root program.  It may also fail if the
311            application has installed a signal handler to catch SIGCHLD
312            signals." */
313 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
314         EMACS_BLOCK_SIGNAL(SIGCHLD);
315
316 #if defined (HAVE_GRANTPT)
317         grantpt(master_fd);
318 #ifdef HPUX
319         /* grantpt() behavior on some versions of HP-UX differs from what's
320            specified in the man page: the group of the slave PTY is set to
321            the user's primary group, and we fix that. */
322         {
323                 struct group *tty_group = getgrnam("tty");
324                 if (tty_group != NULL)
325                         chown(pty_name, (uid_t) - 1, tty_group->gr_gid);
326         }
327 #endif                          /* HPUX has broken grantpt() */
328 #endif                          /* HAVE_GRANTPT */
329
330 #if defined (HAVE_UNLOCKPT)
331         unlockpt(master_fd);
332 #endif
333
334         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
335 #endif                          /* HAVE_GRANTPT || HAVE_UNLOCKPT */
336
337         return master_fd;
338
339       lose:
340         if (master_fd >= 0)
341                 close(master_fd);
342 #endif                          /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
343         return allocate_pty_the_old_fashioned_way();
344 }
345
346 /* This function tries to allocate a pty by iterating through file
347    pairs with names like /dev/ptyp1 and /dev/ttyp1. */
348 static int allocate_pty_the_old_fashioned_way(void)
349 {
350         struct stat stb;
351
352         /* Some systems name their pseudoterminals so that there are gaps in
353            the usual sequence - for example, on HP9000/S700 systems, there
354            are no pseudoterminals with names ending in 'f'.  So we wait for
355            three failures in a row before deciding that we've reached the
356            end of the ptys.  */
357         int failed_count = 0;
358         int fd;
359         int i;
360         int c;
361
362 #ifdef PTY_ITERATION
363         PTY_ITERATION
364 #else
365 # ifndef FIRST_PTY_LETTER
366 # define FIRST_PTY_LETTER 'p'
367 # endif
368         for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
369                 for (i = 0; i < 16; i++)
370 #endif                          /* PTY_ITERATION */
371
372                 {
373                         int sz;
374
375 #ifdef PTY_NAME_SPRINTF
376                         PTY_NAME_SPRINTF;
377 #else
378                         sz = snprintf(pty_name, sizeof(pty_name), "/dev/pty%c%x", c, i);
379                         assert(sz >= 0 && (size_t)sz < sizeof(pty_name));
380 #endif                          /* no PTY_NAME_SPRINTF */
381
382                         if (sxemacs_stat(pty_name, &stb) < 0) {
383                                 if (++failed_count >= 3)
384                                         return -1;
385                         } else
386                                 failed_count = 0;
387                         fd = open(pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY,
388                                   0);
389
390                         if (fd >= 0) {
391 #ifdef PTY_TTY_NAME_SPRINTF
392                                 PTY_TTY_NAME_SPRINTF;
393 #else
394                                 sz = snprintf(pty_name, sizeof(pty_name),
395                                                   "/dev/tty%c%x", c, i);
396                                 assert(sz >= 0 && (size_t)sz < sizeof(pty_name));
397 #endif                          /* no PTY_TTY_NAME_SPRINTF */
398                                 if (access(pty_name, R_OK | W_OK) == 0) {
399                                         setup_pty(fd);
400                                         return fd;
401                                 }
402                                 close(fd);
403                         }
404                 }               /* iteration */
405         return -1;
406 }
407 #endif                          /* HAVE_PTYS */
408
409 static int
410 create_bidirectional_pipe(long int *inchannel, long int *outchannel,
411                           volatile int *forkin, volatile int *forkout)
412 {
413         int sv[2];
414
415 #ifdef SKTPAIR
416         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
417                 return -1;
418         *outchannel = *inchannel = sv[0];
419         *forkout = *forkin = sv[1];
420 #else                           /* not SKTPAIR */
421         int temp;
422         temp = pipe(sv);
423         if (temp < 0)
424                 return -1;
425         *inchannel = sv[0];
426         *forkout = sv[1];
427         temp = pipe(sv);
428         if (temp < 0)
429                 return -1;
430         *outchannel = sv[1];
431         *forkin = sv[0];
432 #endif                          /* not SKTPAIR */
433         return 0;
434 }
435
436 #ifdef HAVE_SOCKETS
437
438 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
439 static int
440 get_internet_address(Lisp_Object host, struct sockaddr_in *address,
441                      Error_behavior errb)
442 {
443         struct hostent *host_info_ptr = NULL;
444 #ifdef TRY_AGAIN
445         int count = 0;
446 #endif
447
448         xzero(*address);
449
450         while (1) {
451 #ifdef TRY_AGAIN
452                 if (count++ > 10)
453                         break;
454                 h_errno = 0;
455 #endif
456                 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
457                 slow_down_interrupts();
458                 host_info_ptr = gethostbyname((char *)XSTRING_DATA(host));
459                 speed_up_interrupts();
460 #ifdef TRY_AGAIN
461                 if (!(host_info_ptr == 0 && h_errno == TRY_AGAIN))
462 #endif
463                         break;
464                 Fsleep_for(make_int(1));
465         }
466         if (host_info_ptr) {
467                 address->sin_family = host_info_ptr->h_addrtype;
468                 memcpy(&address->sin_addr, host_info_ptr->h_addr,
469                        host_info_ptr->h_length);
470         } else {
471                 IN_ADDR numeric_addr;
472                 /* Attempt to interpret host as numeric inet address */
473                 numeric_addr = inet_addr((char *)XSTRING_DATA(host));
474                 if (NUMERIC_ADDR_ERROR) {
475                         maybe_error(Qprocess, errb,
476                                     "Unknown host \"%s\"", XSTRING_DATA(host));
477                         return 0;
478                 }
479
480                 /* There was some broken code here that called strlen() here
481                    on (char *) &numeric_addr and even sometimes accessed
482                    uninitialized data. */
483                 address->sin_family = AF_INET;
484                 *(IN_ADDR *) & address->sin_addr = numeric_addr;
485         }
486
487         return 1;
488 }
489 #endif                          /*  !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
490
491 static void set_socket_nonblocking_maybe(int fd, int port, const char *proto)
492 {
493 #ifdef PROCESS_IO_BLOCKING
494         Lisp_Object tail;
495
496         for (tail = network_stream_blocking_port_list; CONSP(tail);
497              tail = XCDR(tail)) {
498                 Lisp_Object tail_port = XCAR(tail);
499
500                 if (STRINGP(tail_port)) {
501                         struct servent *svc_info;
502                         CHECK_STRING(tail_port);
503                         svc_info =
504                             getservbyname((char *)XSTRING_DATA(tail_port),
505                                           proto);
506                         if ((svc_info != 0) && (svc_info->s_port == port))
507                                 break;
508                         else
509                                 continue;
510                 } else if (INTP(tail_port)
511                            && (htons((unsigned short)XINT(tail_port)) == port))
512                         break;
513         }
514
515         if (!CONSP(tail)) {
516                 set_descriptor_non_blocking(fd);
517         }
518 #else
519         set_descriptor_non_blocking(fd);
520 #endif                          /* PROCESS_IO_BLOCKING */
521 }
522
523 #endif                          /* HAVE_SOCKETS */
524
525 /* Compute the Lisp form of the process status from
526    the numeric status that was returned by `wait'.  */
527
528 static void update_status_from_wait_code(Lisp_Process * p, int *w_fmh)
529 {
530         /* C compiler lossage when attempting to pass w directly */
531         int w = *w_fmh;
532
533         if (WIFSTOPPED(w)) {
534                 p->status_symbol = Qstop;
535                 p->exit_code = WSTOPSIG(w);
536                 p->core_dumped = 0;
537         } else if (WIFEXITED(w)) {
538                 p->status_symbol = Qexit;
539                 p->exit_code = WEXITSTATUS(w);
540                 p->core_dumped = 0;
541         } else if (WIFSIGNALED(w)) {
542                 p->status_symbol = Qsignal;
543                 p->exit_code = WTERMSIG(w);
544                 p->core_dumped = WCOREDUMP(w);
545         } else {
546                 p->status_symbol = Qrun;
547                 p->exit_code = 0;
548         }
549 }
550
551 #ifdef SIGCHLD
552
553 #define MAX_EXITED_PROCESSES 1000
554 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
555 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
556 static volatile int exited_processes_index;
557
558 static volatile int sigchld_happened;
559
560 /* On receipt of a signal that a child status has changed,
561  loop asking about children with changed statuses until
562  the system says there are no more.  All we do is record
563  the processes and wait status.
564
565  This function could be called from within the SIGCHLD
566  handler, so it must be completely reentrant.  When
567  not called from a SIGCHLD handler, BLOCK_SIGCHLD should
568  be non-zero so that SIGCHLD is blocked while this
569  function is running. (This is necessary so avoid
570  race conditions with the SIGCHLD_HAPPENED flag). */
571
572 static void record_exited_processes(int block_sigchld)
573 {
574         if (!sigchld_happened) {
575                 return;
576         }
577 #ifdef EMACS_BLOCK_SIGNAL
578         if (block_sigchld)
579                 EMACS_BLOCK_SIGNAL(SIGCHLD);
580 #endif
581
582         while (sigchld_happened) {
583                 int pid;
584                 int w;
585
586                 /* Keep trying to get a status until we get a definitive result.  */
587                 do {
588                         errno = 0;
589 #ifdef WNOHANG
590 #  ifndef WUNTRACED
591 #    define WUNTRACED 0
592 #  endif                        /* not WUNTRACED */
593 #  ifdef HAVE_WAITPID
594                         pid = waitpid((pid_t) - 1, &w, WNOHANG | WUNTRACED);
595 #  else
596                         pid = wait3(&w, WNOHANG | WUNTRACED, 0);
597 #  endif
598 #else                           /* not WNOHANG */
599                         pid = wait(&w);
600 #endif                          /* not WNOHANG */
601                 }
602                 while (pid <= 0 && errno == EINTR);
603
604                 if (pid <= 0)
605                         break;
606
607                 if (exited_processes_index < MAX_EXITED_PROCESSES) {
608                         exited_processes[exited_processes_index] = pid;
609                         exited_processes_status[exited_processes_index] = w;
610                         exited_processes_index++;
611                 }
612
613                 /* On systems with WNOHANG, we just ignore the number
614                    of times that SIGCHLD was signalled, and keep looping
615                    until there are no more processes to wait on.  If we
616                    don't have WNOHANG, we have to rely on the count in
617                    SIGCHLD_HAPPENED. */
618 #ifndef WNOHANG
619                 sigchld_happened--;
620 #endif                          /* not WNOHANG */
621         }
622
623         sigchld_happened = 0;
624
625         if (block_sigchld)
626                 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
627 }
628
629 /* For any processes that have changed status and are recorded
630    and such, update the corresponding Lisp_Process.
631    We separate this from record_exited_processes() so that
632    we never have to call this function from within a signal
633    handler.  We block SIGCHLD in case record_exited_processes()
634    is called from a signal handler. */
635
636 /** USG WARNING:  Although it is not obvious from the documentation
637  in signal(2), on a USG system the SIGCLD handler MUST NOT call
638  signal() before executing at least one wait(), otherwise the handler
639  will be called again, resulting in an infinite loop.  The relevant
640  portion of the documentation reads "SIGCLD signals will be queued
641  and the signal-catching function will be continually reentered until
642  the queue is empty".  Invoking signal() causes the kernel to reexamine
643  the SIGCLD queue.   Fred Fish, UniSoft Systems Inc.
644
645  (Note that now this only applies in SYS V Release 2 and before.
646  On SYS V Release 3, we use sigset() to set the signal handler for
647  the first time, and so we don't have to reestablish the signal handler
648  in the handler below.  On SYS V Release 4, we don't get this weirdo
649  behavior when we use sigaction(), which we do use.) */
650
651 static SIGTYPE sigchld_handler(int signo)
652 {
653 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
654         int old_errno = errno;
655
656         sigchld_happened++;
657         record_exited_processes(0);
658         errno = old_errno;
659 #else
660         sigchld_happened++;
661 #endif
662 #ifdef HAVE_UNIXOID_EVENT_LOOP
663         signal_fake_event();
664 #endif
665         /* WARNING - must come after wait3() for USG systems */
666         EMACS_REESTABLISH_SIGNAL(signo, sigchld_handler);
667         SIGRETURN;
668 }
669
670 #endif                          /* SIGCHLD */
671
672 #ifdef SIGNALS_VIA_CHARACTERS
673 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
674
675 static int process_signal_char(int tty_fd, int signo)
676 {
677         /* If it's not a tty, pray that these default values work */
678         if (!isatty(tty_fd)) {
679 #define CNTL(ch) (037 & (ch))
680                 switch (signo) {
681                 case SIGINT:
682                         return CNTL('C');
683                 case SIGQUIT:
684                         return CNTL('\\');
685 #ifdef SIGTSTP
686                 case SIGTSTP:
687                         return CNTL('Z');
688 #endif
689                 default:
690                         break;
691                 }
692         }
693 #ifdef HAVE_TERMIOS
694         /* TERMIOS is the latest and bestest, and seems most likely to work.
695            If the system has it, use it. */
696         {
697                 struct termios t;
698                 tcgetattr(tty_fd, &t);
699                 switch (signo) {
700                 case SIGINT:
701                         return t.c_cc[VINTR];
702                 case SIGQUIT:
703                         return t.c_cc[VQUIT];
704 #if defined(SIGTSTP) && defined(VSUSP)
705                 case SIGTSTP:
706                         return t.c_cc[VSUSP];
707 #endif
708                 default:
709                         break;
710                 }
711         }
712
713 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
714         {
715                 /* On Berkeley descendants, the following IOCTL's retrieve the
716                    current control characters.  */
717                 struct tchars c;
718                 struct ltchars lc;
719                 switch (signo) {
720                 case SIGINT:
721                         ioctl(tty_fd, TIOCGETC, &c);
722                         return c.t_intrc;
723                 case SIGQUIT:
724                         ioctl(tty_fd, TIOCGETC, &c);
725                         return c.t_quitc;
726 #  ifdef SIGTSTP
727                 case SIGTSTP:
728                         ioctl(tty_fd, TIOCGLTC, &lc);
729                         return lc.t_suspc;
730 #  endif                        /* SIGTSTP */
731                 }
732         }
733
734 # elif defined (TCGETA)         /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
735         {
736                 /* On SYSV descendants, the TCGETA ioctl retrieves the current
737                    control characters.  */
738                 struct termio t;
739                 ioctl(tty_fd, TCGETA, &t);
740                 switch (signo) {
741                 case SIGINT:
742                         return t.c_cc[VINTR];
743                 case SIGQUIT:
744                         return t.c_cc[VQUIT];
745 #  ifdef SIGTSTP
746                 case SIGTSTP:
747                         return t.c_cc[VSWTCH];
748 #  endif                        /* SIGTSTP */
749                 }
750         }
751 # else                          /* ! defined (TCGETA) */
752 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
753         /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
754            you'd better be using one of the alternatives above!  */
755 # endif                         /* ! defined (TCGETA) */
756         return '\0';
757 }
758 #endif                          /* SIGNALS_VIA_CHARACTERS */
759 \f
760 /**********************************************************************/
761 /*              Process implementation methods                        */
762 /**********************************************************************/
763
764 /*
765  * Allocate and initialize Lisp_Process->process_data
766  */
767
768 static void unix_alloc_process_data(Lisp_Process * p)
769 {
770         p->process_data = xnew(struct unix_process_data);
771
772         UNIX_DATA(p)->connected_via_filedesc_p = 0;
773         UNIX_DATA(p)->infd = -1;
774         UNIX_DATA(p)->subtty = -1;
775         UNIX_DATA(p)->tty_name = Qnil;
776         UNIX_DATA(p)->pty_flag = 0;
777 }
778
779 /*
780  * Mark any Lisp objects in Lisp_Process->process_data
781  */
782
783 static void unix_mark_process_data(Lisp_Process * proc)
784 {
785         mark_object(UNIX_DATA(proc)->tty_name);
786 }
787
788 /*
789  * Initialize SXEmacs process implementation once
790  */
791
792 #ifdef SIGCHLD
793 static void unix_init_process(void)
794 {
795 #ifndef CANNOT_DUMP
796         if (!noninteractive || initialized)
797 #endif
798                 signal(SIGCHLD, sigchld_handler);
799 }
800 #endif                          /* SIGCHLD */
801
802 /*
803  * Initialize any process local data. This is called when newly
804  * created process is connected to real OS file handles. The
805  * handles are generally represented by void* type, but are
806  * of type int (file descriptors) for UNIX.
807  */
808
809 static void
810 unix_init_process_io_handles(Lisp_Process * p, void *in, void *out, int flags)
811 {
812         Lisp_Object process = Qnil;
813         USID        usid = FD_TO_USID((EMACS_INT)in);
814         XSETPROCESS(process, p);
815         puthash((const void *)usid, LISP_TO_VOID(process),
816                 usid_to_process);
817         UNIX_DATA(p)->infd = (EMACS_INT)in;
818 }
819
820 /*
821  * Fork off a subprocess. P is a pointer to a newly created subprocess
822  * object. If this function signals, the caller is responsible for
823  * deleting (and finalizing) the process object.
824  *
825  * The method must return PID of the new process, a (positive??? ####) number
826  * which fits into Lisp_Int. No return value indicates an error, the method
827  * must signal an error instead.
828  */
829
830 static int
831 unix_create_process(Lisp_Process * p,
832                     Lisp_Object * argv, int nargv,
833                     Lisp_Object program, Lisp_Object cur_dir)
834 {
835         int pid;
836         long int inchannel = -1;
837         long int outchannel = -1;
838         /* Use volatile to protect variables from being clobbered by longjmp.  */
839         volatile int forkin = -1;
840         volatile int forkout = -1;
841         volatile int pty_flag = 0;
842
843 #ifdef HAVE_PTYS
844         if (!NILP(Vprocess_connection_type)) {
845                 /* find a new pty, open the master side, return the opened
846                    file handle, and store the name of the corresponding slave
847                    side in global variable pty_name. */
848                 outchannel = inchannel = allocate_pty();
849         }
850
851         if (inchannel >= 0) {
852                 /* You're "supposed" to now open the slave in the child.
853                    On some systems, we can open it here; this allows for
854                    better error checking. */
855 #if !defined(USG)
856                 /* On USG systems it does not work to open the pty's tty here
857                    and then close and reopen it in the child.  */
858 #ifdef O_NOCTTY
859                 /* Don't let this terminal become our controlling terminal
860                    (in case we don't have one).  */
861                 forkout = forkin =
862                     open(pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
863 #else
864                 forkout = forkin = open(pty_name, O_RDWR | OPEN_BINARY, 0);
865 #endif
866                 if (forkin < 0)
867                         goto io_failure;
868 #endif                          /* not USG */
869                 UNIX_DATA(p)->pty_flag = pty_flag = 1;
870         } else
871 #endif                          /* HAVE_PTYS */
872         if (create_bidirectional_pipe(
873                     (void*)&inchannel, (void*)&outchannel,
874                     &forkin, &forkout) < 0)
875                 goto io_failure;
876
877 #if 0
878         /* Replaced by close_process_descs */
879         set_exclusive_use(inchannel);
880         set_exclusive_use(outchannel);
881 #endif
882
883         set_descriptor_non_blocking(inchannel);
884         set_descriptor_non_blocking(outchannel);
885
886         /* Record this as an active process, with its channels.
887            As a result, child_setup will close Emacs's side of the pipes.  */
888         init_process_io_handles(p, (void *)inchannel, (void *)outchannel,
889                                 pty_flag ? STREAM_PTY_FLUSHING : 0);
890         /* Record the tty descriptor used in the subprocess.  */
891         UNIX_DATA(p)->subtty = forkin;
892
893         {
894                 /* child_setup must clobber environ on systems with true vfork.
895                    Protect it from permanent change.  */
896                 char **save_environ = environ;
897
898                 pid = fork();
899                 if (pid == 0) {
900         /**** Now we're in the child process ****/
901                         int xforkin = forkin;
902                         int xforkout = forkout;
903
904                         /* Checking for quit in the child is bad because that will 
905                            cause I/O, and that, in turn, can confuse the X connection. */
906                         begin_dont_check_for_quit();
907
908                         /* Disconnect the current controlling terminal, pursuant to
909                            making the pty be the controlling terminal of the process.
910                            Also put us in our own process group. */
911
912                         disconnect_controlling_terminal();
913
914 #ifdef HAVE_PTYS
915                         if (pty_flag) {
916                                 /* Open the pty connection and make the pty's terminal
917                                    our controlling terminal.
918
919                                    On systems with TIOCSCTTY, we just use it to set
920                                    the controlling terminal.  On other systems, the
921                                    first TTY we open becomes the controlling terminal.
922                                    So, we end up with four possibilities:
923
924                                    (1) on USG and TIOCSCTTY systems, we open the pty
925                                    and use TIOCSCTTY.
926                                    (2) on other USG systems, we just open the pty.
927                                    (3) on non-USG systems with TIOCSCTTY, we
928                                    just use TIOCSCTTY. (On non-USG systems, we
929                                    already opened the pty in the parent process.)
930                                    (4) on non-USG systems without TIOCSCTTY, we
931                                    close the pty and reopen it.
932
933                                    This would be cleaner if we didn't open the pty
934                                    in the parent process, but doing it that way
935                                    makes it possible to trap error conditions.
936                                    It's harder to convey an error from the child
937                                    process, and I don't feel like messing with
938                                    this now. */
939
940                                 /* There was some weirdo, probably wrong,
941                                    conditionalization on RTU and UNIPLUS here.
942                                    I deleted it.  So sue me. */
943
944                                 /* SunOS has TIOCSCTTY but the close/open method
945                                    also works. */
946
947 #  if defined (USG) || !defined (TIOCSCTTY)
948                                 /* Now close the pty (if we had it open) and reopen it.
949                                    This makes the pty the controlling terminal of the
950                                    subprocess.  */
951                                 /* I wonder if close (open (pty_name, ...)) would work?  */
952                                 if (xforkin >= 0)
953                                         close(xforkin);
954                                 xforkout = xforkin =
955                                     open(pty_name, O_RDWR | OPEN_BINARY, 0);
956                                 if (xforkin < 0) {
957                                         write(1,
958                                               "Couldn't open the pty terminal ",
959                                               31);
960                                         write(1, pty_name, strlen(pty_name));
961                                         write(1, "\n", 1);
962                                         _exit(1);
963                                 }
964 #  endif                        /* USG or not TIOCSCTTY */
965
966                                 /* Miscellaneous setup required for some systems.
967                                    Must be done before using tc* functions on xforkin.
968                                    This guarantees that isatty(xforkin) is true. */
969
970 #  if defined (HAVE_ISASTREAM) && defined (I_PUSH)
971                                 if (isastream(xforkin)) {
972 #    if defined (I_FIND)
973 #      define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
974 #    else
975 #      define stream_module_pushed(fd, module) 0
976 #    endif
977                                         if (!stream_module_pushed
978                                             (xforkin, "ptem"))
979                                                 ioctl(xforkin, I_PUSH, "ptem");
980                                         if (!stream_module_pushed
981                                             (xforkin, "ldterm"))
982                                                 ioctl(xforkin, I_PUSH,
983                                                       "ldterm");
984                                         if (!stream_module_pushed
985                                             (xforkin, "ttcompat"))
986                                                 ioctl(xforkin, I_PUSH,
987                                                       "ttcompat");
988                                 }
989 #  endif                        /* HAVE_ISASTREAM */
990
991 #  ifdef TIOCSCTTY
992                                 /* We ignore the return value
993                                    because faith@cs.unc.edu says that is necessary on Linux.  */
994                                 assert(isatty(xforkin));
995                                 ioctl(xforkin, TIOCSCTTY, 0);
996 #  endif                        /* TIOCSCTTY */
997
998                                 /* Change the line discipline. */
999
1000 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1001                                 {
1002                                         struct termios t;
1003                                         assert(isatty(xforkin));
1004                                         tcgetattr(xforkin, &t);
1005                                         t.c_lflag = LDISC1;
1006                                         if (tcsetattr(xforkin, TCSANOW, &t) < 0)
1007                                                 perror
1008                                                     ("create_process/tcsetattr LDISC1 failed\n");
1009                                 }
1010 # elif defined (NTTYDISC) && defined (TIOCSETD)
1011                                 {
1012                                         /* Use new line discipline.  TIOCSETD is accepted and
1013                                            ignored on Sys5.4 systems with ttcompat. */
1014                                         int ldisc = NTTYDISC;
1015                                         assert(isatty(xforkin));
1016                                         ioctl(xforkin, TIOCSETD, &ldisc);
1017                                 }
1018 # endif                         /* TIOCSETD & NTTYDISC */
1019
1020                                 /* Make our process group be the foreground group
1021                                    of our new controlling terminal. */
1022
1023                                 {
1024                                         pid_t piddly =
1025                                             EMACS_GET_PROCESS_GROUP();
1026                                         EMACS_SET_TTY_PROCESS_GROUP(xforkin,
1027                                                                     &piddly);
1028                                 }
1029
1030                                 /* On AIX, we've disabled SIGHUP above once we start a
1031                                    child on a pty.  Now reenable it in the child, so it
1032                                    will die when we want it to.
1033                                    JV: This needs to be done ALWAYS as we might have inherited
1034                                    a SIG_IGN handling from our parent (nohup) and we are in new
1035                                    process group.
1036                                  */
1037                                 signal(SIGHUP, SIG_DFL);
1038                         }
1039
1040                         if (pty_flag)
1041                                 /* Set up the terminal characteristics of the pty. */
1042                                 child_setup_tty(xforkout);
1043
1044 #endif                          /* HAVE_PTYS */
1045
1046                         signal(SIGINT, SIG_DFL);
1047                         signal(SIGQUIT, SIG_DFL);
1048
1049                         {
1050                                 char *current_dir;
1051                                 char **new_argv =
1052                                     alloca_array(char *, nargv + 2);
1053                                 int i;
1054
1055                                 /* Nothing below here GCs so our string pointers shouldn't move. */
1056                                 new_argv[0] = (char *)XSTRING_DATA(program);
1057                                 for (i = 0; i < nargv; i++) {
1058                                         CHECK_STRING(argv[i]);
1059                                         new_argv[i + 1] =
1060                                             (char *)XSTRING_DATA(argv[i]);
1061                                 }
1062                                 new_argv[i + 1] = 0;
1063
1064                                 LISP_STRING_TO_EXTERNAL(cur_dir, current_dir,
1065                                                         Qfile_name);
1066
1067                                 child_setup(xforkin, xforkout, xforkout,
1068                                             new_argv, current_dir);
1069                         }
1070
1071                 }
1072
1073             /**** End of child code ****/
1074  /**** Back in parent process ****/
1075                 environ = save_environ;
1076         }
1077
1078         if (pid < 0) {
1079                 int save_errno = errno;
1080                 close_descriptor_pair(forkin, forkout);
1081                 errno = save_errno;
1082                 report_file_error("Doing fork", Qnil);
1083         }
1084
1085         /* #### dmoore - why is this commented out, otherwise we leave
1086            subtty = forkin, but then we close forkin just below. */
1087         /* UNIX_DATA(p)->subtty = -1; */
1088
1089         /* If the subfork execv fails, and it exits,
1090            this close hangs.  I don't know why.
1091            So have an interrupt jar it loose.  */
1092         if (forkin >= 0)
1093                 close_safely(forkin);
1094         if (forkin != forkout && forkout >= 0)
1095                 close(forkout);
1096
1097 #ifdef HAVE_PTYS
1098         if (pty_flag)
1099                 UNIX_DATA(p)->tty_name = build_string(pty_name);
1100         else
1101 #endif
1102                 UNIX_DATA(p)->tty_name = Qnil;
1103
1104         /* Notice that SIGCHLD was not blocked. (This is not possible on
1105            some systems.) No biggie if SIGCHLD occurs right around the
1106            time that this call happens, because SIGCHLD() does not actually
1107            deselect the process (that doesn't occur until the next time
1108            we're waiting for an event, when status_notify() is called). */
1109         return pid;
1110
1111       io_failure:
1112         {
1113                 int save_errno = errno;
1114                 close_descriptor_pair(forkin, forkout);
1115                 close_descriptor_pair(inchannel, outchannel);
1116                 errno = save_errno;
1117                 report_file_error("Opening pty or pipe", Qnil);
1118                 return 0;       /* not reached */
1119         }
1120 }
1121
1122 /* This is called to set process' virtual terminal size */
1123
1124 static int unix_set_window_size(Lisp_Process * p, int cols, int rows)
1125 {
1126         return set_window_size(UNIX_DATA(p)->infd, cols, rows);
1127 }
1128
1129 /*
1130  * This method is called to update status fields of the process
1131  * structure. If the process has not existed, this method is
1132  * expected to do nothing.
1133  *
1134  * The method is called only for real child processes.
1135  */
1136
1137 #ifdef HAVE_WAITPID
1138 static void unix_update_status_if_terminated(Lisp_Process * p)
1139 {
1140         int w;
1141 #ifdef SIGCHLD
1142         EMACS_BLOCK_SIGNAL(SIGCHLD);
1143 #endif
1144         if (waitpid(XINT(p->pid), &w, WNOHANG) == XINT(p->pid)) {
1145                 p->tick++;
1146                 update_status_from_wait_code(p, &w);
1147         }
1148 #ifdef SIGCHLD
1149         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1150 #endif
1151 }
1152 #endif
1153
1154 /*
1155  * Update status of all exited processes. Called when SIGCLD has signaled.
1156  */
1157
1158 #ifdef SIGCHLD
1159 static void unix_reap_exited_processes(void)
1160 {
1161         int i;
1162         Lisp_Process *p;
1163
1164 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1165         record_exited_processes(1);
1166 #endif
1167
1168         if (exited_processes_index <= 0) {
1169                 return;
1170         }
1171 #ifdef  EMACS_BLOCK_SIGNAL
1172         EMACS_BLOCK_SIGNAL(SIGCHLD);
1173 #endif
1174         for (i = 0; i < exited_processes_index; i++) {
1175                 int pid = exited_processes[i];
1176                 int w = exited_processes_status[i];
1177
1178                 /* Find the process that signaled us, and record its status.  */
1179
1180                 p = 0;
1181                 {
1182                         Lisp_Object tail;
1183                         LIST_LOOP(tail, Vprocess_list) {
1184                                 Lisp_Object proc = XCAR(tail);
1185                                 p = XPROCESS(proc);
1186                                 if (INTP(p->pid) && XINT(p->pid) == pid)
1187                                         break;
1188                                 p = 0;
1189                         }
1190                 }
1191
1192                 if (p) {
1193                         /* Change the status of the process that was found.  */
1194                         p->tick++;
1195                         process_tick++;
1196                         update_status_from_wait_code(p, &w);
1197
1198                         /* If process has terminated, stop waiting for its output.  */
1199                         if (WIFSIGNALED(w) || WIFEXITED(w)) {
1200                                 if (!NILP(p->pipe_instream)) {
1201                                         /* We can't just call event_stream->unselect_process_cb (p)
1202                                            here, because that calls XtRemoveInput, which is not
1203                                            necessarily reentrant, so we can't call this at interrupt
1204                                            level.
1205                                          */
1206                                 }
1207                         }
1208                 } else {
1209                         /* There was no asynchronous process found for that id.  Check
1210                            if we have a synchronous process. Only set sync process status
1211                            if there is one, so we work OK with the waitpid() call in
1212                            wait_for_termination(). */
1213                         if (synch_process_alive != 0) { /* Set the global sync process status variables. */
1214                                 synch_process_alive = 0;
1215
1216                                 /* Report the status of the synchronous process.  */
1217                                 if (WIFEXITED(w))
1218                                         synch_process_retcode = WEXITSTATUS(w);
1219                                 else if (WIFSIGNALED(w))
1220                                         synch_process_death =
1221                                             signal_name(WTERMSIG(w));
1222                         }
1223                 }
1224         }
1225
1226         exited_processes_index = 0;
1227
1228         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1229 }
1230 #endif                          /* SIGCHLD */
1231
1232 /*
1233  * Stuff the entire contents of LSTREAM to the process output pipe
1234  */
1235
1236 static JMP_BUF send_process_frame;
1237
1238 static SIGTYPE send_process_trap(int signum)
1239 {
1240         EMACS_REESTABLISH_SIGNAL(signum, send_process_trap);
1241         EMACS_UNBLOCK_SIGNAL(signum);
1242         LONGJMP(send_process_frame, 1);
1243 }
1244
1245 static void
1246 unix_send_process(Lisp_Object proc, lstream_t lstream)
1247 {
1248         /* Use volatile to protect variables from being clobbered by longjmp.  */
1249         SIGTYPE(*volatile old_sigpipe) (int) = 0;
1250         volatile Lisp_Object vol_proc = proc;
1251         Lisp_Process *volatile p = XPROCESS(proc);
1252
1253         /* #### JV: layering violation?
1254
1255            This function knows too much about the relation between the encoding
1256            stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1257
1258            If encoding streams properly forwarded all calls, we could simply
1259            use DATA_OUTSTREAM everywhere. */
1260
1261         if (!SETJMP(send_process_frame)) {
1262                 /* use a reasonable-sized buffer (somewhere around the size of the
1263                    stream buffer) so as to avoid inundating the stream with blocked
1264                    data. */
1265                 Bufbyte chunkbuf[512];
1266                 Bytecount chunklen = 0;
1267
1268                 do {
1269                         Lstream_data_count writeret;
1270                         if (p->process_type!=PROCESS_TYPE_NETWORK_SERVER_LISTEN) {
1271                                 chunklen = Lstream_read(lstream, chunkbuf, 512);
1272                         }
1273                         old_sigpipe =
1274                             (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1275                         if (chunklen > 0) {
1276                                 int save_errno;
1277
1278                                 switch (p->process_type) {
1279                                 case PROCESS_TYPE_NETWORK_SERVER_LISTEN:
1280                                         report_file_error ("no writing to listen process possible",
1281                                                            list1 (proc));
1282                                         break;
1283                                 case PROCESS_TYPE_SSL:
1284                                 case PROCESS_TYPE_PROC:
1285                                 case PROCESS_TYPE_NETWORK:
1286                                 case PROCESS_TYPE_MULTICAST:
1287                                 default:
1288 /* Lstream_write() will never successfully write less than
1289  * the amount sent in.  In the worst case, it just buffers
1290  * the unwritten data. */
1291                                         writeret = Lstream_write
1292                                                 (XLSTREAM (DATA_OUTSTREAM(p)),
1293                                                  chunkbuf, chunklen);
1294                                         break;
1295                                 }
1296                                 save_errno = errno;
1297                                 signal (SIGPIPE, old_sigpipe);
1298                                 errno = save_errno;
1299                                 if (writeret < 0)
1300 /* This is a real error.  Blocking errors are handled
1301  * specially inside of the filedesc stream.
1302  */
1303                                         report_file_error ("writing to process",
1304                                                            list1 (proc));
1305                         } else {
1306 /* Need to make sure that everything up to and including the
1307  * last chunk is flushed, even when the pipe is currently
1308  * blocked. */
1309                                 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1310                                 signal (SIGPIPE, old_sigpipe);
1311                         }
1312                         while (Lstream_was_blocked_p
1313                                (XLSTREAM(p->pipe_outstream))) {
1314                                 /* Buffer is full.  Wait, accepting input;
1315                                  * that may allow the program
1316                                  * to finish doing output and read more.
1317                                  */
1318                                 Faccept_process_output(Qnil, make_int(1), Qnil);
1319                                 /* It could have *really* finished,
1320                                  * deleting the process */
1321                                 if (NILP(p->pipe_outstream))
1322                                         return;
1323                                 old_sigpipe = (SIGTYPE(*)(int))signal(
1324                                         SIGPIPE,
1325                                         send_process_trap);
1326                                 Lstream_flush(XLSTREAM(p->pipe_outstream));
1327                                 signal(SIGPIPE, old_sigpipe);
1328                         }
1329                         /* Perhaps should abort() if < 0?
1330                          * This should never happen.
1331                          */
1332                 }
1333                 while (chunklen > 0);
1334         } else {        /* We got here from a longjmp() from the SIGPIPE handler */
1335                 signal(SIGPIPE, old_sigpipe);
1336                 /* Close the file lstream so we don't attempt to write to it further */
1337                 /* #### There is controversy over whether this might cause fd leakage */
1338                 /*      my tests say no. -slb */
1339                 XLSTREAM(p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1340 #ifdef FILE_CODING
1341                 XLSTREAM(p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1342 #endif
1343                 p->status_symbol = Qexit;
1344                 p->exit_code = 256;     /* #### SIGPIPE ??? */
1345                 p->core_dumped = 0;
1346                 p->tick++;
1347                 process_tick++;
1348                 deactivate_process(vol_proc);
1349                 invalid_operation("SIGPIPE raised on process; closed it",
1350                                   p->name);
1351         }
1352
1353         old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1354         Lstream_flush(XLSTREAM(DATA_OUTSTREAM(p)));
1355         signal(SIGPIPE, old_sigpipe);
1356 }
1357
1358 /*
1359  * Send EOF to the process. The default implementation simply
1360  * closes the output stream. The method must return 0 to call
1361  * the default implementation, or 1 if it has taken all care about
1362  * sending EOF to the process.
1363  */
1364
1365 static int unix_process_send_eof(Lisp_Object proc)
1366 {
1367         if (!UNIX_DATA(XPROCESS(proc))->pty_flag)
1368                 return 0;
1369
1370         /* #### get_eof_char simply doesn't return the correct character
1371            here.  Maybe it is needed to determine the right eof
1372            character in init_process_io_handles but here it simply screws
1373            things up. */
1374 #if 0
1375         Bufbyte eof_char = get_eof_char(XPROCESS(proc));
1376         send_process(proc, Qnil, &eof_char, 0, 1);
1377 #else
1378         send_process(proc, Qnil, (const Bufbyte *)"\004", 0, 1);
1379 #endif
1380         return 1;
1381 }
1382
1383 /*
1384  * Called before the process is deactivated. The process object
1385  * is not immediately finalized, just undergoes a transition to
1386  * inactive state.
1387  *
1388  * The return value is a unique stream ID, as returned by
1389  * event_stream_delete_stream_pair
1390  *
1391  * In the lack of this method, only event_stream_delete_stream_pair
1392  * is called on both I/O streams of the process.
1393  *
1394  * The UNIX version guards this by ignoring possible SIGPIPE.
1395  */
1396
1397 static USID unix_deactivate_process(Lisp_Process * p)
1398 {
1399         SIGTYPE(*old_sigpipe) (int) = 0;
1400         USID usid;
1401
1402         if (UNIX_DATA(p)->infd >= 0)
1403                 flush_pending_output(UNIX_DATA(p)->infd);
1404
1405         /* closing the outstream could result in SIGPIPE, so ignore it. */
1406         old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, SIG_IGN);
1407         usid =  FD_TO_USID(UNIX_DATA(p)->infd);
1408         event_stream_delete_stream_pair(p->pipe_instream,
1409                                         p->pipe_outstream);
1410
1411         signal(SIGPIPE, old_sigpipe);
1412
1413         UNIX_DATA(p)->infd = -1;
1414
1415         return usid;
1416 }
1417
1418 /* If the subtty field of the process data is not filled in, do so now. */
1419 static void try_to_initialize_subtty(struct unix_process_data *upd)
1420 {
1421         if (upd->pty_flag && (upd->subtty == -1 || !isatty(upd->subtty))
1422             && STRINGP(upd->tty_name))
1423                 upd->subtty =
1424                     open((char *)XSTRING_DATA(upd->tty_name), O_RDWR, 0);
1425 }
1426
1427 /* Send signal number SIGNO to PROCESS.
1428    CURRENT_GROUP means send to the process group that currently owns
1429    the terminal being used to communicate with PROCESS.
1430    This is used for various commands in shell mode.
1431    If NOMSG is zero, insert signal-announcements into process's buffers
1432    right away.
1433
1434    If we can, we try to signal PROCESS by sending control characters
1435    down the pty.  This allows us to signal inferiors who have changed
1436    their uid, for which killpg would return an EPERM error,
1437    or processes running on other machines via remote login.
1438
1439    The method signals an error if the given SIGNO is not valid. */
1440
1441 static void
1442 unix_kill_child_process(Lisp_Object proc, int signo,
1443                         int current_group, int nomsg)
1444 {
1445         pid_t pgid = -1;
1446         Lisp_Process *p = XPROCESS(proc);
1447         struct unix_process_data *d = UNIX_DATA(p);
1448
1449         switch (signo) {
1450 #ifdef SIGCONT
1451         case SIGCONT:
1452                 p->status_symbol = Qrun;
1453                 p->exit_code = 0;
1454                 p->tick++;
1455                 process_tick++;
1456                 if (!nomsg)
1457                         status_notify();
1458                 break;
1459 #endif                          /* ! defined (SIGCONT) */
1460         case SIGINT:
1461         case SIGQUIT:
1462         case SIGKILL:
1463                 flush_pending_output(d->infd);
1464                 break;
1465         default:
1466                 break;
1467         }
1468
1469         if (!d->pty_flag)
1470                 current_group = 0;
1471
1472         /* If current_group is true, we want to send a signal to the
1473            foreground process group of the terminal our child process is
1474            running on.  You would think that would be easy.
1475
1476            The BSD people invented the TIOCPGRP ioctl to get the foreground
1477            process group of a tty.  That, combined with killpg, gives us
1478            what we want.
1479
1480            However, the POSIX standards people, in their infinite wisdom,
1481            have seen fit to only allow this for processes which have the
1482            terminal as controlling terminal, which doesn't apply to us.
1483
1484            Sooo..., we have to do something non-standard.  The ioctls
1485            TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1486            many systems.  POSIX tcgetpgrp(), since it is *documented* as not
1487            doing what we want, is actually less likely to work than the BSD
1488            ioctl TIOCGPGRP it is supposed to obsolete.  Sometimes we have to
1489            use TIOCGPGRP on the master end, sometimes the slave end
1490            (probably an AIX bug).  So we better get a fd for the slave if we
1491            haven't got it yet.
1492
1493            Anal operating systems like SGI Irix and Compaq Tru64 adhere
1494            strictly to the letter of the law, so our hack doesn't work.
1495            The following fragment from an Irix header file is suggestive:
1496
1497            #ifdef __notdef__
1498            // this is not currently supported
1499            #define TIOCSIGNAL      (tIOC|31)       // pty: send signal to slave
1500            #endif
1501
1502            On those systems where none of our tricks work, we just fall back
1503            to the non-current_group behavior and kill the process group of
1504            the child.
1505          */
1506         if (current_group) {
1507                 try_to_initialize_subtty(d);
1508
1509 #ifdef SIGNALS_VIA_CHARACTERS
1510                 /* If possible, send signals to the entire pgrp
1511                    by sending an input character to it.  */
1512                 {
1513                         char sigchar = process_signal_char(d->subtty, signo);
1514                         if (sigchar) {
1515                                 send_process(proc, Qnil, (Bufbyte *) & sigchar,
1516                                              0, 1);
1517                                 return;
1518                         }
1519                 }
1520 #endif                          /* SIGNALS_VIA_CHARACTERS */
1521
1522 #ifdef TIOCGPGRP
1523                 if (pgid == -1)
1524                         ioctl(d->infd, TIOCGPGRP, &pgid);       /* BSD */
1525                 if (pgid == -1 && d->subtty != -1)
1526                         ioctl(d->subtty, TIOCGPGRP, &pgid);     /* Only this works on AIX! */
1527 #endif                          /* TIOCGPGRP */
1528
1529                 if (pgid == -1) {
1530                         /* Many systems provide an ioctl to send a signal directly */
1531 #ifdef TIOCSIGNAL               /* Solaris, HP-UX */
1532                         if (ioctl(d->infd, TIOCSIGNAL, signo) != -1)
1533                                 return;
1534 #endif                          /* TIOCSIGNAL */
1535
1536 #ifdef TIOCSIG                  /* BSD */
1537                         if (ioctl(d->infd, TIOCSIG, signo) != -1)
1538                                 return;
1539 #endif                          /* TIOCSIG */
1540                 }
1541         }
1542         /* current_group */
1543         if (pgid == -1)
1544                 /* Either current_group is 0, or we failed to get the foreground
1545                    process group using the trickery above.  So we fall back to
1546                    sending the signal to the process group of our child process.
1547                    Since this is often a shell that ignores signals like SIGINT,
1548                    the shell's subprocess is killed, which is the desired effect.
1549                    The process group of p->pid is always p->pid, since it was
1550                    created as a process group leader. */
1551                 pgid = XINT(p->pid);
1552
1553         /* Finally send the signal. */
1554         if (EMACS_KILLPG(pgid, signo) == -1) {
1555                 /* It's not an error if our victim is already dead.
1556                    And we can't rely on the result of killing a zombie, since
1557                    XPG 4.2 requires that killing a zombie fail with ESRCH,
1558                    while FIPS 151-2 requires that it succeeds! */
1559 #ifdef ESRCH
1560                 if (errno != ESRCH)
1561 #endif
1562                         error("kill (%ld, %ld) failed: %s",
1563                               (long)pgid, (long)signo, strerror(errno));
1564         }
1565 }
1566
1567 /* Send signal SIGCODE to any process in the system given its PID.
1568    Return zero if successful, a negative number upon failure. */
1569
1570 static int unix_kill_process_by_pid(int pid, int sigcode)
1571 {
1572         return kill(pid, sigcode);
1573 }
1574
1575 /* Return TTY name used to communicate with subprocess. */
1576
1577 static Lisp_Object unix_get_tty_name(Lisp_Process * p)
1578 {
1579         return UNIX_DATA(p)->tty_name;
1580 }
1581
1582 /* Canonicalize host name HOST, and return its canonical form.
1583    The default implementation just takes HOST for a canonical name. */
1584
1585 #ifdef HAVE_SOCKETS
1586 static Lisp_Object unix_canonicalize_host_name(Lisp_Object host)
1587 {
1588 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1589         struct addrinfo hints, *res;
1590         static char addrbuf[NI_MAXHOST];
1591         Lisp_Object canonname;
1592         int retval;
1593         char *ext_host;
1594
1595         xzero(hints);
1596         hints.ai_flags = AI_CANONNAME;
1597 #ifdef IPV6_CANONICALIZE
1598         hints.ai_family = AF_UNSPEC;
1599 #else
1600         hints.ai_family = PF_INET;
1601 #endif
1602         hints.ai_socktype = SOCK_STREAM;
1603         hints.ai_protocol = 0;
1604         LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1605         retval = getaddrinfo(ext_host, NULL, &hints, &res);
1606         if (retval != 0) {
1607                 char *gai_error_l;
1608
1609                 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1610                                      gai_error_l, Qnative);
1611                 maybe_error(Qprocess, ERROR_ME_NOT,
1612                             "%s \"%s\"", gai_error_l, XSTRING_DATA(host));
1613                 canonname = host;
1614         } else {
1615                 int gni = getnameinfo(res->ai_addr, res->ai_addrlen,
1616                                       addrbuf, sizeof(addrbuf),
1617                                       NULL, 0, NI_NUMERICHOST);
1618                 canonname = gni ? host : build_ext_string(addrbuf, Qnative);
1619
1620                 freeaddrinfo(res);
1621         }
1622
1623         return canonname;
1624 #else                           /* ! HAVE_GETADDRINFO */
1625         struct sockaddr_in address;
1626
1627         if (!get_internet_address(host, &address, ERROR_ME_NOT))
1628                 return host;
1629
1630         if (address.sin_family == AF_INET)
1631                 return build_string(inet_ntoa(address.sin_addr));
1632         else
1633                 /* #### any clue what to do here? */
1634                 return host;
1635 #endif                          /* ! HAVE_GETADDRINFO */
1636 }
1637
1638 /* Open a TCP network connection to a given HOST/SERVICE.
1639    Treated exactly like a normal process when reading and writing.
1640    Only differences are in status display and process deletion.
1641    A network connection has no PID; you cannot signal it.  All you can
1642    do is deactivate and close it via delete-process. */
1643
1644 static void
1645 unix_open_network_stream(Lisp_Object name, Lisp_Object host,
1646                          Lisp_Object service, Lisp_Object protocol,
1647                          void **vinfd, void **voutfd)
1648 {
1649         EMACS_INT inch;
1650         EMACS_INT outch;
1651         volatile int s;
1652         volatile int port;
1653         volatile int retry = 0;
1654         int retval;
1655
1656         CHECK_STRING(host);
1657
1658         if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
1659                 invalid_argument("Unsupported protocol", protocol);
1660
1661         {
1662 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1663                 struct addrinfo hints, *res;
1664                 struct addrinfo *volatile lres;
1665                 char *portstring;
1666                 volatile int xerrno = 0;
1667                 volatile int failed_connect = 0;
1668                 char *ext_host;
1669                 char portbuf[sizeof(long)*3 + 2];
1670                 /*
1671                  * Caution: service can either be a string or int.
1672                  * Convert to a C string for later use by getaddrinfo.
1673                  */
1674                 if (INTP(service)) {
1675                         int sz= snprintf(portbuf, sizeof(portbuf), "%ld",
1676                                          (long)XINT(service));
1677                         assert(sz >= 0 && (size_t)sz < sizeof(portbuf));
1678                         portstring = portbuf;
1679                         port = htons((unsigned short)XINT(service));
1680                 } else {
1681                         CHECK_STRING(service);
1682                         LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
1683                         port = 0;
1684                 }
1685
1686                 xzero(hints);
1687                 hints.ai_flags = 0;
1688                 hints.ai_family = AF_UNSPEC;
1689                 if (EQ(protocol, Qtcp))
1690                         hints.ai_socktype = SOCK_STREAM;
1691                 else            /* EQ (protocol, Qudp) */
1692                         hints.ai_socktype = SOCK_DGRAM;
1693                 hints.ai_protocol = 0;
1694                 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1695                 retval = getaddrinfo(ext_host, portstring, &hints, &res);
1696                 if (retval != 0) {
1697                         char *gai_error_l;
1698
1699                         EXTERNAL_TO_C_STRING(gai_strerror(retval),
1700                                              gai_error_l, Qnative);
1701                         error("%s/%s %s", XSTRING_DATA(host), portstring,
1702                               gai_error_l);
1703                 }
1704
1705                 /* address loop */
1706                 for (lres = res; lres; lres = lres->ai_next) {
1707                         if (EQ(protocol, Qtcp))
1708                                 s = socket(lres->ai_family, SOCK_STREAM, 0);
1709                         else    /* EQ (protocol, Qudp) */
1710                                 s = socket(lres->ai_family, SOCK_DGRAM, 0);
1711
1712                         if (s < 0)
1713                                 continue;
1714
1715                         /* Turn off interrupts here -- see comments below.
1716                            There used to be code which called
1717                            bind_polling_period() to slow the polling period down
1718                            rather than turn it off, but that seems rather bogus
1719                            to me.  Best thing here is to use a non-blocking
1720                            connect or something, to check for QUIT. */
1721
1722                         /* Comments that are not quite valid: */
1723
1724                         /* Kernel bugs (on Ultrix at least) cause lossage (not
1725                            just EINTR) when connect is interrupted.  So let's
1726                            not let it get interrupted.  Note we do not turn off
1727                            polling, because polling is only used when not
1728                            interrupt_input, and thus not normally used on the
1729                            systems which have this bug.  On systems which use
1730                            polling, there's no way to quit if polling is turned
1731                            off.  */
1732
1733                         /* Slow down polling.  Some kernels have a bug which
1734                            causes retrying connect to fail after a connect.  */
1735
1736                         slow_down_interrupts();
1737
1738                       loop:
1739
1740                         /* A system call interrupted with a SIGALRM or SIGIO
1741                            comes back here, with can_break_system_calls reset to
1742                            0. */
1743                         SETJMP(break_system_call_jump);
1744                         if (QUITP) {
1745                                 speed_up_interrupts();
1746                                 REALLY_QUIT;
1747                                 /* In case something really weird happens ... */
1748                                 slow_down_interrupts();
1749                         }
1750
1751                         /* Break out of connect with a signal (it isn't
1752                            otherwise possible).  Thus you don't get screwed with
1753                            a hung network. */
1754                         can_break_system_calls = 1;
1755                         retval = connect(s, lres->ai_addr, lres->ai_addrlen);
1756                         can_break_system_calls = 0;
1757                         if (retval == -1) {
1758                                 xerrno = errno;
1759                                 if (errno != EISCONN) {
1760                                         if (errno == EINTR)
1761                                                 goto loop;
1762                                         if (errno == EADDRINUSE && retry < 20) {
1763                                                 /* A delay here is needed on
1764                                                    some FreeBSD systems, and
1765                                                    it is harmless, since this
1766                                                    retrying takes time anyway
1767                                                    and should be infrequent.
1768                                                    `sleep-for' allowed for
1769                                                    quitting this loop with
1770                                                    interrupts slowed down so
1771                                                    it can't be used here.
1772                                                    Async timers should already
1773                                                    be disabled at this point
1774                                                    so we can use `sleep'. */
1775                                                 retry++;
1776                                                 goto loop;
1777                                         }
1778                                 }
1779
1780                                 failed_connect = 1;
1781                                 close(s);
1782                                 s = -1;
1783
1784                                 speed_up_interrupts();
1785
1786                                 continue;
1787                         }
1788
1789                         if (port == 0) {
1790                                 int gni;
1791                                 char servbuf[NI_MAXSERV];
1792
1793                                 if (EQ(protocol, Qtcp))
1794                                         gni =
1795                                             getnameinfo(lres->ai_addr,
1796                                                         lres->ai_addrlen, NULL,
1797                                                         0, servbuf,
1798                                                         sizeof(servbuf),
1799                                                         NI_NUMERICSERV);
1800                                 else    /* EQ (protocol, Qudp) */
1801                                         gni =
1802                                             getnameinfo(lres->ai_addr,
1803                                                         lres->ai_addrlen, NULL,
1804                                                         0, servbuf,
1805                                                         sizeof(servbuf),
1806                                                         NI_NUMERICSERV |
1807                                                         NI_DGRAM);
1808
1809                                 if (gni == 0)
1810                                         port = strtol(servbuf, NULL, 10);
1811                         }
1812
1813                         break;
1814                 }               /* address loop */
1815
1816                 speed_up_interrupts();
1817
1818                 freeaddrinfo(res);
1819                 if (s < 0) {
1820                         errno = xerrno;
1821
1822                         if (failed_connect)
1823                                 report_file_error("connection failed",
1824                                                   list2(host, name));
1825                         else
1826                                 report_file_error("error creating socket",
1827                                                   list1(name));
1828                 }
1829 #else                           /* ! HAVE_GETADDRINFO */
1830                 struct sockaddr_in address;
1831
1832                 if (INTP(service))
1833                         port = htons((unsigned short)XINT(service));
1834                 else {
1835                         struct servent *svc_info;
1836                         CHECK_STRING(service);
1837
1838                         if (EQ(protocol, Qtcp))
1839                                 svc_info =
1840                                     getservbyname((char *)XSTRING_DATA(service),
1841                                                   "tcp");
1842                         else    /* EQ (protocol, Qudp) */
1843                                 svc_info =
1844                                     getservbyname((char *)XSTRING_DATA(service),
1845                                                   "udp");
1846
1847                         if (svc_info == 0)
1848                                 invalid_argument("Unknown service", service);
1849                         port = svc_info->s_port;
1850                 }
1851
1852                 get_internet_address(host, &address, ERROR_ME);
1853                 address.sin_port = port;
1854
1855                 if (EQ(protocol, Qtcp))
1856                         s = socket(address.sin_family, SOCK_STREAM, 0);
1857                 else            /* EQ (protocol, Qudp) */
1858                         s = socket(address.sin_family, SOCK_DGRAM, 0);
1859
1860                 if (s < 0)
1861                         report_file_error("error creating socket", list1(name));
1862
1863                 /* Turn off interrupts here -- see comments below.  There used to
1864                    be code which called bind_polling_period() to slow the polling
1865                    period down rather than turn it off, but that seems rather
1866                    bogus to me.  Best thing here is to use a non-blocking connect
1867                    or something, to check for QUIT. */
1868
1869                 /* Comments that are not quite valid: */
1870
1871                 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1872                    when connect is interrupted.  So let's not let it get interrupted.
1873                    Note we do not turn off polling, because polling is only used
1874                    when not interrupt_input, and thus not normally used on the systems
1875                    which have this bug.  On systems which use polling, there's no way
1876                    to quit if polling is turned off.  */
1877
1878                 /* Slow down polling.  Some kernels have a bug which causes retrying
1879                    connect to fail after a connect.  */
1880
1881                 slow_down_interrupts();
1882
1883               loop:
1884
1885                 /* A system call interrupted with a SIGALRM or SIGIO comes back
1886                    here, with can_break_system_calls reset to 0. */
1887                 SETJMP(break_system_call_jump);
1888                 if (QUITP) {
1889                         speed_up_interrupts();
1890                         REALLY_QUIT;
1891                         /* In case something really weird happens ... */
1892                         slow_down_interrupts();
1893                 }
1894
1895                 /* Break out of connect with a signal (it isn't otherwise possible).
1896                    Thus you don't get screwed with a hung network. */
1897                 can_break_system_calls = 1;
1898                 retval =
1899                     connect(s, (struct sockaddr *)&address, sizeof(address));
1900                 can_break_system_calls = 0;
1901                 if (retval == -1 && errno != EISCONN) {
1902                         int xerrno = errno;
1903                         if (errno == EINTR)
1904                                 goto loop;
1905                         if (errno == EADDRINUSE && retry < 20) {
1906                                 /* A delay here is needed on some FreeBSD
1907                                    systems, and it is harmless, since this
1908                                    retrying takes time anyway and should
1909                                    be infrequent.  `sleep-for' allowed for
1910                                    quitting this loop with interrupts
1911                                    slowed down so it can't be used here.
1912                                    Async timers should already be disabled
1913                                    at this point so we can use `sleep'. */
1914                                 retry++;
1915                                 goto loop;
1916                         }
1917
1918                         close(s);
1919
1920                         speed_up_interrupts();
1921
1922                         errno = xerrno;
1923                         report_file_error("connection failed",
1924                                           list2(host, name));
1925                 }
1926
1927                 speed_up_interrupts();
1928 #endif                          /* ! HAVE_GETADDRINFO */
1929         }
1930
1931         inch = s;
1932         outch = dup(s);
1933         if (outch < 0) {
1934                 close(s);       /* this used to be leaked; from Kyle Jones */
1935                 report_file_error("error duplicating socket", list1(name));
1936         }
1937
1938         set_socket_nonblocking_maybe(inch, port, "tcp");
1939
1940         *vinfd = (void *)inch;
1941         *voutfd = (void *)outch;
1942 }
1943
1944
1945 /*
1946   Return the listener process of the accepted listened process
1947 */
1948 static Lisp_Object unix_network_process_listener(Lisp_Object process)
1949 {
1950         Lisp_Process *listener = 0,
1951                      *p = XPROCESS(process);
1952         Lisp_Object   ret = Qnil;
1953         int           sock = 0;
1954         struct  gcpro ngcpro1;
1955
1956         if (!PROCESS_READABLE_P(p)) 
1957                 return Qnil;
1958
1959         if (!CONSP(p->pid) || NILP(XCDR(XCDR(p->pid))))
1960                 return Qnil;
1961
1962         NGCPRO1(ret);
1963         sock = XINT(XCAR(XCDR(p->pid)));
1964         listener = get_process_from_usid(FD_TO_USID(sock));
1965         ret = listener ? (Lisp_Object)listener : Qnil;
1966         NUNGCPRO;
1967         return ret;
1968 }
1969
1970 /*
1971   Unwind a call to the network server stream accept below
1972 */
1973 static Lisp_Object exec_acceptor_unwind(Lisp_Object datum)
1974 {
1975         Lisp_Cons *d = XCONS(datum);
1976         free_cons(d);
1977         return Qnil;
1978 }
1979
1980
1981 /*
1982   Accept a connection being listened in the given network server
1983   stream process.
1984   Create a new network stream for the accepted connection.
1985   Call the acceptor callback and setup the sentinel and filter functions
1986 */
1987 static void unix_network_server_accept(Lisp_Object process)
1988 {
1989         Lisp_Process *p = XPROCESS(process);
1990         Lisp_Object np = Qnil;
1991         Lisp_Object acceptor = Qnil, filter = Qnil, sentinel = Qnil;
1992         Lisp_Object bufname = Qnil;
1993         Lisp_Object buffer = Qnil;
1994         long int ns, inch, outch;
1995         struct sockaddr_in sa;
1996         int sa_size = sizeof(sa);
1997         struct gcpro ngcpro1, ngcpro2, ngcpro3, ngcpro4, ngcpro5;
1998
1999         if (!PROCESS_READABLE_P(p)) 
2000                 return;
2001
2002         /* Make sure the listen process is not disconnected
2003            afterwards.  We have to make this here because in process.c
2004            we should not have any knowledge we need to do this, and in
2005            unix_open_network_server_stream we have no access to the
2006            process struct. It works, so I'm not complaining...
2007          */
2008         UNIX_DATA(p)->connected_via_filedesc_p = 1;
2009         
2010         errno = 0; /* if we got an error, let it be from the accept call */
2011         ns = accept((int)UNIX_DATA(p)->infd, (struct sockaddr*)(&sa),
2012                     (socklen_t*)&sa_size);
2013         if ( ns < 0 ) 
2014                 return;
2015
2016         NGCPRO5(np,bufname,acceptor,filter,sentinel);
2017         if (CONSP(p->process_type_data)) {
2018                 acceptor = XCAR(p->process_type_data);
2019                 filter = XCDR(p->process_type_data);
2020                 if (CONSP(filter)) {
2021                         sentinel = XCDR(filter);
2022                         filter   = XCAR(filter);
2023                 }
2024                 if (CONSP(sentinel)) {
2025                         bufname  = XCDR(sentinel);
2026                         sentinel = XCAR(sentinel);
2027                 }
2028                 if (CONSP(bufname)) {
2029                         bufname  = XCAR(bufname);
2030                 }
2031         }
2032         if (!NILP(bufname)) {
2033                 Lisp_Object args[] = {
2034                         build_string("<server port:%S listened_on:%S>"),
2035                         make_int(sa.sin_port), bufname
2036                 };
2037                 bufname = Fformat( 3, args );
2038         } else {
2039                 Lisp_Object args[] = {
2040                         build_string("<server proc:%S pid:%S service:%S>"),
2041                         p->name, p->pid, make_int(sa.sin_port)
2042                 };
2043                 bufname = Fformat( 5, args );
2044         }
2045         if (!NILP(bufname) ) {
2046                 bufname = Fgenerate_new_buffer_name(bufname,Qnil);
2047                 buffer  =  Fget_buffer_create(bufname);
2048         }
2049         np = make_process_internal(p->name);
2050         XPROCESS(np)->pid = Fcons( make_int(sa.sin_port),
2051                                    Fcons(make_int(UNIX_DATA(p)->infd),p->pid));
2052         XPROCESS(np)->process_type = PROCESS_TYPE_NETWORK;
2053         XPROCESS(np)->buffer = buffer;
2054         inch = ns;
2055         outch = dup(ns);
2056         set_socket_nonblocking_maybe(inch, sa.sin_port, "tcp");
2057         init_process_io_handles(XPROCESS(np), (void *)inch, (void *)outch,
2058                                 STREAM_NETWORK_CONNECTION);
2059         /* Process the call backs.. */
2060         if (CONSP(p->process_type_data)) {
2061                 if (!NILP(filter)) {
2062                         XPROCESS(np)->filter = filter;
2063                 }
2064                 if (!NILP(sentinel)) {
2065                         XPROCESS(np)->sentinel = sentinel;
2066                 }
2067                 if (!NILP(acceptor)) {
2068                         int speccount = specpdl_depth();
2069                         record_unwind_protect(exec_acceptor_unwind,
2070                                               noseeum_cons(process, acceptor));
2071                         running_asynch_code = 1;
2072                         call1_trapping_errors("Error in server stream acceptor",
2073                                               acceptor, np);
2074                         running_asynch_code = 0;
2075                         restore_match_data();
2076                         unbind_to(speccount, Qnil);
2077                         
2078                 }
2079         } else {
2080                 /* We have to log something here... */
2081         }
2082         event_stream_select_process(XPROCESS(np));
2083         NUNGCPRO;
2084 }
2085
2086 /* Open a TCP network connection to a given HOST/SERVICE.
2087    Treated exactly like a normal process when reading and writing.
2088    Only differences are in status display and process deletion.
2089    A network connection has no PID; you cannot signal it.  All you can
2090    do is deactivate and close it via delete-process. */
2091
2092 static void
2093 unix_open_network_server_stream(Lisp_Object name, Lisp_Object host,
2094                                 Lisp_Object service, Lisp_Object protocol,
2095                                 void **vinfd, void **voutfd)
2096 {
2097         EMACS_INT inch;
2098         EMACS_INT outch;
2099         volatile int s;
2100         volatile int port;
2101         volatile int retry = 0;
2102         int retval;
2103         /* FIXME: Limited to 5 since it is the maximum for several BSD
2104            based implementations of sockets, and it is an acceptable
2105            value for a low rate of service purpose like this facility
2106            was designed for. */
2107         int listenQ = 5; 
2108
2109
2110         if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
2111                 invalid_argument("Unsupported protocol", protocol);
2112
2113         {
2114 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
2115                 struct addrinfo hints, *res;
2116                 struct addrinfo *volatile lres;
2117                 char *portstring;
2118                 volatile int xerrno = 0;
2119                 volatile int failed_connect = 0;
2120                 char *ext_host;
2121                 char portbuf[sizeof(long)*3 + 2];
2122                 /*
2123                  * Caution: service can either be a string or int.
2124                  * Convert to a C string for later use by getaddrinfo.
2125                  */
2126                 if (INTP(service)) {
2127                         int sz = snprintf(portbuf, sizeof(portbuf), "%ld",
2128                                           (long)XINT(service));
2129                         assert(sz >= 0 && (size_t)sz < sizeof(portbuf));
2130                         portstring = portbuf;
2131                         port = htons((unsigned short)XINT(service));
2132                 } else {
2133                         CHECK_STRING(service);
2134                         LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
2135                         port = 0;
2136                 }
2137
2138                 xzero(hints);
2139                 hints.ai_flags = 0;
2140                 hints.ai_family = AF_UNSPEC;
2141                 if (EQ(protocol, Qtcp))
2142                         hints.ai_socktype = SOCK_STREAM;
2143                 else            /* EQ (protocol, Qudp) */
2144                         hints.ai_socktype = SOCK_DGRAM;
2145                 hints.ai_protocol = 0;
2146                 if (SYMBOLP(host) ) {
2147                         if (EQ(host,Qip_any)) {
2148                                 hints.ai_flags |= AI_PASSIVE;
2149                         } else if (!EQ(host,Qlocalhost)) {
2150                                 invalid_argument("invalid host ",host);
2151                         } else {
2152                                 /* If using localhost, not passing
2153                                    AI_PASSIVE will cause getaddrinfo
2154                                    to return a proper addr spec for
2155                                    listening only to local
2156                                    connections. */
2157                         }
2158                         retval = getaddrinfo(NULL, portstring, &hints, &res);
2159                 } else {
2160                         CHECK_STRING(host);
2161                         LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
2162                         retval = getaddrinfo(ext_host, portstring, &hints, &res);
2163                 }
2164                 if (retval != 0) {
2165                         char *gai_error_l;
2166
2167                         EXTERNAL_TO_C_STRING(gai_strerror(retval),
2168                                              gai_error_l, Qnative);
2169                         error("%s/%s %s", XSTRING_DATA(host), portstring,
2170                               gai_error_l);
2171                 }
2172
2173                 /* address loop */
2174                 for (lres = res; lres; lres = lres->ai_next) {
2175                         if (EQ(protocol, Qtcp))
2176                                 s = socket(lres->ai_family, SOCK_STREAM, 0);
2177                         else    /* EQ (protocol, Qudp) */
2178                                 s = socket(lres->ai_family, SOCK_DGRAM, 0);
2179
2180                         if (s < 0)
2181                                 continue;
2182
2183                         /* Turn off interrupts here -- see comments below.
2184                            There used to be code which called
2185                            bind_polling_period() to slow the polling period down
2186                            rather than turn it off, but that seems rather bogus
2187                            to me.  Best thing here is to use a non-blocking
2188                            connect or something, to check for QUIT. */
2189
2190                         /* Comments that are not quite valid: */
2191
2192                         /* Kernel bugs (on Ultrix at least) cause lossage (not
2193                            just EINTR) when connect is interrupted.  So let's
2194                            not let it get interrupted.  Note we do not turn off
2195                            polling, because polling is only used when not
2196                            interrupt_input, and thus not normally used on the
2197                            systems which have this bug.  On systems which use
2198                            polling, there's no way to quit if polling is turned
2199                            off.  */
2200
2201                         /* Slow down polling.  Some kernels have a bug which
2202                            causes retrying connect to fail after a connect.  */
2203
2204                         slow_down_interrupts();
2205
2206                       loop:
2207
2208                         /* A system call interrupted with a SIGALRM or SIGIO
2209                            comes back here, with can_break_system_calls reset to
2210                            0. */
2211                         SETJMP(break_system_call_jump);
2212                         if (QUITP) {
2213                                 speed_up_interrupts();
2214                                 REALLY_QUIT;
2215                                 /* In case something really weird happens ... */
2216                                 slow_down_interrupts();
2217                         }
2218
2219                         /* Break out of connect with a signal (it isn't
2220                            otherwise possible).  Thus you don't get screwed with
2221                            a hung network. */
2222                         can_break_system_calls = 1;
2223                         retval = bind(s, lres->ai_addr, lres->ai_addrlen);
2224                         if (retval >= 0 )
2225                                 retval = listen(s, listenQ); 
2226                         can_break_system_calls = 0;
2227                         if (retval == -1) {
2228                                 xerrno = errno;
2229                                 if (errno != EISCONN) {
2230                                         if (errno == EINTR)
2231                                                 goto loop;
2232                                         if (errno == EADDRINUSE && retry < 20) {
2233                                                 /* A delay here is needed on
2234                                                    some FreeBSD systems, and it
2235                                                    is harmless, since this
2236                                                    retrying takes time anyway
2237                                                    and should be infrequent.
2238                                                    `sleep-for' allowed for
2239                                                    quitting this loop with
2240                                                    interrupts slowed down so it
2241                                                    can't be used here.  Async
2242                                                    timers should already be
2243                                                    disabled at this point so we
2244                                                    can use `sleep'. */
2245                                                 retry++;
2246                                                 goto loop;
2247                                         }
2248                                 }
2249
2250                                 failed_connect = 1;
2251                                 close(s);
2252                                 s = -1;
2253
2254                                 speed_up_interrupts();
2255
2256                                 continue;
2257                         }
2258
2259                         if (port == 0) {
2260                                 int gni;
2261                                 char servbuf[NI_MAXSERV];
2262
2263                                 if (EQ(protocol, Qtcp))
2264                                         gni =
2265                                             getnameinfo(lres->ai_addr,
2266                                                         lres->ai_addrlen, NULL,
2267                                                         0, servbuf,
2268                                                         sizeof(servbuf),
2269                                                         NI_NUMERICSERV);
2270                                 else    /* EQ (protocol, Qudp) */
2271                                         gni =
2272                                             getnameinfo(lres->ai_addr,
2273                                                         lres->ai_addrlen, NULL,
2274                                                         0, servbuf,
2275                                                         sizeof(servbuf),
2276                                                         NI_NUMERICSERV |
2277                                                         NI_DGRAM);
2278
2279                                 if (gni == 0)
2280                                         port = strtol(servbuf, NULL, 10);
2281                         }
2282
2283                         break;
2284                 }               /* address loop */
2285
2286                 speed_up_interrupts();
2287
2288                 freeaddrinfo(res);
2289                 if (s < 0) {
2290                         errno = xerrno;
2291
2292                         if (failed_connect)
2293                                 report_file_error("bind failed",
2294                                                   list2(host, name));
2295                         else
2296                                 report_file_error("error creating socket",
2297                                                   list1(name));
2298                 }
2299 #else                           /* ! HAVE_GETADDRINFO */
2300                 struct sockaddr_in address;
2301
2302                 if (INTP(service))
2303                         port = htons((unsigned short)XINT(service));
2304                 else {
2305                         struct servent *svc_info;
2306                         CHECK_STRING(service);
2307
2308                         if (EQ(protocol, Qtcp))
2309                                 svc_info =
2310                                     getservbyname((char *)XSTRING_DATA(service),
2311                                                   "tcp");
2312                         else    /* EQ (protocol, Qudp) */
2313                                 svc_info =
2314                                     getservbyname((char *)XSTRING_DATA(service),
2315                                                   "udp");
2316
2317                         if (svc_info == 0)
2318                                 invalid_argument("Unknown service", service);
2319                         port = svc_info->s_port;
2320                 }
2321                 if (SYMBOLP(host)) {
2322                         if (EQ(host,Qip_any)) {
2323                                 address.sin_addr.s_host = htonl(INADDR_ANY);
2324                         } else if (EQ(host,Qlocalhost)) {
2325                                 address.sin_addr.s_host = htonl(INADDR_LOOPBACK);
2326                         } else {
2327                                 invalid_argument("invalid host ",host);
2328                         }
2329                 } else {
2330                         get_internet_address(host, &address, ERROR_ME);
2331                 }
2332                 address.sin_port = port;
2333
2334                 if (EQ(protocol, Qtcp))
2335                         s = socket(address.sin_family, SOCK_STREAM, 0);
2336                 else            /* EQ (protocol, Qudp) */
2337                         s = socket(address.sin_family, SOCK_DGRAM, 0);
2338
2339                 if (s < 0)
2340                         report_file_error("error creating socket", list1(name));
2341
2342                 /* Turn off interrupts here -- see comments below.  There used to
2343                    be code which called bind_polling_period() to slow the polling
2344                    period down rather than turn it off, but that seems rather
2345                    bogus to me.  Best thing here is to use a non-blocking connect
2346                    or something, to check for QUIT. */
2347
2348                 /* Comments that are not quite valid: */
2349
2350                 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2351                    when connect is interrupted.  So let's not let it get interrupted.
2352                    Note we do not turn off polling, because polling is only used
2353                    when not interrupt_input, and thus not normally used on the systems
2354                    which have this bug.  On systems which use polling, there's no way
2355                    to quit if polling is turned off.  */
2356
2357                 /* Slow down polling.  Some kernels have a bug which causes retrying
2358                    connect to fail after a connect.  */
2359
2360                 slow_down_interrupts();
2361
2362               loop:
2363
2364                 /* A system call interrupted with a SIGALRM or SIGIO comes back
2365                    here, with can_break_system_calls reset to 0. */
2366                 SETJMP(break_system_call_jump);
2367                 if (QUITP) {
2368                         speed_up_interrupts();
2369                         REALLY_QUIT;
2370                         /* In case something really weird happens ... */
2371                         slow_down_interrupts();
2372                 }
2373
2374                 /* Break out of connect with a signal (it isn't otherwise possible).
2375                    Thus you don't get screwed with a hung network. */
2376                 can_break_system_calls = 1;
2377                 retval =
2378                     bind(s, (struct sockaddr *)&address, sizeof(address));
2379                 if ( retval >= 0 ) 
2380                         listen( s, listenQ ); /* @@@ FIXME: This should be a parameter */
2381                 can_break_system_calls = 0;
2382                 if (retval == -1 && errno != EISCONN) {
2383                         int xerrno = errno;
2384                         if (errno == EINTR)
2385                                 goto loop;
2386                         if (errno == EADDRINUSE && retry < 20) {
2387                                 /* A delay here is needed on some FreeBSD
2388                                    systems, and it is harmless, since this
2389                                    retrying takes time anyway and should be
2390                                    infrequent.  `sleep-for' allowed for quitting
2391                                    this loop with interrupts slowed down so it
2392                                    can't be used here.  Async timers should
2393                                    already be disabled at this point so we can
2394                                    use `sleep'. */
2395                                 retry++;
2396                                 goto loop;
2397                         }
2398
2399                         close(s);
2400
2401                         speed_up_interrupts();
2402
2403                         errno = xerrno;
2404                         report_file_error("connection failed",
2405                                           list2(host, name));
2406                 }
2407
2408                 speed_up_interrupts();
2409 #endif                          /* ! HAVE_GETADDRINFO */
2410         }
2411
2412         inch = s;
2413         outch = dup(s);
2414         if (outch < 0) {
2415                 close(s);       /* this used to be leaked; from Kyle Jones */
2416                 report_file_error("error duplicating socket", list1(name));
2417         }
2418
2419         set_socket_nonblocking_maybe(inch, port, "tcp");
2420
2421         *vinfd = (void *)inch;
2422         *voutfd = (void *)outch;
2423 }
2424
2425
2426 #ifdef HAVE_MULTICAST
2427
2428 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
2429
2430    This function is similar to open-network-stream-internal, but provides a
2431    mean to open an UDP multicast connection instead of a TCP one. Like in the
2432    TCP case, the multicast connection will be seen as a sub-process,
2433
2434    Some notes:
2435    - Normally, we should use sendto and recvfrom with non connected
2436    sockets. The current code doesn't allow us to do this. In the future, it
2437    would be a good idea to extend the process data structure in order to deal
2438    properly with the different types network connections.
2439    - For the same reason, when leaving a multicast group, it is better to make
2440    a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
2441    Unfortunately, this can't be done here because delete_process doesn't know
2442    about the kind of connection we have. However, this is not such an
2443    important issue.
2444 */
2445
2446 static void
2447 unix_open_multicast_group(Lisp_Object name, Lisp_Object dest,
2448                           Lisp_Object port, Lisp_Object ttl, void **vinfd,
2449                           void **voutfd)
2450 {
2451         struct ip_mreq imr;
2452         struct sockaddr_in sa;
2453         struct protoent *udp;
2454         EMACS_INT ws, rs;
2455         int theport;
2456         unsigned char thettl;
2457         int one = 1;            /* For REUSEADDR */
2458         int ret;
2459         volatile int retry = 0;
2460
2461         CHECK_STRING(dest);
2462
2463         CHECK_NATNUM(port);
2464         theport = htons((unsigned short)XINT(port));
2465
2466         CHECK_NATNUM(ttl);
2467         thettl = (unsigned char)XINT(ttl);
2468
2469         if ((udp = getprotobyname("udp")) == NULL)
2470                 type_error(Qinvalid_operation,
2471                            "No info available for UDP protocol");
2472
2473         /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
2474         if ((rs = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
2475                 report_file_error("error creating socket", list1(name));
2476         if ((ws = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0) {
2477                 close(rs);
2478                 report_file_error("error creating socket", list1(name));
2479         }
2480
2481         /* This will be used for both sockets */
2482         memset(&sa, 0, sizeof(sa));
2483         sa.sin_family = AF_INET;
2484         sa.sin_port = theport;
2485         sa.sin_addr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2486
2487         /* Socket configuration for reading ------------------------ */
2488
2489         /* Multiple connections from the same machine. This must be done before
2490            bind. If it fails, it shouldn't be fatal. The only consequence is that
2491            people won't be able to connect twice from the same machine. */
2492         if (setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))
2493             < 0)
2494                 warn_when_safe(Qmulticast, Qwarning,
2495                                "Cannot reuse socket address");
2496
2497         /* bind socket name */
2498         if (bind(rs, (struct sockaddr *)&sa, sizeof(sa))) {
2499                 close(rs);
2500                 close(ws);
2501                 report_file_error("error binding socket", list2(name, port));
2502         }
2503
2504         /* join multicast group */
2505         imr.imr_multiaddr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2506         imr.imr_interface.s_addr = htonl(INADDR_ANY);
2507         if (setsockopt(rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2508                        &imr, sizeof(struct ip_mreq)) < 0) {
2509                 close(ws);
2510                 close(rs);
2511                 report_file_error("error adding membership", list2(name, dest));
2512         }
2513
2514         /* Socket configuration for writing ----------------------- */
2515
2516         /* Normally, there's no 'connect' in multicast, since we prefer to use
2517            'sendto' and 'recvfrom'. However, in order to handle this connection
2518            in the process-like way it is done for TCP, we must be able to use
2519            'write' instead of 'sendto'. Consequently, we 'connect' this
2520            socket. */
2521
2522         /* See open-network-stream-internal for comments on this part of the
2523            code */
2524         slow_down_interrupts();
2525
2526       loop:
2527
2528         /* A system call interrupted with a SIGALRM or SIGIO comes back
2529            here, with can_break_system_calls reset to 0. */
2530         SETJMP(break_system_call_jump);
2531         if (QUITP) {
2532                 speed_up_interrupts();
2533                 REALLY_QUIT;
2534                 /* In case something really weird happens ... */
2535                 slow_down_interrupts();
2536         }
2537
2538         /* Break out of connect with a signal (it isn't otherwise possible).
2539            Thus you don't get screwed with a hung network. */
2540         can_break_system_calls = 1;
2541         ret = connect(ws, (struct sockaddr *)&sa, sizeof(sa));
2542         can_break_system_calls = 0;
2543         if (ret == -1 && errno != EISCONN) {
2544                 int xerrno = errno;
2545
2546                 if (errno == EINTR)
2547                         goto loop;
2548                 if (errno == EADDRINUSE && retry < 20) {
2549                         /* A delay here is needed on some FreeBSD systems, and
2550                            it is harmless, since this retrying takes time anyway
2551                            and should be infrequent.  `sleep-for' allowed for
2552                            quitting this loop with interrupts slowed down so it
2553                            can't be used here.  Async timers should already be
2554                            disabled at this point so we can use `sleep'. */
2555                         retry++;
2556                         goto loop;
2557                 }
2558
2559                 close(rs);
2560                 close(ws);
2561                 speed_up_interrupts();
2562
2563                 errno = xerrno;
2564                 report_file_error("error connecting socket", list2(name, port));
2565         }
2566
2567         speed_up_interrupts();
2568
2569         /* scope */
2570         if (setsockopt(ws, IPPROTO_IP, IP_MULTICAST_TTL,
2571                        &thettl, sizeof(thettl)) < 0) {
2572                 close(rs);
2573                 close(ws);
2574                 report_file_error("error setting ttl", list2(name, ttl));
2575         }
2576
2577         set_socket_nonblocking_maybe(rs, theport, "udp");
2578
2579         *vinfd = (void *)rs;
2580         *voutfd = (void *)ws;
2581 }
2582
2583 #endif                          /* HAVE_MULTICAST */
2584
2585 #endif                          /* HAVE_SOCKETS */
2586 \f
2587 /**********************************************************************/
2588 /*                            Initialization                          */
2589 /**********************************************************************/
2590
2591 void process_type_create_unix(void)
2592 {
2593         PROCESS_HAS_METHOD(unix, alloc_process_data);
2594         PROCESS_HAS_METHOD(unix, mark_process_data);
2595 #ifdef SIGCHLD
2596         PROCESS_HAS_METHOD(unix, init_process);
2597         PROCESS_HAS_METHOD(unix, reap_exited_processes);
2598 #endif
2599         PROCESS_HAS_METHOD(unix, init_process_io_handles);
2600         PROCESS_HAS_METHOD(unix, create_process);
2601         PROCESS_HAS_METHOD(unix, set_window_size);
2602 #ifdef HAVE_WAITPID
2603         PROCESS_HAS_METHOD(unix, update_status_if_terminated);
2604 #endif
2605         PROCESS_HAS_METHOD(unix, send_process);
2606         PROCESS_HAS_METHOD(unix, process_send_eof);
2607         PROCESS_HAS_METHOD(unix, deactivate_process);
2608         PROCESS_HAS_METHOD(unix, kill_child_process);
2609         PROCESS_HAS_METHOD(unix, kill_process_by_pid);
2610         PROCESS_HAS_METHOD(unix, get_tty_name);
2611 #ifdef HAVE_SOCKETS
2612         PROCESS_HAS_METHOD(unix, canonicalize_host_name);
2613         PROCESS_HAS_METHOD(unix, open_network_stream);
2614         PROCESS_HAS_METHOD(unix, open_network_server_stream);
2615         PROCESS_HAS_METHOD(unix, network_server_accept);
2616         PROCESS_HAS_METHOD(unix, network_process_listener);
2617 #ifdef HAVE_MULTICAST
2618         PROCESS_HAS_METHOD(unix, open_multicast_group);
2619 #endif
2620 #endif
2621 }
2622
2623 void vars_of_process_unix(void)
2624 {
2625         Fprovide(intern("unix-processes"));
2626 }
2627
2628 #endif                          /* !defined (NO_SUBPROCESSES) */