XEmacs 21.2.8
[chise/xemacs-chise.git.1] / 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 XEmacs.
8
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING.  If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* This file has been Mule-ized except for `start-process-internal',
25    `open-network-stream-internal' and `open-multicast-group-internal'. */
26
27 /* This file has been split into process.c and process-unix.c by
28    Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
29    the original author(s) */
30
31 #include <config.h>
32
33 #if !defined (NO_SUBPROCESSES)
34
35 /* The entire file is within this conditional */
36
37 #include "lisp.h"
38
39 #include "buffer.h"
40 #include "events.h"
41 #include "frame.h"
42 #include "hash.h"
43 #include "lstream.h"
44 #include "opaque.h"
45 #include "process.h"
46 #include "procimpl.h"
47 #include "sysdep.h"
48 #include "window.h"
49 #ifdef FILE_CODING
50 #include "file-coding.h"
51 #endif
52
53 #include <setjmp.h>
54 #include "sysfile.h"
55 #include "sysproc.h"
56 #include "systime.h"
57 #include "syssignal.h" /* Always include before systty.h */
58 #include "systty.h"
59 #include "syswait.h"
60
61
62 /*
63  * Implementation-specific data. Pointed to by Lisp_Process->process_data
64  */
65
66 struct unix_process_data
67 {
68   /* Non-0 if this is really a ToolTalk channel. */
69   int connected_via_filedesc_p;
70   /* Descriptor by which we read from this process.  -1 for dead process */
71   int infd;
72   /* Descriptor for the tty which this process is using.
73      -1 if we didn't record it (on some systems, there's no need).  */
74   int subtty;
75   /* Name of subprocess terminal. */
76   Lisp_Object tty_name;
77   /* Non-false if communicating through a pty.  */
78   char pty_flag;
79 };
80
81 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
82
83 #ifdef HAVE_PTYS
84 /* The file name of the pty opened by allocate_pty.  */
85
86 static char pty_name[24];
87 #endif
88
89
90 \f
91 /**********************************************************************/
92 /*                    Static helper routines                          */
93 /**********************************************************************/
94
95 static SIGTYPE
96 close_safely_handler (int signo)
97 {
98   EMACS_REESTABLISH_SIGNAL (signo, close_safely_handler);
99   SIGRETURN;
100 }
101
102 static void
103 close_safely (int fd)
104 {
105   stop_interrupts ();
106   signal (SIGALRM, close_safely_handler);
107   alarm (1);
108   close (fd);
109   alarm (0);
110   start_interrupts ();
111 }
112
113 static void
114 close_descriptor_pair (int in, int out)
115 {
116   if (in >= 0)
117     close (in);
118   if (out != in && out >= 0)
119     close (out);
120 }
121
122 /* Close all descriptors currently in use for communication
123    with subprocess.  This is used in a newly-forked subprocess
124    to get rid of irrelevant descriptors.  */
125
126 static int
127 close_process_descs_mapfun (CONST void* key, void* contents, void* arg)
128 {
129   Lisp_Object proc;
130   CVOID_TO_LISP (proc, contents);
131   event_stream_delete_stream_pair (XPROCESS(proc)->pipe_instream,
132                                    XPROCESS(proc)->pipe_outstream);
133   return 0;
134 }
135
136 /* #### This function is currently called from child_setup
137    in callproc.c. It should become static though - kkm */
138 void
139 close_process_descs (void)
140 {
141   maphash (close_process_descs_mapfun, usid_to_process, 0);
142 }
143
144 /* connect to an existing file descriptor.  This is very similar to
145    open-network-stream except that it assumes that the connection has
146    already been initialized.  It is currently used for ToolTalk
147    communication. */
148
149 /* This function used to be visible on the Lisp level, but there is no
150    real point in doing that.  Here is the doc string:
151
152   "Connect to an existing file descriptor.\n\
153 Returns a subprocess-object to represent the connection.\n\
154 Input and output work as for subprocesses; `delete-process' closes it.\n\
155 Args are NAME BUFFER INFD OUTFD.\n\
156 NAME is name for process.  It is modified if necessary to make it unique.\n\
157 BUFFER is the buffer (or buffer-name) to associate with the process.\n\
158  Process output goes at end of that buffer, unless you specify\n\
159  an output stream or filter function to handle the output.\n\
160  BUFFER may be also nil, meaning that this process is not associated\n\
161  with any buffer\n\
162 INFD and OUTFD specify the file descriptors to use for input and\n\
163  output, respectively."
164 */
165
166 Lisp_Object
167 connect_to_file_descriptor (Lisp_Object name, Lisp_Object buffer,
168                             Lisp_Object infd, Lisp_Object outfd)
169 {
170   /* This function can GC */
171   Lisp_Object proc;
172   int inch;
173
174   CHECK_STRING (name);
175   CHECK_INT (infd);
176   CHECK_INT (outfd);
177
178   inch = XINT (infd);
179   if (get_process_from_usid (FD_TO_USID(inch)))
180     error ("There is already a process connected to fd %d", inch);
181   if (!NILP (buffer))
182     buffer = Fget_buffer_create (buffer);
183   proc = make_process_internal (name);
184
185   XPROCESS (proc)->pid = Fcons (infd, name);
186   XPROCESS (proc)->buffer = buffer;
187   init_process_io_handles (XPROCESS (proc), (void*)inch, (void*)XINT (outfd), 0);
188   UNIX_DATA (XPROCESS (proc))->connected_via_filedesc_p = 1;
189
190   event_stream_select_process (XPROCESS (proc));
191
192   return proc;
193 }
194
195 #ifdef HAVE_PTYS
196
197 /* Open an available pty, returning a file descriptor.
198    Return -1 on failure.
199    The file name of the terminal corresponding to the pty
200    is left in the variable pty_name.  */
201
202 static int
203 allocate_pty (void)
204 {
205 #ifndef PTY_OPEN
206   struct stat stb;
207
208   /* Some systems name their pseudoterminals so that there are gaps in
209      the usual sequence - for example, on HP9000/S700 systems, there
210      are no pseudoterminals with names ending in 'f'.  So we wait for
211      three failures in a row before deciding that we've reached the
212      end of the ptys.  */
213   int failed_count = 0;
214 #endif
215   int i;
216   int fd;
217   int c;
218
219 #ifdef PTY_ITERATION
220   PTY_ITERATION
221 #else
222   for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
223     for (i = 0; i < 16; i++)
224 #endif
225       {
226 #ifdef PTY_NAME_SPRINTF
227         PTY_NAME_SPRINTF
228 #else
229         sprintf (pty_name, "/dev/pty%c%x", c, i);
230 #endif /* no PTY_NAME_SPRINTF */
231
232 #ifdef PTY_OPEN
233         PTY_OPEN;
234 #else /* no PTY_OPEN */
235 #ifdef IRIS
236         /* Unusual IRIS code */
237         *ptyv = open ("/dev/ptc", O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
238         if (fd < 0)
239           return -1;
240         if (fstat (fd, &stb) < 0)
241           return -1;
242 #else /* not IRIS */
243         if (stat (pty_name, &stb) < 0)
244           {
245             failed_count++;
246             if (failed_count >= 3)
247               return -1;
248           }
249         else
250           failed_count = 0;
251         fd = open (pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
252 #endif /* not IRIS */
253 #endif /* no PTY_OPEN */
254
255         if (fd >= 0)
256           {
257             /* check to make certain that both sides are available
258                this avoids a nasty yet stupid bug in rlogins */
259 #ifdef PTY_TTY_NAME_SPRINTF
260             PTY_TTY_NAME_SPRINTF
261 #else
262             sprintf (pty_name, "/dev/tty%c%x", c, i);
263 #endif /* no PTY_TTY_NAME_SPRINTF */
264 #ifndef UNIPLUS
265             if (access (pty_name, 6) != 0)
266               {
267                 close (fd);
268 #if !defined(IRIS) && !defined(__sgi)
269                 continue;
270 #else
271                 return -1;
272 #endif /* IRIS */
273               }
274 #endif /* not UNIPLUS */
275             setup_pty (fd);
276             return fd;
277           }
278       }
279   return -1;
280 }
281 #endif /* HAVE_PTYS */
282
283 static int
284 create_bidirectional_pipe (int *inchannel, int *outchannel,
285                            volatile int *forkin, volatile int *forkout)
286 {
287   int sv[2];
288
289 #ifdef SKTPAIR
290   if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
291     return -1;
292   *outchannel = *inchannel = sv[0];
293   *forkout = *forkin = sv[1];
294 #else /* not SKTPAIR */
295   int temp;
296   temp = pipe (sv);
297   if (temp < 0) return -1;
298   *inchannel = sv[0];
299   *forkout = sv[1];
300   temp = pipe (sv);
301   if (temp < 0) return -1;
302   *outchannel = sv[1];
303   *forkin = sv[0];
304 #endif /* not SKTPAIR */
305   return 0;
306 }
307
308
309 #ifdef HAVE_SOCKETS
310
311 static int
312 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
313                       Error_behavior errb)
314 {
315   struct hostent *host_info_ptr = NULL;
316 #ifdef TRY_AGAIN
317   int count = 0;
318 #endif
319
320   xzero (*address);
321
322   while (1)
323     {
324 #ifdef TRY_AGAIN
325       if (count++ > 10) break;
326 #ifndef BROKEN_CYGWIN
327       h_errno = 0;
328 #endif
329 #endif
330       /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
331       slow_down_interrupts ();
332       host_info_ptr = gethostbyname ((char *) XSTRING_DATA (host));
333       speed_up_interrupts ();
334 #ifdef TRY_AGAIN
335       if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
336 #endif
337         break;
338       Fsleep_for (make_int (1));
339     }
340   if (host_info_ptr)
341     {
342       address->sin_family = host_info_ptr->h_addrtype;
343       memcpy (&address->sin_addr, host_info_ptr->h_addr, host_info_ptr->h_length);
344     }
345   else
346     {
347       IN_ADDR numeric_addr;
348       /* Attempt to interpret host as numeric inet address */
349       numeric_addr = inet_addr ((char *) XSTRING_DATA (host));
350       if (NUMERIC_ADDR_ERROR)
351         {
352           maybe_error (Qprocess, errb,
353                        "Unknown host \"%s\"", XSTRING_DATA (host));
354           return 0;
355         }
356
357       /* There was some broken code here that called strlen() here
358          on (char *) &numeric_addr and even sometimes accessed
359          uninitialized data. */
360       address->sin_family = AF_INET;
361       * (IN_ADDR *) &address->sin_addr = numeric_addr;
362     }
363
364   return 1;
365 }
366
367 static void
368 set_socket_nonblocking_maybe (int fd, int port, CONST char* proto)
369 {
370 #ifdef PROCESS_IO_BLOCKING
371   Lisp_Object tail;
372
373   for (tail = network_stream_blocking_port_list; CONSP (tail); tail = XCDR (tail))
374     {
375       Lisp_Object tail_port = XCAR (tail);
376
377       if (STRINGP (tail_port))
378         {
379           struct servent *svc_info;
380           CHECK_STRING (tail_port);
381           svc_info = getservbyname ((char *) XSTRING_DATA (tail_port), proto);
382           if ((svc_info != 0) && (svc_info->s_port == port))
383             break;
384           else
385             continue;
386         }
387       else if ((INTP (tail_port)) && (htons ((unsigned short) XINT (tail_port)) == port))
388         break;
389     }
390
391   if (!CONSP (tail))
392     {
393       set_descriptor_non_blocking (fd);
394     }
395 #else
396   set_descriptor_non_blocking (fd);
397 #endif  /* PROCESS_IO_BLOCKING */
398 }
399
400 #endif /* HAVE_SOCKETS */
401
402 /* Compute the Lisp form of the process status from
403    the numeric status that was returned by `wait'.  */
404
405 static void
406 update_status_from_wait_code (struct Lisp_Process *p, int *w_fmh)
407 {
408   /* C compiler lossage when attempting to pass w directly */
409   int w = *w_fmh;
410
411   if (WIFSTOPPED (w))
412     {
413       p->status_symbol = Qstop;
414       p->exit_code = WSTOPSIG (w);
415       p->core_dumped = 0;
416     }
417   else if (WIFEXITED (w))
418     {
419       p->status_symbol = Qexit;
420       p->exit_code = WEXITSTATUS (w);
421       p->core_dumped = 0;
422     }
423   else if (WIFSIGNALED (w))
424     {
425       p->status_symbol = Qsignal;
426       p->exit_code = WTERMSIG (w);
427       p->core_dumped = WCOREDUMP (w);
428     }
429   else
430     {
431       p->status_symbol = Qrun;
432       p->exit_code = 0;
433     }
434 }
435
436 #ifdef SIGCHLD
437
438 #define MAX_EXITED_PROCESSES 1000
439 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
440 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
441 static volatile int exited_processes_index;
442
443 static volatile int sigchld_happened;
444
445 /* On receipt of a signal that a child status has changed,
446  loop asking about children with changed statuses until
447  the system says there are no more.  All we do is record
448  the processes and wait status.
449
450  This function could be called from within the SIGCHLD
451  handler, so it must be completely reentrant.  When
452  not called from a SIGCHLD handler, BLOCK_SIGCHLD should
453  be non-zero so that SIGCHLD is blocked while this
454  function is running. (This is necessary so avoid
455  race conditions with the SIGCHLD_HAPPENED flag). */
456
457 static void
458 record_exited_processes (int block_sigchld)
459 {
460   if (!sigchld_happened)
461     {
462       return;
463     }
464
465 #ifdef EMACS_BLOCK_SIGNAL
466   if (block_sigchld)
467     EMACS_BLOCK_SIGNAL (SIGCHLD);
468 #endif
469
470   while (sigchld_happened)
471     {
472       int pid;
473       int w;
474
475       /* Keep trying to get a status until we get a definitive result.  */
476       do
477         {
478           errno = 0;
479 #ifdef WNOHANG
480 #  ifndef WUNTRACED
481 #    define WUNTRACED 0
482 #  endif /* not WUNTRACED */
483 #  ifdef HAVE_WAITPID
484           pid = waitpid ((pid_t) -1, &w, WNOHANG | WUNTRACED);
485 #  else
486           pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
487 #  endif
488 #else /* not WNOHANG */
489           pid = wait (&w);
490 #endif /* not WNOHANG */
491         }
492       while (pid <= 0 && errno == EINTR);
493
494       if (pid <= 0)
495         break;
496
497       if (exited_processes_index < MAX_EXITED_PROCESSES)
498         {
499           exited_processes[exited_processes_index] = pid;
500           exited_processes_status[exited_processes_index] = w;
501           exited_processes_index++;
502         }
503
504       /* On systems with WNOHANG, we just ignore the number
505          of times that SIGCHLD was signalled, and keep looping
506          until there are no more processes to wait on.  If we
507          don't have WNOHANG, we have to rely on the count in
508          SIGCHLD_HAPPENED. */
509 #ifndef WNOHANG
510       sigchld_happened--;
511 #endif /* not WNOHANG */
512     }
513
514   sigchld_happened = 0;
515
516   if (block_sigchld)
517     EMACS_UNBLOCK_SIGNAL (SIGCHLD);
518 }
519
520 /* For any processes that have changed status and are recorded
521    and such, update the corresponding struct Lisp_Process.
522    We separate this from record_exited_processes() so that
523    we never have to call this function from within a signal
524    handler.  We block SIGCHLD in case record_exited_processes()
525    is called from a signal handler. */
526
527 /** USG WARNING:  Although it is not obvious from the documentation
528  in signal(2), on a USG system the SIGCLD handler MUST NOT call
529  signal() before executing at least one wait(), otherwise the handler
530  will be called again, resulting in an infinite loop.  The relevant
531  portion of the documentation reads "SIGCLD signals will be queued
532  and the signal-catching function will be continually reentered until
533  the queue is empty".  Invoking signal() causes the kernel to reexamine
534  the SIGCLD queue.   Fred Fish, UniSoft Systems Inc.
535
536  (Note that now this only applies in SYS V Release 2 and before.
537  On SYS V Release 3, we use sigset() to set the signal handler for
538  the first time, and so we don't have to reestablish the signal handler
539  in the handler below.  On SYS V Release 4, we don't get this weirdo
540  behavior when we use sigaction(), which we do use.) */
541
542 static SIGTYPE
543 sigchld_handler (int signo)
544 {
545 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
546   int old_errno = errno;
547
548   sigchld_happened++;
549   record_exited_processes (0);
550   errno = old_errno;
551 #else
552   sigchld_happened++;
553 #endif
554 #ifdef HAVE_UNIXOID_EVENT_LOOP
555   signal_fake_event ();
556 #endif
557   /* WARNING - must come after wait3() for USG systems */
558   EMACS_REESTABLISH_SIGNAL (signo, sigchld_handler);
559   SIGRETURN;
560 }
561
562 #endif /* SIGCHLD */
563
564 #ifdef SIGNALS_VIA_CHARACTERS
565 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
566
567 static int
568 process_signal_char (int tty_fd, int signo)
569 {
570   /* If it's not a tty, pray that these default values work */
571   if (!isatty(tty_fd)) {
572 #define CNTL(ch) (037 & (ch))
573     switch (signo)
574       {
575       case SIGINT:  return CNTL('C');
576       case SIGQUIT: return CNTL('\\');
577 #ifdef SIGTSTP
578       case SIGTSTP: return CNTL('Z');
579 #endif
580       }
581   }
582
583 #ifdef HAVE_TERMIOS
584   /* TERMIOS is the latest and bestest, and seems most likely to work.
585      If the system has it, use it. */
586   {
587     struct termios t;
588     tcgetattr (tty_fd, &t);
589     switch (signo)
590       {
591       case SIGINT:  return t.c_cc[VINTR];
592       case SIGQUIT: return t.c_cc[VQUIT];
593 #if defined(SIGTSTP) && defined(VSUSP)
594       case SIGTSTP: return t.c_cc[VSUSP];
595 #endif
596       }
597   }
598
599 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
600   {
601     /* On Berkeley descendants, the following IOCTL's retrieve the
602        current control characters.  */
603     struct tchars c;
604     struct ltchars lc;
605     switch (signo)
606       {
607       case SIGINT:  ioctl (tty_fd, TIOCGETC, &c);  return c.t_intrc;
608       case SIGQUIT: ioctl (tty_fd, TIOCGETC, &c);  return c.t_quitc;
609 #  ifdef SIGTSTP
610       case SIGTSTP: ioctl (tty_fd, TIOCGLTC, &lc); return lc.t_suspc;
611 #  endif /* SIGTSTP */
612       }
613   }
614
615 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
616   {
617     /* On SYSV descendants, the TCGETA ioctl retrieves the current
618        control characters.  */
619     struct termio t;
620     ioctl (tty_fd, TCGETA, &t);
621     switch (signo) {
622     case SIGINT:  return t.c_cc[VINTR];
623     case SIGQUIT: return t.c_cc[VQUIT];
624 #  ifdef SIGTSTP
625     case SIGTSTP: return t.c_cc[VSWTCH];
626 #  endif /* SIGTSTP */
627     }
628   }
629 # else /* ! defined (TCGETA) */
630 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
631   /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
632      you'd better be using one of the alternatives above!  */
633 # endif /* ! defined (TCGETA) */
634   return '\0';
635 }
636 #endif /* SIGNALS_VIA_CHARACTERS */
637
638
639
640 \f
641 /**********************************************************************/
642 /*              Process implementation methods                        */
643 /**********************************************************************/
644
645 /*
646  * Allocate and initialize Lisp_Process->process_data
647  */
648
649 static void
650 unix_alloc_process_data (struct Lisp_Process *p)
651 {
652   p->process_data = xnew (struct unix_process_data);
653
654   UNIX_DATA(p)->connected_via_filedesc_p = 0;
655   UNIX_DATA(p)->infd   = -1;
656   UNIX_DATA(p)->subtty = -1;
657   UNIX_DATA(p)->tty_name = Qnil;
658   UNIX_DATA(p)->pty_flag = 0;
659 }
660
661 /*
662  * Mark any Lisp objects in Lisp_Process->process_data
663  */
664
665 static void
666 unix_mark_process_data (struct Lisp_Process *proc,
667                         void (*markobj) (Lisp_Object))
668 {
669   markobj (UNIX_DATA(proc)->tty_name);
670 }
671
672 /*
673  * Initialize XEmacs process implementation once
674  */
675
676 #ifdef SIGCHLD
677 static void
678 unix_init_process (void)
679 {
680 #ifndef CANNOT_DUMP
681   if (! noninteractive || initialized)
682 #endif
683     signal (SIGCHLD, sigchld_handler);
684 }
685 #endif /* SIGCHLD */
686
687 /*
688  * Initialize any process local data. This is called when newly
689  * created process is connected to real OS file handles. The
690  * handles are generally represented by void* type, but are
691  * of type int (file descriptors) for UNIX
692  */
693
694 static void
695 unix_init_process_io_handles (struct Lisp_Process *p, void* in, void* out, int flags)
696 {
697   UNIX_DATA(p)->infd = (int)in;
698 }
699
700 /*
701  * Fork off a subprocess. P is a pointer to a newly created subprocess
702  * object. If this function signals, the caller is responsible for
703  * deleting (and finalizing) the process object.
704  *
705  * The method must return PID of the new process, a (positive??? ####) number
706  * which fits into Lisp_Int. No return value indicates an error, the method
707  * must signal an error instead.
708  */
709
710 static int
711 unix_create_process (struct Lisp_Process *p,
712                      Lisp_Object *argv, int nargv,
713                      Lisp_Object program, Lisp_Object cur_dir)
714 {
715   /* This function rewritten by ben@xemacs.org. */
716
717   int pid;
718   int inchannel  = -1;
719   int outchannel = -1;
720   /* Use volatile to protect variables from being clobbered by longjmp.  */
721   volatile int forkin   = -1;
722   volatile int forkout  = -1;
723   volatile int pty_flag = 0;
724
725 #ifdef HAVE_PTYS
726   if (!NILP (Vprocess_connection_type))
727     {
728       /* find a new pty, open the master side, return the opened
729          file handle, and store the name of the corresponding slave
730          side in global variable pty_name. */
731       outchannel = inchannel = allocate_pty ();
732     }
733
734   if (inchannel >= 0)
735     {
736       /* You're "supposed" to now open the slave in the child.
737          On some systems, we can open it here; this allows for
738          better error checking. */
739 #if !defined(USG)
740       /* On USG systems it does not work to open the pty's tty here
741          and then close and reopen it in the child.  */
742 #ifdef O_NOCTTY
743       /* Don't let this terminal become our controlling terminal
744          (in case we don't have one).  */
745       forkout = forkin = open (pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
746 #else
747       forkout = forkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
748 #endif
749       if (forkin < 0)
750         goto io_failure;
751 #endif /* not USG */
752       UNIX_DATA(p)->pty_flag = pty_flag = 1;
753     }
754   else
755 #endif /* HAVE_PTYS */
756     if (create_bidirectional_pipe (&inchannel, &outchannel,
757                                    &forkin, &forkout) < 0)
758       goto io_failure;
759
760 #if 0
761   /* Replaced by close_process_descs */
762   set_exclusive_use (inchannel);
763   set_exclusive_use (outchannel);
764 #endif
765
766   set_descriptor_non_blocking (inchannel);
767
768   /* Record this as an active process, with its channels.
769      As a result, child_setup will close Emacs's side of the pipes.  */
770   init_process_io_handles (p, (void*)inchannel, (void*)outchannel,
771                            pty_flag ? STREAM_PTY_FLUSHING : 0);
772   /* Record the tty descriptor used in the subprocess.  */
773   UNIX_DATA(p)->subtty = forkin;
774
775   {
776 #if !defined(__CYGWIN32__)
777     /* child_setup must clobber environ on systems with true vfork.
778        Protect it from permanent change.  */
779     char **save_environ = environ;
780 #endif
781
782     pid = fork ();
783     if (pid == 0)
784       {
785         /**** Now we're in the child process ****/
786         int xforkin = forkin;
787         int xforkout = forkout;
788
789         if (!pty_flag)
790           EMACS_SEPARATE_PROCESS_GROUP ();
791 #ifdef HAVE_PTYS
792         else
793           {
794             /* Disconnect the current controlling terminal, pursuant to
795                making the pty be the controlling terminal of the process.
796                Also put us in our own process group. */
797
798             disconnect_controlling_terminal ();
799
800             /* Open the pty connection and make the pty's terminal
801                our controlling terminal.
802
803                On systems with TIOCSCTTY, we just use it to set
804                the controlling terminal.  On other systems, the
805                first TTY we open becomes the controlling terminal.
806                So, we end up with four possibilities:
807
808                (1) on USG and TIOCSCTTY systems, we open the pty
809                    and use TIOCSCTTY.
810                (2) on other USG systems, we just open the pty.
811                (3) on non-USG systems with TIOCSCTTY, we
812                    just use TIOCSCTTY. (On non-USG systems, we
813                    already opened the pty in the parent process.)
814                (4) on non-USG systems without TIOCSCTTY, we
815                    close the pty and reopen it.
816
817                This would be cleaner if we didn't open the pty
818                in the parent process, but doing it that way
819                makes it possible to trap error conditions.
820                It's harder to convey an error from the child
821                process, and I don't feel like messing with
822                this now. */
823
824             /* There was some weirdo, probably wrong,
825                conditionalization on RTU and UNIPLUS here.
826                I deleted it.  So sue me. */
827
828             /* SunOS has TIOCSCTTY but the close/open method
829                also works. */
830
831 #  if defined (USG) || !defined (TIOCSCTTY)
832             /* Now close the pty (if we had it open) and reopen it.
833                This makes the pty the controlling terminal of the
834                subprocess.  */
835             /* I wonder if close (open (pty_name, ...)) would work?  */
836             if (xforkin >= 0)
837               close (xforkin);
838             xforkout = xforkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
839             if (xforkin < 0)
840               {
841                 write (1, "Couldn't open the pty terminal ", 31);
842                 write (1, pty_name, strlen (pty_name));
843                 write (1, "\n", 1);
844                 _exit (1);
845               }
846 #  endif /* USG or not TIOCSCTTY */
847
848             /* Miscellaneous setup required for some systems.
849                Must be done before using tc* functions on xforkin.
850                This guarantees that isatty(xforkin) is true. */
851
852 # ifdef SETUP_SLAVE_PTY
853             SETUP_SLAVE_PTY;
854 # endif /* SETUP_SLAVE_PTY */
855
856 #  ifdef TIOCSCTTY
857             /* We ignore the return value
858                because faith@cs.unc.edu says that is necessary on Linux.  */
859             assert (isatty (xforkin));
860             ioctl (xforkin, TIOCSCTTY, 0);
861 #  endif /* TIOCSCTTY */
862
863             /* Change the line discipline. */
864
865 # if defined (HAVE_TERMIOS) && defined (LDISC1)
866             {
867               struct termios t;
868               assert (isatty (xforkin));
869               tcgetattr (xforkin, &t);
870               t.c_lflag = LDISC1;
871               if (tcsetattr (xforkin, TCSANOW, &t) < 0)
872                 perror ("create_process/tcsetattr LDISC1 failed\n");
873             }
874 # elif defined (NTTYDISC) && defined (TIOCSETD)
875             {
876               /* Use new line discipline.  TIOCSETD is accepted and
877                  ignored on Sys5.4 systems with ttcompat. */
878               int ldisc = NTTYDISC;
879               assert (isatty (xforkin));
880               ioctl (xforkin, TIOCSETD, &ldisc);
881             }
882 # endif /* TIOCSETD & NTTYDISC */
883
884             /* Make our process group be the foreground group
885                of our new controlling terminal. */
886
887             {
888               int piddly = EMACS_GET_PROCESS_GROUP ();
889               EMACS_SET_TTY_PROCESS_GROUP (xforkin, &piddly);
890             }
891
892             /* On AIX, we've disabled SIGHUP above once we start a
893                child on a pty.  Now reenable it in the child, so it
894                will die when we want it to.
895                JV: This needs to be done ALWAYS as we might have inherited
896                a SIG_IGN handling from our parent (nohup) and we are in new
897                process group.
898             */
899             signal (SIGHUP, SIG_DFL);
900           }
901
902         if (pty_flag)
903           /* Set up the terminal characteristics of the pty. */
904           child_setup_tty (xforkout);
905
906 #endif /* HAVE_PTYS */
907
908         signal (SIGINT,  SIG_DFL);
909         signal (SIGQUIT, SIG_DFL);
910
911         {
912           char *current_dir;
913           char **new_argv = alloca_array (char *, nargv + 2);
914           int i;
915
916           /* Nothing below here GCs so our string pointers shouldn't move. */
917           new_argv[0] = (char *) XSTRING_DATA (program);
918           for (i = 0; i < nargv; i++)
919             {
920               CHECK_STRING (argv[i]);
921               new_argv[i + 1] = (char *) XSTRING_DATA (argv[i]);
922             }
923           new_argv[i + 1] = 0;
924
925           GET_C_STRING_FILENAME_DATA_ALLOCA (cur_dir, current_dir);
926
927           child_setup (xforkin, xforkout, xforkout, new_argv, current_dir);
928         }
929
930       } /**** End of child code ****/
931
932     /**** Back in parent process ****/
933 #if !defined(__CYGWIN32__)
934     environ = save_environ;
935 #endif
936   }
937
938   if (pid < 0)
939     {
940       close_descriptor_pair (forkin, forkout);
941       report_file_error ("Doing fork", Qnil);
942     }
943
944   /* #### dmoore - why is this commented out, otherwise we leave
945      subtty = forkin, but then we close forkin just below. */
946   /* UNIX_DATA(p)->subtty = -1; */
947
948   /* If the subfork execv fails, and it exits,
949      this close hangs.  I don't know why.
950      So have an interrupt jar it loose.  */
951   if (forkin >= 0)
952     close_safely (forkin);
953   if (forkin != forkout && forkout >= 0)
954     close (forkout);
955
956 #ifdef HAVE_PTYS
957   if (pty_flag)
958     UNIX_DATA (p)->tty_name = build_string (pty_name);
959   else
960 #endif
961     UNIX_DATA (p)->tty_name = Qnil;
962
963   /* Notice that SIGCHLD was not blocked. (This is not possible on
964      some systems.) No biggie if SIGCHLD occurs right around the
965      time that this call happens, because SIGCHLD() does not actually
966      deselect the process (that doesn't occur until the next time
967      we're waiting for an event, when status_notify() is called). */
968   return pid;
969
970 io_failure:
971   {
972     int save_errno = errno;
973     close_descriptor_pair (forkin, forkout);
974     close_descriptor_pair (inchannel, outchannel);
975     errno = save_errno;
976     report_file_error ("Opening pty or pipe", Qnil);
977     return 0; /* not reached */
978   }
979 }
980
981 /* Return nonzero if this process is a ToolTalk connection. */
982
983 static int
984 unix_tooltalk_connection_p (struct Lisp_Process *p)
985 {
986   return UNIX_DATA(p)->connected_via_filedesc_p;
987 }
988
989 /* This is called to set process' virtual terminal size */
990
991 static int
992 unix_set_window_size (struct Lisp_Process* p, int cols, int rows)
993 {
994   return set_window_size (UNIX_DATA(p)->infd, cols, rows);
995 }
996
997 /*
998  * This method is called to update status fields of the process
999  * structure. If the process has not existed, this method is
1000  * expected to do nothing.
1001  *
1002  * The method is called only for real child processes.
1003  */
1004
1005 #ifdef HAVE_WAITPID
1006 static void
1007 unix_update_status_if_terminated (struct Lisp_Process* p)
1008 {
1009   int w;
1010 #ifdef SIGCHLD
1011   EMACS_BLOCK_SIGNAL (SIGCHLD);
1012 #endif
1013   if (waitpid (XINT (p->pid), &w, WNOHANG) == XINT (p->pid))
1014     {
1015       p->tick++;
1016       update_status_from_wait_code (p, &w);
1017     }
1018 #ifdef SIGCHLD
1019   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1020 #endif
1021 }
1022 #endif
1023
1024 /*
1025  * Update status of all exited processes. Called when SIGCLD has signaled.
1026  */
1027
1028 #ifdef SIGCHLD
1029 static void
1030 unix_reap_exited_processes (void)
1031 {
1032   int i;
1033   struct Lisp_Process *p;
1034
1035 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1036   record_exited_processes (1);
1037 #endif
1038
1039   if (exited_processes_index <= 0)
1040     {
1041       return;
1042     }
1043
1044 #ifdef  EMACS_BLOCK_SIGNAL
1045   EMACS_BLOCK_SIGNAL (SIGCHLD);
1046 #endif
1047   for (i = 0; i < exited_processes_index; i++)
1048     {
1049       int pid = exited_processes[i];
1050       int w = exited_processes_status[i];
1051
1052       /* Find the process that signaled us, and record its status.  */
1053
1054       p = 0;
1055       {
1056         Lisp_Object tail;
1057         LIST_LOOP (tail, Vprocess_list)
1058           {
1059             Lisp_Object proc = XCAR (tail);
1060             p = XPROCESS (proc);
1061             if (INTP (p->pid) && XINT (p->pid) == pid)
1062               break;
1063             p = 0;
1064           }
1065       }
1066
1067       if (p)
1068         {
1069           /* Change the status of the process that was found.  */
1070           p->tick++;
1071           process_tick++;
1072           update_status_from_wait_code (p, &w);
1073
1074           /* If process has terminated, stop waiting for its output.  */
1075           if (WIFSIGNALED (w) || WIFEXITED (w))
1076             {
1077               if (!NILP(p->pipe_instream))
1078                 {
1079                   /* We can't just call event_stream->unselect_process_cb (p)
1080                      here, because that calls XtRemoveInput, which is not
1081                      necessarily reentrant, so we can't call this at interrupt
1082                      level.
1083                    */
1084                 }
1085             }
1086         }
1087       else
1088         {
1089           /* There was no asynchronous process found for that id.  Check
1090              if we have a synchronous process. Only set sync process status
1091              if there is one, so we work OK with the waitpid() call in
1092              wait_for_termination(). */
1093           if (synch_process_alive != 0)
1094             { /* Set the global sync process status variables. */
1095               synch_process_alive = 0;
1096
1097               /* Report the status of the synchronous process.  */
1098               if (WIFEXITED (w))
1099                 synch_process_retcode = WEXITSTATUS (w);
1100               else if (WIFSIGNALED (w))
1101                 synch_process_death = signal_name (WTERMSIG (w));
1102             }
1103         }
1104     }
1105
1106   exited_processes_index = 0;
1107
1108   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1109 }
1110 #endif /* SIGCHLD */
1111
1112 /*
1113  * Stuff the entire contents of LSTREAM to the process output pipe
1114  */
1115
1116 static JMP_BUF send_process_frame;
1117
1118 static SIGTYPE
1119 send_process_trap (int signum)
1120 {
1121   EMACS_REESTABLISH_SIGNAL (signum, send_process_trap);
1122   EMACS_UNBLOCK_SIGNAL (signum);
1123   LONGJMP (send_process_frame, 1);
1124 }
1125
1126 static void
1127 unix_send_process (Lisp_Object proc, struct lstream* lstream)
1128 {
1129   /* Use volatile to protect variables from being clobbered by longjmp.  */
1130   SIGTYPE (*volatile old_sigpipe) (int) = 0;
1131   volatile Lisp_Object vol_proc = proc;
1132   struct Lisp_Process *volatile p = XPROCESS (proc);
1133
1134   if (!SETJMP (send_process_frame))
1135     {
1136       /* use a reasonable-sized buffer (somewhere around the size of the
1137          stream buffer) so as to avoid inundating the stream with blocked
1138          data. */
1139       Bufbyte chunkbuf[512];
1140       Bytecount chunklen;
1141
1142       while (1)
1143         {
1144           int writeret;
1145
1146           chunklen = Lstream_read (lstream, chunkbuf, 512);
1147           if (chunklen <= 0)
1148             break; /* perhaps should abort() if < 0?
1149                       This should never happen. */
1150           old_sigpipe =
1151             (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1152           /* Lstream_write() will never successfully write less than
1153              the amount sent in.  In the worst case, it just buffers
1154              the unwritten data. */
1155           writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
1156                                     chunklen);
1157           signal (SIGPIPE, old_sigpipe);
1158           if (writeret < 0)
1159             /* This is a real error.  Blocking errors are handled
1160                specially inside of the filedesc stream. */
1161             report_file_error ("writing to process", list1 (proc));
1162           while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
1163             {
1164               /* Buffer is full.  Wait, accepting input;
1165                  that may allow the program
1166                  to finish doing output and read more.  */
1167               Faccept_process_output (Qnil, make_int (1), Qnil);
1168               old_sigpipe =
1169                 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1170               Lstream_flush (XLSTREAM (p->pipe_outstream));
1171               signal (SIGPIPE, old_sigpipe);
1172             }
1173         }
1174     }
1175   else
1176     { /* We got here from a longjmp() from the SIGPIPE handler */
1177       signal (SIGPIPE, old_sigpipe);
1178       /* Close the file lstream so we don't attempt to write to it further */
1179       /* #### There is controversy over whether this might cause fd leakage */
1180       /*      my tests say no. -slb */
1181       XLSTREAM (p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1182       p->status_symbol = Qexit;
1183       p->exit_code = 256; /* #### SIGPIPE ??? */
1184       p->core_dumped = 0;
1185       p->tick++;
1186       process_tick++;
1187       deactivate_process (*((Lisp_Object *) (&vol_proc)));
1188       error ("SIGPIPE raised on process %s; closed it",
1189              XSTRING_DATA (p->name));
1190     }
1191
1192   old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1193   Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1194   signal (SIGPIPE, old_sigpipe);
1195 }
1196
1197 /*
1198  * Send EOF to the process. The default implementation simply
1199  * closes the output stream. The method must return 0 to call
1200  * the default implementation, or 1 if it has taken all care about
1201  * sending EOF to the process.
1202  */
1203
1204 static int
1205 unix_process_send_eof (Lisp_Object proc)
1206 {
1207   if (!UNIX_DATA (XPROCESS (proc))->pty_flag)
1208     return 0;
1209
1210   /* #### get_eof_char simply doesn't return the correct character
1211      here.  Maybe it is needed to determine the right eof
1212      character in init_process_io_handles but here it simply screws
1213      things up. */
1214 #if 0
1215   Bufbyte eof_char = get_eof_char (XPROCESS (proc));
1216   send_process (proc, Qnil, &eof_char, 0, 1);
1217 #else
1218   send_process (proc, Qnil, (CONST Bufbyte *) "\004", 0, 1);
1219 #endif
1220   return 1;
1221 }
1222
1223 /*
1224  * Called before the process is deactivated. The process object
1225  * is not immediately finalized, just undergoes a transition to
1226  * inactive state.
1227  *
1228  * The return value is a unique stream ID, as returned by
1229  * event_stream_delete_stream_pair
1230  *
1231  * In the lack of this method, only event_stream_delete_stream_pair
1232  * is called on both I/O streams of the process.
1233  *
1234  * The UNIX version guards this by ignoring possible SIGPIPE.
1235  */
1236
1237 static USID
1238 unix_deactivate_process (struct Lisp_Process *p)
1239 {
1240   SIGTYPE (*old_sigpipe) (int) = 0;
1241   USID usid;
1242
1243   if (UNIX_DATA(p)->infd >= 0)
1244     flush_pending_output (UNIX_DATA(p)->infd);
1245
1246   /* closing the outstream could result in SIGPIPE, so ignore it. */
1247   old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, SIG_IGN);
1248   usid = event_stream_delete_stream_pair (p->pipe_instream, p->pipe_outstream);
1249   signal (SIGPIPE, old_sigpipe);
1250
1251   UNIX_DATA(p)->infd  = -1;
1252
1253   return usid;
1254 }
1255
1256 /* send a signal number SIGNO to PROCESS.
1257    CURRENT_GROUP means send to the process group that currently owns
1258    the terminal being used to communicate with PROCESS.
1259    This is used for various commands in shell mode.
1260    If NOMSG is zero, insert signal-announcements into process's buffers
1261    right away.
1262
1263    If we can, we try to signal PROCESS by sending control characters
1264    down the pty.  This allows us to signal inferiors who have changed
1265    their uid, for which killpg would return an EPERM error.
1266
1267    The method signals an error if the given SIGNO is not valid
1268 */
1269
1270 static void
1271 unix_kill_child_process (Lisp_Object proc, int signo,
1272                          int current_group, int nomsg)
1273 {
1274   int gid;
1275   int no_pgrp = 0;
1276   int kill_retval;
1277   struct Lisp_Process *p = XPROCESS (proc);
1278
1279   if (!UNIX_DATA(p)->pty_flag)
1280     current_group = 0;
1281
1282   /* If we are using pgrps, get a pgrp number and make it negative.  */
1283   if (current_group)
1284     {
1285 #ifdef SIGNALS_VIA_CHARACTERS
1286       /* If possible, send signals to the entire pgrp
1287          by sending an input character to it.  */
1288       {
1289         char sigchar = process_signal_char(UNIX_DATA(p)->subtty, signo);
1290         if (sigchar) {
1291           send_process (proc, Qnil, (Bufbyte *) &sigchar, 0, 1);
1292           return;
1293         }
1294       }
1295 #endif /* ! defined (SIGNALS_VIA_CHARACTERS) */
1296
1297 #ifdef TIOCGPGRP
1298       /* Get the pgrp using the tty itself, if we have that.
1299          Otherwise, use the pty to get the pgrp.
1300          On pfa systems, saka@pfu.fujitsu.co.JP writes:
1301          "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
1302          But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
1303          His patch indicates that if TIOCGPGRP returns an error, then
1304          we should just assume that p->pid is also the process group id.  */
1305       {
1306         int err;
1307
1308         err = ioctl ( (UNIX_DATA(p)->subtty != -1
1309                        ? UNIX_DATA(p)->subtty
1310                        : UNIX_DATA(p)->infd), TIOCGPGRP, &gid);
1311
1312 #ifdef pfa
1313         if (err == -1)
1314           gid = - XINT (p->pid);
1315 #endif /* ! defined (pfa) */
1316       }
1317       if (gid == -1)
1318         no_pgrp = 1;
1319       else
1320         gid = - gid;
1321 #else /* ! defined (TIOCGPGRP ) */
1322       /* Can't select pgrps on this system, so we know that
1323          the child itself heads the pgrp.  */
1324       gid = - XINT (p->pid);
1325 #endif /* ! defined (TIOCGPGRP ) */
1326     }
1327   else
1328     gid = - XINT (p->pid);
1329
1330   switch (signo)
1331     {
1332 #ifdef SIGCONT
1333     case SIGCONT:
1334       p->status_symbol = Qrun;
1335       p->exit_code = 0;
1336       p->tick++;
1337       process_tick++;
1338       if (!nomsg)
1339         status_notify ();
1340       break;
1341 #endif /* ! defined (SIGCONT) */
1342     case SIGINT:
1343     case SIGQUIT:
1344     case SIGKILL:
1345       flush_pending_output (UNIX_DATA(p)->infd);
1346       break;
1347     }
1348
1349   /* If we don't have process groups, send the signal to the immediate
1350      subprocess.  That isn't really right, but it's better than any
1351      obvious alternative.  */
1352   if (no_pgrp)
1353     {
1354       kill_retval = kill (XINT (p->pid), signo) ? errno : 0;
1355     }
1356   else
1357     {
1358       /* gid may be a pid, or minus a pgrp's number */
1359 #if defined (TIOCSIGNAL) || defined (TIOCSIGSEND)
1360       if (current_group)
1361         {
1362 #ifdef TIOCSIGNAL
1363           kill_retval = ioctl (UNIX_DATA(p)->infd, TIOCSIGNAL, signo);
1364 #else /* ! defined (TIOCSIGNAL) */
1365           kill_retval = ioctl (UNIX_DATA(p)->infd, TIOCSIGSEND, signo);
1366 #endif /* ! defined (TIOCSIGNAL) */
1367         }
1368       else
1369         kill_retval = kill (- XINT (p->pid), signo) ? errno : 0;
1370 #else /* ! (defined (TIOCSIGNAL) || defined (TIOCSIGSEND)) */
1371       kill_retval = EMACS_KILLPG (-gid, signo) ? errno : 0;
1372 #endif /* ! (defined (TIOCSIGNAL) || defined (TIOCSIGSEND)) */
1373     }
1374
1375   if (kill_retval < 0 && errno == EINVAL)
1376     error ("Signal number %d is invalid for this system", signo);
1377 }
1378
1379 /*
1380  * Kill any process in the system given its PID.
1381  *
1382  * Returns zero if a signal successfully sent, or
1383  * negative number upon failure
1384  */
1385
1386 static int
1387 unix_kill_process_by_pid (int pid, int sigcode)
1388 {
1389   return kill (pid, sigcode);
1390 }
1391
1392 /*
1393  * Return TTY name used to communicate with subprocess
1394  */
1395
1396 static Lisp_Object
1397 unix_get_tty_name (struct Lisp_Process *p)
1398 {
1399   return UNIX_DATA (p)->tty_name;
1400 }
1401
1402 /*
1403  * Canonicalize host name HOST, and return its canonical form
1404  *
1405  * The default implementation just takes HOST for a canonical name.
1406  */
1407
1408 #ifdef HAVE_SOCKETS
1409 static Lisp_Object
1410 unix_canonicalize_host_name (Lisp_Object host)
1411 {
1412   struct sockaddr_in address;
1413
1414   if (!get_internet_address (host, &address, ERROR_ME_NOT))
1415     return host;
1416
1417   if (address.sin_family == AF_INET)
1418     return build_string (inet_ntoa (address.sin_addr));
1419   else
1420     /* #### any clue what to do here? */
1421     return host;
1422 }
1423
1424 /* open a TCP network connection to a given HOST/SERVICE.  Treated
1425    exactly like a normal process when reading and writing.  Only
1426    differences are in status display and process deletion.  A network
1427    connection has no PID; you cannot signal it.  All you can do is
1428    deactivate and close it via delete-process */
1429
1430 static void
1431 unix_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
1432                           Lisp_Object family, void** vinfd, void** voutfd)
1433 {
1434   struct sockaddr_in address;
1435   int s, inch, outch;
1436   volatile int port;
1437   volatile int retry = 0;
1438   int retval;
1439
1440   CHECK_STRING (host);
1441
1442   if (!EQ (family, Qtcpip))
1443     error ("Unsupported protocol family \"%s\"",
1444            string_data (symbol_name (XSYMBOL (family))));
1445
1446   if (INTP (service))
1447     port = htons ((unsigned short) XINT (service));
1448   else
1449     {
1450       struct servent *svc_info;
1451       CHECK_STRING (service);
1452       svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
1453       if (svc_info == 0)
1454         error ("Unknown service \"%s\"", XSTRING_DATA (service));
1455       port = svc_info->s_port;
1456     }
1457
1458   get_internet_address (host, &address, ERROR_ME);
1459   address.sin_port = port;
1460
1461   s = socket (address.sin_family, SOCK_STREAM, 0);
1462   if (s < 0)
1463     report_file_error ("error creating socket", list1 (name));
1464
1465   /* Turn off interrupts here -- see comments below.  There used to
1466      be code which called bind_polling_period() to slow the polling
1467      period down rather than turn it off, but that seems rather
1468      bogus to me.  Best thing here is to use a non-blocking connect
1469      or something, to check for QUIT. */
1470
1471   /* Comments that are not quite valid: */
1472
1473   /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1474      when connect is interrupted.  So let's not let it get interrupted.
1475      Note we do not turn off polling, because polling is only used
1476      when not interrupt_input, and thus not normally used on the systems
1477      which have this bug.  On systems which use polling, there's no way
1478      to quit if polling is turned off.  */
1479
1480   /* Slow down polling.  Some kernels have a bug which causes retrying
1481      connect to fail after a connect.  */
1482
1483   slow_down_interrupts ();
1484
1485  loop:
1486
1487   /* A system call interrupted with a SIGALRM or SIGIO comes back
1488      here, with can_break_system_calls reset to 0. */
1489   SETJMP (break_system_call_jump);
1490   if (QUITP)
1491     {
1492       speed_up_interrupts ();
1493       REALLY_QUIT;
1494       /* In case something really weird happens ... */
1495       slow_down_interrupts ();
1496     }
1497
1498   /* Break out of connect with a signal (it isn't otherwise possible).
1499      Thus you don't get screwed with a hung network. */
1500   can_break_system_calls = 1;
1501   retval = connect (s, (struct sockaddr *) &address, sizeof (address));
1502   can_break_system_calls = 0;
1503   if (retval == -1 && errno != EISCONN)
1504     {
1505       int xerrno = errno;
1506       if (errno == EINTR)
1507         goto loop;
1508       if (errno == EADDRINUSE && retry < 20)
1509         {
1510           /* A delay here is needed on some FreeBSD systems,
1511              and it is harmless, since this retrying takes time anyway
1512              and should be infrequent.
1513              `sleep-for' allowed for quitting this loop with interrupts
1514              slowed down so it can't be used here.  Async timers should
1515              already be disabled at this point so we can use `sleep'. */
1516           sleep (1);
1517           retry++;
1518           goto loop;
1519         }
1520
1521       close (s);
1522
1523       speed_up_interrupts ();
1524
1525       errno = xerrno;
1526       report_file_error ("connection failed", list2 (host, name));
1527     }
1528
1529   speed_up_interrupts ();
1530
1531   inch = s;
1532   outch = dup (s);
1533   if (outch < 0)
1534     {
1535       close (s); /* this used to be leaked; from Kyle Jones */
1536       report_file_error ("error duplicating socket", list1 (name));
1537     }
1538
1539   set_socket_nonblocking_maybe (inch, port, "tcp");
1540
1541   *vinfd = (void*)inch;
1542   *voutfd = (void*)outch;
1543 }
1544
1545
1546 #ifdef HAVE_MULTICAST
1547
1548 /* Didier Verna <verna@inf.enst.fr> Nov. 28 1997.
1549
1550    This function is similar to open-network-stream-internal, but provides a
1551    mean to open an UDP multicast connection instead of a TCP one. Like in the
1552    TCP case, the multicast connection will be seen as a sub-process,
1553
1554    Some notes:
1555    - Normally, we should use sendto and recvfrom with non connected
1556    sockets. The current code doesn't allow us to do this. In the future, it
1557    would be a good idea to extend the process data structure in order to deal
1558    properly with the different types network connections.
1559    - For the same reason, when leaving a multicast group, it is better to make
1560    a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
1561    Unfortunately, this can't be done here because delete_process doesn't know
1562    about the kind of connection we have. However, this is not such an
1563    important issue.
1564 */
1565
1566 static void
1567 unix_open_multicast_group (Lisp_Object name, Lisp_Object dest, Lisp_Object port,
1568                            Lisp_Object ttl, void** vinfd, void** voutfd)
1569 {
1570   struct ip_mreq imr;
1571   struct sockaddr_in sa;
1572   struct protoent *udp;
1573   int ws, rs;
1574   int theport;
1575   unsigned char thettl;
1576   int one = 1; /* For REUSEADDR */
1577   int ret;
1578   volatile int retry = 0;
1579
1580   CHECK_STRING (dest);
1581
1582   CHECK_NATNUM (port);
1583   theport = htons ((unsigned short) XINT (port));
1584
1585   CHECK_NATNUM (ttl);
1586   thettl = (unsigned char) XINT (ttl);
1587
1588   if ((udp = getprotobyname ("udp")) == NULL)
1589     error ("No info available for UDP protocol");
1590
1591   /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
1592   if ((rs = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1593     report_file_error ("error creating socket", list1(name));
1594   if ((ws = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1595     {
1596       close (rs);
1597       report_file_error ("error creating socket", list1(name));
1598     }
1599
1600   /* This will be used for both sockets */
1601   memset (&sa, 0, sizeof(sa));
1602   sa.sin_family = AF_INET;
1603   sa.sin_port = theport;
1604   sa.sin_addr.s_addr = htonl (inet_addr ((char *) XSTRING_DATA (dest)));
1605
1606   /* Socket configuration for reading ------------------------ */
1607
1608   /* Multiple connections from the same machine. This must be done before
1609      bind. If it fails, it shouldn't be fatal. The only consequence is that
1610      people won't be able to connect twice from the same machine. */
1611   if (setsockopt (rs, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one))
1612       < 0)
1613     warn_when_safe (Qmulticast, Qwarning, "Cannot reuse socket address");
1614
1615   /* bind socket name */
1616   if (bind (rs, (struct sockaddr *)&sa, sizeof(sa)))
1617     {
1618       close (rs);
1619       close (ws);
1620       report_file_error ("error binding socket", list2(name, port));
1621     }
1622
1623   /* join multicast group */
1624   imr.imr_multiaddr.s_addr = htonl (inet_addr ((char *) XSTRING_DATA (dest)));
1625   imr.imr_interface.s_addr = htonl (INADDR_ANY);
1626   if (setsockopt (rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1627                  (char *) &imr, sizeof (struct ip_mreq)) < 0)
1628     {
1629       close (ws);
1630       close (rs);
1631       report_file_error ("error adding membership", list2(name, dest));
1632     }
1633
1634   /* Socket configuration for writing ----------------------- */
1635
1636   /* Normally, there's no 'connect' in multicast, since we prefer to use
1637      'sendto' and 'recvfrom'. However, in order to handle this connection in
1638      the process-like way it is done for TCP, we must be able to use 'write'
1639      instead of 'sendto'. Consequently, we 'connect' this socket. */
1640
1641   /* See open-network-stream-internal for comments on this part of the code */
1642   slow_down_interrupts ();
1643
1644  loop:
1645
1646   /* A system call interrupted with a SIGALRM or SIGIO comes back
1647      here, with can_break_system_calls reset to 0. */
1648   SETJMP (break_system_call_jump);
1649   if (QUITP)
1650     {
1651       speed_up_interrupts ();
1652       REALLY_QUIT;
1653       /* In case something really weird happens ... */
1654       slow_down_interrupts ();
1655     }
1656
1657   /* Break out of connect with a signal (it isn't otherwise possible).
1658      Thus you don't get screwed with a hung network. */
1659   can_break_system_calls = 1;
1660   ret = connect (ws, (struct sockaddr *) &sa, sizeof (sa));
1661   can_break_system_calls = 0;
1662   if (ret == -1 && errno != EISCONN)
1663     {
1664       int xerrno = errno;
1665
1666       if (errno == EINTR)
1667         goto loop;
1668       if (errno == EADDRINUSE && retry < 20)
1669         {
1670           /* A delay here is needed on some FreeBSD systems,
1671              and it is harmless, since this retrying takes time anyway
1672              and should be infrequent.
1673              `sleep-for' allowed for quitting this loop with interrupts
1674              slowed down so it can't be used here.  Async timers should
1675              already be disabled at this point so we can use `sleep'. */
1676           sleep (1);
1677           retry++;
1678           goto loop;
1679         }
1680
1681       close (rs);
1682       close (ws);
1683       speed_up_interrupts ();
1684
1685       errno = xerrno;
1686       report_file_error ("error connecting socket", list2(name, port));
1687     }
1688
1689   speed_up_interrupts ();
1690
1691   /* scope */
1692   if (setsockopt (ws, IPPROTO_IP, IP_MULTICAST_TTL,
1693                   (char *) &thettl, sizeof (thettl)) < 0)
1694     {
1695       close (rs);
1696       close (ws);
1697       report_file_error ("error setting ttl", list2(name, ttl));
1698     }
1699
1700   set_socket_nonblocking_maybe (rs, theport, "udp");
1701
1702   *vinfd = (void*)rs;
1703   *voutfd = (void*)ws;
1704 }
1705
1706 #endif /* HAVE_MULTICAST */
1707
1708 #endif /* HAVE_SOCKETS */
1709
1710 \f
1711 /**********************************************************************/
1712 /*                            Initialization                          */
1713 /**********************************************************************/
1714
1715 void
1716 process_type_create_unix (void)
1717 {
1718   PROCESS_HAS_METHOD (unix, alloc_process_data);
1719   PROCESS_HAS_METHOD (unix, mark_process_data);
1720 #ifdef SIGCHLD
1721   PROCESS_HAS_METHOD (unix, init_process);
1722   PROCESS_HAS_METHOD (unix, reap_exited_processes);
1723 #endif
1724   PROCESS_HAS_METHOD (unix, init_process_io_handles);
1725   PROCESS_HAS_METHOD (unix, create_process);
1726   PROCESS_HAS_METHOD (unix, tooltalk_connection_p);
1727   PROCESS_HAS_METHOD (unix, set_window_size);
1728 #ifdef HAVE_WAITPID
1729   PROCESS_HAS_METHOD (unix, update_status_if_terminated);
1730 #endif
1731   PROCESS_HAS_METHOD (unix, send_process);
1732   PROCESS_HAS_METHOD (unix, process_send_eof);
1733   PROCESS_HAS_METHOD (unix, deactivate_process);
1734   PROCESS_HAS_METHOD (unix, kill_child_process);
1735   PROCESS_HAS_METHOD (unix, kill_process_by_pid);
1736   PROCESS_HAS_METHOD (unix, get_tty_name);
1737 #ifdef HAVE_SOCKETS
1738   PROCESS_HAS_METHOD (unix, canonicalize_host_name);
1739   PROCESS_HAS_METHOD (unix, open_network_stream);
1740 #ifdef HAVE_MULTICAST
1741   PROCESS_HAS_METHOD (unix, open_multicast_group);
1742 #endif
1743 #endif
1744 }
1745
1746 void
1747 vars_of_process_unix (void)
1748 {
1749   Fprovide (intern ("unix-processes"));
1750 }
1751
1752 #endif /* !defined (NO_SUBPROCESSES) */