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