1 /* Asynchronous subprocess control for GNU Emacs.
2 
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2021 Free Software
4 Foundation, Inc.
5 
6 This file is part of GNU Emacs.
7 
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
12 
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
20 
21 
22 #include <config.h>
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h>		/* Some typedefs are used in sys/file.h.  */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 
33 #include "lisp.h"
34 
35 /* Only MS-DOS does not define `subprocesses'.  */
36 #ifdef subprocesses
37 
38 #include <sys/socket.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 
43 #else
44 #define PIPECONN_P(p) false
45 #define PIPECONN1_P(p) false
46 #endif
47 
48 #ifdef HAVE_SETRLIMIT
49 # include <sys/resource.h>
50 
51 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
52    NOFILE_LIMIT is the initial limit on the number of open files,
53    which should be restored in child processes.  */
54 static struct rlimit nofile_limit;
55 #endif
56 
57 #ifdef subprocesses
58 
59 /* Are local (unix) sockets supported?  */
60 #if defined (HAVE_SYS_UN_H)
61 #if !defined (AF_LOCAL) && defined (AF_UNIX)
62 #define AF_LOCAL AF_UNIX
63 #endif
64 #ifdef AF_LOCAL
65 #define HAVE_LOCAL_SOCKETS
66 #include <sys/un.h>
67 #endif
68 #endif
69 
70 #include <sys/ioctl.h>
71 #if defined (HAVE_NET_IF_H)
72 #include <net/if.h>
73 #endif /* HAVE_NET_IF_H */
74 
75 #if defined (HAVE_IFADDRS_H)
76 /* Must be after net/if.h */
77 #include <ifaddrs.h>
78 
79 /* We only use structs from this header when we use getifaddrs.  */
80 #if defined (HAVE_NET_IF_DL_H)
81 #include <net/if_dl.h>
82 #endif
83 
84 #endif
85 
86 #ifdef HAVE_UTIL_H
87 #include <util.h>
88 #endif
89 
90 #ifdef HAVE_PTY_H
91 #include <pty.h>
92 #endif
93 
94 #include <c-ctype.h>
95 #include <flexmember.h>
96 #include <nproc.h>
97 #include <sig2str.h>
98 #include <verify.h>
99 
100 #endif	/* subprocesses */
101 
102 #include "systime.h"
103 #include "systty.h"
104 
105 #include "window.h"
106 #include "character.h"
107 #include "buffer.h"
108 #include "coding.h"
109 #include "process.h"
110 #include "frame.h"
111 #include "termopts.h"
112 #include "keyboard.h"
113 #include "blockinput.h"
114 #include "atimer.h"
115 #include "sysselect.h"
116 #include "syssignal.h"
117 #include "syswait.h"
118 #ifdef HAVE_GNUTLS
119 #include "gnutls.h"
120 #endif
121 
122 #ifdef HAVE_WINDOW_SYSTEM
123 #include TERM_HEADER
124 #endif /* HAVE_WINDOW_SYSTEM */
125 
126 #ifdef HAVE_GLIB
127 #include "xgselect.h"
128 #ifndef WINDOWSNT
129 #include <glib.h>
130 #endif
131 #endif
132 
133 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
134 /* This is 0.1s in nanoseconds. */
135 #define ASYNC_RETRY_NSEC 100000000
136 #endif
137 
138 #ifdef WINDOWSNT
139 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
140                        const struct timespec *, const sigset_t *);
141 #endif
142 
143 /* Work around GCC 4.3.0 bug with strict overflow checking; see
144    <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
145    This bug appears to be fixed in GCC 5.1, so don't work around it there.  */
146 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
147 # pragma GCC diagnostic ignored "-Wstrict-overflow"
148 #endif
149 
150 /* True if keyboard input is on hold, zero otherwise.  */
151 
152 static bool kbd_is_on_hold;
153 
154 /* Nonzero means don't run process sentinels.  This is used
155    when exiting.  */
156 bool inhibit_sentinels;
157 
158 #ifdef subprocesses
159 union u_sockaddr
160 {
161   struct sockaddr sa;
162   struct sockaddr_in in;
163 #ifdef AF_INET6
164   struct sockaddr_in6 in6;
165 #endif
166 #ifdef HAVE_LOCAL_SOCKETS
167   struct sockaddr_un un;
168 #endif
169 };
170 
171 #ifndef SOCK_CLOEXEC
172 # define SOCK_CLOEXEC 0
173 #endif
174 #ifndef SOCK_NONBLOCK
175 # define SOCK_NONBLOCK 0
176 #endif
177 
178 /* True if ERRNUM represents an error where the system call would
179    block if a blocking variant were used.  */
180 static bool
would_block(int errnum)181 would_block (int errnum)
182 {
183 #ifdef EWOULDBLOCK
184   if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
185     return true;
186 #endif
187   return errnum == EAGAIN;
188 }
189 
190 #ifndef HAVE_ACCEPT4
191 
192 /* Emulate GNU/Linux accept4 and socket well enough for this module.  */
193 
194 static int
close_on_exec(int fd)195 close_on_exec (int fd)
196 {
197   if (0 <= fd)
198     fcntl (fd, F_SETFD, FD_CLOEXEC);
199   return fd;
200 }
201 
202 # undef accept4
203 # define accept4(sockfd, addr, addrlen, flags) \
204     process_accept4 (sockfd, addr, addrlen, flags)
205 static int
accept4(int sockfd,struct sockaddr * addr,socklen_t * addrlen,int flags)206 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
207 {
208   return close_on_exec (accept (sockfd, addr, addrlen));
209 }
210 
211 static int
process_socket(int domain,int type,int protocol)212 process_socket (int domain, int type, int protocol)
213 {
214   return close_on_exec (socket (domain, type, protocol));
215 }
216 # undef socket
217 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
218 #endif
219 
220 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
221 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
222 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
223 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
224 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
225 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
226 
227 /* Number of events of change of status of a process.  */
228 static EMACS_INT process_tick;
229 /* Number of events for which the user or sentinel has been notified.  */
230 static EMACS_INT update_tick;
231 
232 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
233    this system.  We need to read full packets, so we need a
234    "non-destructive" select.  So we require either native select,
235    or emulation of select using FIONREAD.  */
236 
237 #ifndef BROKEN_DATAGRAM_SOCKETS
238 # if defined HAVE_SELECT || defined USABLE_FIONREAD
239 #  if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
240 #   define DATAGRAM_SOCKETS
241 #  endif
242 # endif
243 #endif
244 
245 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
246 # define HAVE_SEQPACKET
247 #endif
248 
249 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_HZ / 100)
250 #define READ_OUTPUT_DELAY_MAX       (READ_OUTPUT_DELAY_INCREMENT * 5)
251 #define READ_OUTPUT_DELAY_MAX_MAX   (READ_OUTPUT_DELAY_INCREMENT * 7)
252 
253 /* Number of processes which have a non-zero read_output_delay,
254    and therefore might be delayed for adaptive read buffering.  */
255 
256 static int process_output_delay_count;
257 
258 /* True if any process has non-nil read_output_skip.  */
259 
260 static bool process_output_skip;
261 
262 static void start_process_unwind (Lisp_Object);
263 static void create_process (Lisp_Object, char **, Lisp_Object);
264 #if defined (USABLE_SIGIO) || defined (USABLE_SIGPOLL)
265 static bool keyboard_bit_set (fd_set *);
266 #endif
267 static void deactivate_process (Lisp_Object);
268 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
269 static int read_process_output (Lisp_Object, int);
270 static void create_pty (Lisp_Object);
271 static void exec_sentinel (Lisp_Object, Lisp_Object);
272 
273 static Lisp_Object
274 network_lookup_address_info_1 (Lisp_Object host, const char *service,
275                                struct addrinfo *hints, struct addrinfo **res);
276 
277 /* Number of bits set in connect_wait_mask.  */
278 static int num_pending_connects;
279 
280 /* The largest descriptor currently in use; -1 if none.  */
281 static int max_desc;
282 
283 /* Set the external socket descriptor for Emacs to use when
284    `make-network-process' is called with a non-nil
285    `:use-external-socket' option.  The value should be either -1, or
286    the file descriptor of a socket that is already bound.  */
287 static int external_sock_fd;
288 
289 /* File descriptor that becomes readable when we receive SIGCHLD.  */
290 static int child_signal_read_fd = -1;
291 /* The write end thereof.  The SIGCHLD handler writes to this file
292    descriptor to notify `wait_reading_process_output' of process
293    status changes.  */
294 static int child_signal_write_fd = -1;
295 static void child_signal_init (void);
296 #ifndef WINDOWSNT
297 static void child_signal_read (int, void *);
298 #endif
299 static void child_signal_notify (void);
300 
301 /* Indexed by descriptor, gives the process (if any) for that descriptor.  */
302 static Lisp_Object chan_process[FD_SETSIZE];
303 static void wait_for_socket_fds (Lisp_Object, char const *);
304 
305 /* Alist of elements (NAME . PROCESS).  */
306 static Lisp_Object Vprocess_alist;
307 
308 /* Buffered-ahead input char from process, indexed by channel.
309    -1 means empty (no char is buffered).
310    Used on sys V where the only way to tell if there is any
311    output from the process is to read at least one char.
312    Always -1 on systems that support FIONREAD.  */
313 
314 static int proc_buffered_char[FD_SETSIZE];
315 
316 /* Table of `struct coding-system' for each process.  */
317 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
318 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
319 
320 #ifdef DATAGRAM_SOCKETS
321 /* Table of `partner address' for datagram sockets.  */
322 static struct sockaddr_and_len {
323   struct sockaddr *sa;
324   ptrdiff_t len;
325 } datagram_address[FD_SETSIZE];
326 #define DATAGRAM_CHAN_P(chan)	(datagram_address[chan].sa != 0)
327 #define DATAGRAM_CONN_P(proc)                                           \
328   (PROCESSP (proc) &&                                                   \
329    XPROCESS (proc)->infd >= 0 &&                                        \
330    datagram_address[XPROCESS (proc)->infd].sa != 0)
331 #else
332 #define DATAGRAM_CONN_P(proc)	(0)
333 #endif
334 
335 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
336    a `for' loop which iterates over processes from Vprocess_alist.  */
337 
338 #define FOR_EACH_PROCESS(list_var, proc_var)			\
339   FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
340 
341 /* These setters are used only in this file, so they can be private.  */
342 static void
pset_buffer(struct Lisp_Process * p,Lisp_Object val)343 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
344 {
345   p->buffer = val;
346 }
347 static void
pset_command(struct Lisp_Process * p,Lisp_Object val)348 pset_command (struct Lisp_Process *p, Lisp_Object val)
349 {
350   p->command = val;
351 }
352 static void
pset_decode_coding_system(struct Lisp_Process * p,Lisp_Object val)353 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
354 {
355   p->decode_coding_system = val;
356 }
357 static void
pset_decoding_buf(struct Lisp_Process * p,Lisp_Object val)358 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
359 {
360   p->decoding_buf = val;
361 }
362 static void
pset_encode_coding_system(struct Lisp_Process * p,Lisp_Object val)363 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
364 {
365   p->encode_coding_system = val;
366 }
367 static void
pset_encoding_buf(struct Lisp_Process * p,Lisp_Object val)368 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
369 {
370   p->encoding_buf = val;
371 }
372 static void
pset_filter(struct Lisp_Process * p,Lisp_Object val)373 pset_filter (struct Lisp_Process *p, Lisp_Object val)
374 {
375   p->filter = NILP (val) ? Qinternal_default_process_filter : val;
376 }
377 static void
pset_log(struct Lisp_Process * p,Lisp_Object val)378 pset_log (struct Lisp_Process *p, Lisp_Object val)
379 {
380   p->log = val;
381 }
382 static void
pset_mark(struct Lisp_Process * p,Lisp_Object val)383 pset_mark (struct Lisp_Process *p, Lisp_Object val)
384 {
385   p->mark = val;
386 }
387 static void
pset_thread(struct Lisp_Process * p,Lisp_Object val)388 pset_thread (struct Lisp_Process *p, Lisp_Object val)
389 {
390   p->thread = val;
391 }
392 static void
pset_name(struct Lisp_Process * p,Lisp_Object val)393 pset_name (struct Lisp_Process *p, Lisp_Object val)
394 {
395   p->name = val;
396 }
397 static void
pset_plist(struct Lisp_Process * p,Lisp_Object val)398 pset_plist (struct Lisp_Process *p, Lisp_Object val)
399 {
400   p->plist = val;
401 }
402 static void
pset_sentinel(struct Lisp_Process * p,Lisp_Object val)403 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
404 {
405   p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
406 }
407 static void
pset_tty_name(struct Lisp_Process * p,Lisp_Object val)408 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
409 {
410   p->tty_name = val;
411 }
412 static void
pset_type(struct Lisp_Process * p,Lisp_Object val)413 pset_type (struct Lisp_Process *p, Lisp_Object val)
414 {
415   p->type = val;
416 }
417 static void
pset_write_queue(struct Lisp_Process * p,Lisp_Object val)418 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
419 {
420   p->write_queue = val;
421 }
422 static void
pset_stderrproc(struct Lisp_Process * p,Lisp_Object val)423 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
424 {
425   p->stderrproc = val;
426 }
427 
428 
429 static Lisp_Object
make_lisp_proc(struct Lisp_Process * p)430 make_lisp_proc (struct Lisp_Process *p)
431 {
432   return make_lisp_ptr (p, Lisp_Vectorlike);
433 }
434 
435 enum fd_bits
436 {
437   /* Read from file descriptor.  */
438   FOR_READ = 1,
439   /* Write to file descriptor.  */
440   FOR_WRITE = 2,
441   /* This descriptor refers to a keyboard.  Only valid if FOR_READ is
442      set.  */
443   KEYBOARD_FD = 4,
444   /* This descriptor refers to a process.  */
445   PROCESS_FD = 8,
446   /* A non-blocking connect.  Only valid if FOR_WRITE is set.  */
447   NON_BLOCKING_CONNECT_FD = 16
448 };
449 
450 static struct fd_callback_data
451 {
452   fd_callback func;
453   void *data;
454   /* Flags from enum fd_bits.  */
455   int flags;
456   /* If this fd is locked to a certain thread, this points to it.
457      Otherwise, this is NULL.  If an fd is locked to a thread, then
458      only that thread is permitted to wait on it.  */
459   struct thread_state *thread;
460   /* If this fd is currently being selected on by a thread, this
461      points to the thread.  Otherwise it is NULL.  */
462   struct thread_state *waiting_thread;
463 } fd_callback_info[FD_SETSIZE];
464 
465 
466 /* Add a file descriptor FD to be monitored for when read is possible.
467    When read is possible, call FUNC with argument DATA.  */
468 
469 void
add_read_fd(int fd,fd_callback func,void * data)470 add_read_fd (int fd, fd_callback func, void *data)
471 {
472   add_keyboard_wait_descriptor (fd);
473 
474   eassert (0 <= fd && fd < FD_SETSIZE);
475   fd_callback_info[fd].func = func;
476   fd_callback_info[fd].data = data;
477 }
478 
479 void
add_non_keyboard_read_fd(int fd,fd_callback func,void * data)480 add_non_keyboard_read_fd (int fd, fd_callback func, void *data)
481 {
482   add_read_fd(fd, func, data);
483   fd_callback_info[fd].flags &= ~KEYBOARD_FD;
484 }
485 
486 static void
add_process_read_fd(int fd)487 add_process_read_fd (int fd)
488 {
489   eassert (fd >= 0 && fd < FD_SETSIZE);
490   eassert (fd_callback_info[fd].func == NULL);
491 
492   fd_callback_info[fd].flags &= ~KEYBOARD_FD;
493   fd_callback_info[fd].flags |= FOR_READ;
494   if (fd > max_desc)
495     max_desc = fd;
496   eassert (0 <= fd && fd < FD_SETSIZE);
497   fd_callback_info[fd].flags |= PROCESS_FD;
498 }
499 
500 /* Stop monitoring file descriptor FD for when read is possible.  */
501 
502 void
delete_read_fd(int fd)503 delete_read_fd (int fd)
504 {
505   delete_keyboard_wait_descriptor (fd);
506 
507   eassert (0 <= fd && fd < FD_SETSIZE);
508   if (fd_callback_info[fd].flags == 0)
509     {
510       fd_callback_info[fd].func = 0;
511       fd_callback_info[fd].data = 0;
512     }
513 }
514 
515 /* Add a file descriptor FD to be monitored for when write is possible.
516    When write is possible, call FUNC with argument DATA.  */
517 
518 void
add_write_fd(int fd,fd_callback func,void * data)519 add_write_fd (int fd, fd_callback func, void *data)
520 {
521   eassert (fd >= 0 && fd < FD_SETSIZE);
522 
523   fd_callback_info[fd].func = func;
524   fd_callback_info[fd].data = data;
525   fd_callback_info[fd].flags |= FOR_WRITE;
526   if (fd > max_desc)
527     max_desc = fd;
528 }
529 
530 static void
add_non_blocking_write_fd(int fd)531 add_non_blocking_write_fd (int fd)
532 {
533   eassert (fd >= 0 && fd < FD_SETSIZE);
534   eassert (fd_callback_info[fd].func == NULL);
535 
536   fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
537   if (fd > max_desc)
538     max_desc = fd;
539   ++num_pending_connects;
540 }
541 
542 static void
recompute_max_desc(void)543 recompute_max_desc (void)
544 {
545   int fd;
546 
547   eassert (max_desc < FD_SETSIZE);
548   for (fd = max_desc; fd >= 0; --fd)
549     {
550       if (fd_callback_info[fd].flags != 0)
551 	{
552 	  max_desc = fd;
553 	  break;
554 	}
555     }
556   eassert (max_desc < FD_SETSIZE);
557 }
558 
559 /* Stop monitoring file descriptor FD for when write is possible.  */
560 
561 void
delete_write_fd(int fd)562 delete_write_fd (int fd)
563 {
564   eassert (0 <= fd && fd < FD_SETSIZE);
565   if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
566     {
567       if (--num_pending_connects < 0)
568 	emacs_abort ();
569     }
570   fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
571   if (fd_callback_info[fd].flags == 0)
572     {
573       fd_callback_info[fd].func = 0;
574       fd_callback_info[fd].data = 0;
575 
576       if (fd == max_desc)
577 	recompute_max_desc ();
578     }
579 }
580 
581 static void
compute_input_wait_mask(fd_set * mask)582 compute_input_wait_mask (fd_set *mask)
583 {
584   int fd;
585 
586   FD_ZERO (mask);
587   eassert (max_desc < FD_SETSIZE);
588   for (fd = 0; fd <= max_desc; ++fd)
589     {
590       if (fd_callback_info[fd].thread != NULL
591 	  && fd_callback_info[fd].thread != current_thread)
592 	continue;
593       if (fd_callback_info[fd].waiting_thread != NULL
594 	  && fd_callback_info[fd].waiting_thread != current_thread)
595 	continue;
596       if ((fd_callback_info[fd].flags & FOR_READ) != 0)
597 	{
598 	  FD_SET (fd, mask);
599 	  fd_callback_info[fd].waiting_thread = current_thread;
600 	}
601     }
602 }
603 
604 static void
compute_non_process_wait_mask(fd_set * mask)605 compute_non_process_wait_mask (fd_set *mask)
606 {
607   int fd;
608 
609   FD_ZERO (mask);
610   eassert (max_desc < FD_SETSIZE);
611   for (fd = 0; fd <= max_desc; ++fd)
612     {
613       if (fd_callback_info[fd].thread != NULL
614 	  && fd_callback_info[fd].thread != current_thread)
615 	continue;
616       if (fd_callback_info[fd].waiting_thread != NULL
617 	  && fd_callback_info[fd].waiting_thread != current_thread)
618 	continue;
619       if ((fd_callback_info[fd].flags & FOR_READ) != 0
620 	  && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
621 	{
622 	  FD_SET (fd, mask);
623 	  fd_callback_info[fd].waiting_thread = current_thread;
624 	}
625     }
626 }
627 
628 static void
compute_non_keyboard_wait_mask(fd_set * mask)629 compute_non_keyboard_wait_mask (fd_set *mask)
630 {
631   int fd;
632 
633   FD_ZERO (mask);
634   eassert (max_desc < FD_SETSIZE);
635   for (fd = 0; fd <= max_desc; ++fd)
636     {
637       if (fd_callback_info[fd].thread != NULL
638 	  && fd_callback_info[fd].thread != current_thread)
639 	continue;
640       if (fd_callback_info[fd].waiting_thread != NULL
641 	  && fd_callback_info[fd].waiting_thread != current_thread)
642 	continue;
643       if ((fd_callback_info[fd].flags & FOR_READ) != 0
644 	  && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
645 	{
646 	  FD_SET (fd, mask);
647 	  fd_callback_info[fd].waiting_thread = current_thread;
648 	}
649     }
650 }
651 
652 static void
compute_write_mask(fd_set * mask)653 compute_write_mask (fd_set *mask)
654 {
655   int fd;
656 
657   FD_ZERO (mask);
658   eassert (max_desc < FD_SETSIZE);
659   for (fd = 0; fd <= max_desc; ++fd)
660     {
661       if (fd_callback_info[fd].thread != NULL
662 	  && fd_callback_info[fd].thread != current_thread)
663 	continue;
664       if (fd_callback_info[fd].waiting_thread != NULL
665 	  && fd_callback_info[fd].waiting_thread != current_thread)
666 	continue;
667       if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
668 	{
669 	  FD_SET (fd, mask);
670 	  fd_callback_info[fd].waiting_thread = current_thread;
671 	}
672     }
673 }
674 
675 static void
clear_waiting_thread_info(void)676 clear_waiting_thread_info (void)
677 {
678   int fd;
679 
680   eassert (max_desc < FD_SETSIZE);
681   for (fd = 0; fd <= max_desc; ++fd)
682     {
683       if (fd_callback_info[fd].waiting_thread == current_thread)
684 	fd_callback_info[fd].waiting_thread = NULL;
685     }
686 }
687 
688 /* Return TRUE if the keyboard descriptor is being monitored by the
689    current thread, FALSE otherwise.  */
690 static bool
kbd_is_ours(void)691 kbd_is_ours (void)
692 {
693   for (int fd = 0; fd <= max_desc; ++fd)
694     {
695       if (fd_callback_info[fd].waiting_thread != current_thread)
696 	continue;
697       if ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
698 	  == (FOR_READ | KEYBOARD_FD))
699 	return true;
700     }
701   return false;
702 }
703 
704 
705 /* Compute the Lisp form of the process status, p->status, from
706    the numeric status that was returned by `wait'.  */
707 
708 static Lisp_Object status_convert (int);
709 
710 static void
update_status(struct Lisp_Process * p)711 update_status (struct Lisp_Process *p)
712 {
713   eassert (p->raw_status_new);
714   pset_status (p, status_convert (p->raw_status));
715   p->raw_status_new = 0;
716 }
717 
718 /*  Convert a process status word in Unix format to
719     the list that we use internally.  */
720 
721 static Lisp_Object
status_convert(int w)722 status_convert (int w)
723 {
724   if (WIFSTOPPED (w))
725     return Fcons (Qstop, Fcons (make_fixnum (WSTOPSIG (w)), Qnil));
726   else if (WIFEXITED (w))
727     return Fcons (Qexit, Fcons (make_fixnum (WEXITSTATUS (w)), Qnil));
728   else if (WIFSIGNALED (w))
729     return Fcons (Qsignal, Fcons (make_fixnum (WTERMSIG (w)),
730 				  WCOREDUMP (w) ? Qt : Qnil));
731   else
732     return Qrun;
733 }
734 
735 /* True if STATUS is that of a process attempting connection.  */
736 
737 static bool
connecting_status(Lisp_Object status)738 connecting_status (Lisp_Object status)
739 {
740   return CONSP (status) && EQ (XCAR (status), Qconnect);
741 }
742 
743 /* Given a status-list, extract the three pieces of information
744    and store them individually through the three pointers.  */
745 
746 static void
decode_status(Lisp_Object l,Lisp_Object * symbol,Lisp_Object * code,bool * coredump)747 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
748 	       bool *coredump)
749 {
750   Lisp_Object tem;
751 
752   if (connecting_status (l))
753     l = XCAR (l);
754 
755   if (SYMBOLP (l))
756     {
757       *symbol = l;
758       *code = make_fixnum (0);
759       *coredump = 0;
760     }
761   else
762     {
763       *symbol = XCAR (l);
764       tem = XCDR (l);
765       *code = XCAR (tem);
766       tem = XCDR (tem);
767       *coredump = !NILP (tem);
768     }
769 }
770 
771 /* Return a string describing a process status list.  */
772 
773 static Lisp_Object
status_message(struct Lisp_Process * p)774 status_message (struct Lisp_Process *p)
775 {
776   Lisp_Object status = p->status;
777   Lisp_Object symbol, code;
778   bool coredump;
779   Lisp_Object string;
780 
781   decode_status (status, &symbol, &code, &coredump);
782 
783   if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
784     {
785       char const *signame;
786       synchronize_system_messages_locale ();
787       signame = strsignal (XFIXNAT (code));
788       if (signame == 0)
789 	string = build_string ("unknown");
790       else
791 	{
792 	  int c1, c2;
793 
794 	  string = build_unibyte_string (signame);
795 	  if (! NILP (Vlocale_coding_system))
796 	    string = (code_convert_string_norecord
797 		      (string, Vlocale_coding_system, 0));
798 	  c1 = STRING_CHAR (SDATA (string));
799 	  c2 = downcase (c1);
800 	  if (c1 != c2)
801 	    Faset (string, make_fixnum (0), make_fixnum (c2));
802 	}
803       AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
804       return concat2 (string, suffix);
805     }
806   else if (EQ (symbol, Qexit))
807     {
808       if (NETCONN1_P (p))
809 	return build_string (XFIXNAT (code) == 0
810 			     ? "deleted\n"
811 			     : "connection broken by remote peer\n");
812       if (XFIXNAT (code) == 0)
813 	return build_string ("finished\n");
814       AUTO_STRING (prefix, "exited abnormally with code ");
815       string = Fnumber_to_string (code);
816       AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
817       return concat3 (prefix, string, suffix);
818     }
819   else if (EQ (symbol, Qfailed))
820     {
821       AUTO_STRING (format, "failed with code %s\n");
822       return CALLN (Fformat, format, code);
823     }
824   else
825     return Fcopy_sequence (Fsymbol_name (symbol));
826 }
827 
828 enum { PTY_NAME_SIZE = 24 };
829 
830 /* Open an available pty, returning a file descriptor.
831    Store into PTY_NAME the file name of the terminal corresponding to the pty.
832    Return -1 on failure.  */
833 
834 static int
allocate_pty(char pty_name[PTY_NAME_SIZE])835 allocate_pty (char pty_name[PTY_NAME_SIZE])
836 {
837 #ifdef HAVE_PTYS
838   int fd;
839 
840 #ifdef PTY_ITERATION
841   PTY_ITERATION
842 #else
843   register int c, i;
844   for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
845     for (i = 0; i < 16; i++)
846 #endif
847       {
848 #ifdef PTY_NAME_SPRINTF
849 	PTY_NAME_SPRINTF
850 #else
851 	sprintf (pty_name, "/dev/pty%c%x", c, i);
852 #endif /* no PTY_NAME_SPRINTF */
853 
854 #ifdef PTY_OPEN
855 	PTY_OPEN;
856 #else /* no PTY_OPEN */
857 	fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
858 #endif /* no PTY_OPEN */
859 
860 	if (fd >= 0)
861 	  {
862 #ifdef PTY_TTY_NAME_SPRINTF
863 	    PTY_TTY_NAME_SPRINTF
864 #else
865 	    sprintf (pty_name, "/dev/tty%c%x", c, i);
866 #endif /* no PTY_TTY_NAME_SPRINTF */
867 
868 	    /* Set FD's close-on-exec flag.  This is needed even if
869 	       PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
870 	       doesn't require support for that combination.
871 	       Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
872 	       doesn't work if the close-on-exec flag is set (Bug#20555).
873 	       Multithreaded platforms where posix_openpt ignores
874 	       O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
875 	       have a race condition between the PTY_OPEN and here.  */
876 	    fcntl (fd, F_SETFD, FD_CLOEXEC);
877 
878 	    /* Check to make certain that both sides are available.
879 	       This avoids a nasty yet stupid bug in rlogins.  */
880 	    if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
881 	      {
882 		emacs_close (fd);
883 		continue;
884 	      }
885 	    setup_pty (fd);
886 	    return fd;
887 	  }
888       }
889 #endif /* HAVE_PTYS */
890   return -1;
891 }
892 
893 /* Allocate basically initialized process.  */
894 
895 static struct Lisp_Process *
allocate_process(void)896 allocate_process (void)
897 {
898   return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, thread,
899 				       PVEC_PROCESS);
900 }
901 
902 static Lisp_Object
make_process(Lisp_Object name)903 make_process (Lisp_Object name)
904 {
905   struct Lisp_Process *p = allocate_process ();
906   /* Initialize Lisp data.  Note that allocate_process initializes all
907      Lisp data to nil, so do it only for slots which should not be nil.  */
908   pset_status (p, Qrun);
909   pset_mark (p, Fmake_marker ());
910   pset_thread (p, Fcurrent_thread ());
911 
912   /* Initialize non-Lisp data.  Note that allocate_process zeroes out all
913      non-Lisp data, so do it only for slots which should not be zero.  */
914   p->infd = -1;
915   p->outfd = -1;
916   for (int i = 0; i < PROCESS_OPEN_FDS; i++)
917     p->open_fd[i] = -1;
918 
919 #ifdef HAVE_GNUTLS
920   verify (GNUTLS_STAGE_EMPTY == 0);
921   eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
922   eassert (NILP (p->gnutls_boot_parameters));
923 #endif
924 
925   /* If name is already in use, modify it until it is unused.  */
926 
927   Lisp_Object name1 = name;
928   for (intmax_t i = 1; ; i++)
929     {
930       Lisp_Object tem = Fget_process (name1);
931       if (NILP (tem))
932 	break;
933       char const suffix_fmt[] = "<%"PRIdMAX">";
934       char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (i)];
935       AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
936       name1 = concat2 (name, lsuffix);
937     }
938   name = name1;
939   pset_name (p, name);
940   pset_sentinel (p, Qinternal_default_process_sentinel);
941   pset_filter (p, Qinternal_default_process_filter);
942   Lisp_Object val;
943   XSETPROCESS (val, p);
944   Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
945   return val;
946 }
947 
948 static void
remove_process(register Lisp_Object proc)949 remove_process (register Lisp_Object proc)
950 {
951   register Lisp_Object pair;
952 
953   pair = Frassq (proc, Vprocess_alist);
954   Vprocess_alist = Fdelq (pair, Vprocess_alist);
955 
956   deactivate_process (proc);
957 }
958 
959 void
update_processes_for_thread_death(Lisp_Object dying_thread)960 update_processes_for_thread_death (Lisp_Object dying_thread)
961 {
962   Lisp_Object pair;
963 
964   for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
965     {
966       Lisp_Object process = XCDR (XCAR (pair));
967       if (EQ (XPROCESS (process)->thread, dying_thread))
968 	{
969 	  struct Lisp_Process *proc = XPROCESS (process);
970 
971 	  pset_thread (proc, Qnil);
972 	  eassert (proc->infd < FD_SETSIZE);
973 	  if (proc->infd >= 0)
974 	    fd_callback_info[proc->infd].thread = NULL;
975 	  eassert (proc->outfd < FD_SETSIZE);
976 	  if (proc->outfd >= 0)
977 	    fd_callback_info[proc->outfd].thread = NULL;
978 	}
979     }
980 }
981 
982 #ifdef HAVE_GETADDRINFO_A
983 static void
free_dns_request(Lisp_Object proc)984 free_dns_request (Lisp_Object proc)
985 {
986   struct Lisp_Process *p = XPROCESS (proc);
987 
988   if (p->dns_request->ar_result)
989     freeaddrinfo (p->dns_request->ar_result);
990   xfree (p->dns_request);
991   p->dns_request = NULL;
992 }
993 #endif
994 
995 
996 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
997        doc: /* Return t if OBJECT is a process.  */)
998   (Lisp_Object object)
999 {
1000   return PROCESSP (object) ? Qt : Qnil;
1001 }
1002 
1003 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
1004        doc: /* Return the process named NAME, or nil if there is none.  */)
1005   (register Lisp_Object name)
1006 {
1007   if (PROCESSP (name))
1008     return name;
1009   CHECK_STRING (name);
1010   return Fcdr (Fassoc (name, Vprocess_alist, Qnil));
1011 }
1012 
1013 /* This is how commands for the user decode process arguments.  It
1014    accepts a process, a process name, a buffer, a buffer name, or nil.
1015    Buffers denote the first process in the buffer, and nil denotes the
1016    current buffer.  */
1017 
1018 static Lisp_Object
get_process(register Lisp_Object name)1019 get_process (register Lisp_Object name)
1020 {
1021   register Lisp_Object proc, obj;
1022   if (STRINGP (name))
1023     {
1024       obj = Fget_process (name);
1025       if (NILP (obj))
1026 	obj = Fget_buffer (name);
1027       if (NILP (obj))
1028 	error ("Process %s does not exist", SDATA (name));
1029     }
1030   else if (NILP (name))
1031     obj = Fcurrent_buffer ();
1032   else
1033     obj = name;
1034 
1035   /* Now obj should be either a buffer object or a process object.  */
1036   if (BUFFERP (obj))
1037     {
1038       if (NILP (BVAR (XBUFFER (obj), name)))
1039         error ("Attempt to get process for a dead buffer");
1040       proc = Fget_buffer_process (obj);
1041       if (NILP (proc))
1042         error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
1043     }
1044   else
1045     {
1046       CHECK_PROCESS (obj);
1047       proc = obj;
1048     }
1049   return proc;
1050 }
1051 
1052 
1053 /* Fdelete_process promises to immediately forget about the process, but in
1054    reality, Emacs needs to remember those processes until they have been
1055    treated by the SIGCHLD handler and waitpid has been invoked on them;
1056    otherwise they might fill up the kernel's process table.
1057 
1058    Some processes created by call-process are also put onto this list.
1059 
1060    Members of this list are (process-ID . filename) pairs.  The
1061    process-ID is a number; the filename, if a string, is a file that
1062    needs to be removed after the process exits.  */
1063 static Lisp_Object deleted_pid_list;
1064 
1065 void
record_deleted_pid(pid_t pid,Lisp_Object filename)1066 record_deleted_pid (pid_t pid, Lisp_Object filename)
1067 {
1068   deleted_pid_list = Fcons (Fcons (INT_TO_INTEGER (pid), filename),
1069 			    /* GC treated elements set to nil.  */
1070 			    Fdelq (Qnil, deleted_pid_list));
1071 
1072 }
1073 
1074 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1075        doc: /* Delete PROCESS: kill it and forget about it immediately.
1076 PROCESS may be a process, a buffer, the name of a process or buffer, or
1077 nil, indicating the current buffer's process.  */)
1078   (register Lisp_Object process)
1079 {
1080   register struct Lisp_Process *p;
1081 
1082   process = get_process (process);
1083   p = XPROCESS (process);
1084 
1085 #ifdef HAVE_GETADDRINFO_A
1086   if (p->dns_request)
1087     {
1088       /* Cancel the request.  Unless shutting down, wait until
1089 	 completion.  Free the request if completely canceled. */
1090 
1091       bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
1092       if (!canceled && !inhibit_sentinels)
1093 	{
1094 	  struct gaicb const *req = p->dns_request;
1095 	  while (gai_suspend (&req, 1, NULL) != 0)
1096 	    continue;
1097 	  canceled = true;
1098 	}
1099       if (canceled)
1100 	free_dns_request (process);
1101     }
1102 #endif
1103 
1104   p->raw_status_new = 0;
1105   if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1106     {
1107       pset_status (p, list2 (Qexit, make_fixnum (0)));
1108       p->tick = ++process_tick;
1109       status_notify (p, NULL);
1110       redisplay_preserve_echo_area (13);
1111     }
1112   else
1113     {
1114       if (p->alive)
1115 	record_kill_process (p, Qnil);
1116 
1117       if (p->infd >= 0)
1118 	{
1119 	  /* Update P's status, since record_kill_process will make the
1120 	     SIGCHLD handler update deleted_pid_list, not *P.  */
1121 	  Lisp_Object symbol;
1122 	  if (p->raw_status_new)
1123 	    update_status (p);
1124 	  symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1125 	  if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1126 	    pset_status (p, list2 (Qsignal, make_fixnum (SIGKILL)));
1127 
1128 	  p->tick = ++process_tick;
1129 	  status_notify (p, NULL);
1130 	  redisplay_preserve_echo_area (13);
1131 	}
1132     }
1133   remove_process (process);
1134   return Qnil;
1135 }
1136 
1137 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1138        doc: /* Return the status of PROCESS.
1139 The returned value is one of the following symbols:
1140 run  -- for a process that is running.
1141 stop -- for a process stopped but continuable.
1142 exit -- for a process that has exited.
1143 signal -- for a process that has got a fatal signal.
1144 open -- for a network stream connection that is open.
1145 listen -- for a network stream server that is listening.
1146 closed -- for a network stream connection that is closed.
1147 connect -- when waiting for a non-blocking connection to complete.
1148 failed -- when a non-blocking connection has failed.
1149 nil -- if arg is a process name and no such process exists.
1150 PROCESS may be a process, a buffer, the name of a process, or
1151 nil, indicating the current buffer's process.  */)
1152   (register Lisp_Object process)
1153 {
1154   register struct Lisp_Process *p;
1155   register Lisp_Object status;
1156 
1157   if (STRINGP (process))
1158     process = Fget_process (process);
1159   else
1160     process = get_process (process);
1161 
1162   if (NILP (process))
1163     return process;
1164 
1165   p = XPROCESS (process);
1166   if (p->raw_status_new)
1167     update_status (p);
1168   status = p->status;
1169   if (CONSP (status))
1170     status = XCAR (status);
1171   if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1172     {
1173       if (EQ (status, Qexit))
1174 	status = Qclosed;
1175       else if (EQ (p->command, Qt))
1176 	status = Qstop;
1177       else if (EQ (status, Qrun))
1178 	status = Qopen;
1179     }
1180   return status;
1181 }
1182 
1183 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1184        1, 1, 0,
1185        doc: /* Return the exit status of PROCESS or the signal number that killed it.
1186 If PROCESS has not yet exited or died, return 0.  */)
1187   (register Lisp_Object process)
1188 {
1189   CHECK_PROCESS (process);
1190   if (XPROCESS (process)->raw_status_new)
1191     update_status (XPROCESS (process));
1192   if (CONSP (XPROCESS (process)->status))
1193     return XCAR (XCDR (XPROCESS (process)->status));
1194   return make_fixnum (0);
1195 }
1196 
1197 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1198        doc: /* Return the process id of PROCESS.
1199 This is the pid of the external process which PROCESS uses or talks to.
1200 It is a fixnum if the value is small enough, otherwise a bignum.
1201 For a network, serial, and pipe connections, this value is nil.  */)
1202   (register Lisp_Object process)
1203 {
1204   pid_t pid;
1205 
1206   CHECK_PROCESS (process);
1207   pid = XPROCESS (process)->pid;
1208   return pid ? INT_TO_INTEGER (pid) : Qnil;
1209 }
1210 
1211 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1212        doc: /* Return the name of PROCESS, as a string.
1213 This is the name of the program invoked in PROCESS,
1214 possibly modified to make it unique among process names.  */)
1215   (register Lisp_Object process)
1216 {
1217   CHECK_PROCESS (process);
1218   return XPROCESS (process)->name;
1219 }
1220 
1221 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1222        doc: /* Return the command that was executed to start PROCESS.
1223 This is a list of strings, the first string being the program executed
1224 and the rest of the strings being the arguments given to it.
1225 For a network or serial or pipe connection, this is nil (process is running)
1226 or t (process is stopped).  */)
1227   (register Lisp_Object process)
1228 {
1229   CHECK_PROCESS (process);
1230   return XPROCESS (process)->command;
1231 }
1232 
1233 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1234        doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1235 This is the terminal that the process itself reads and writes on,
1236 not the name of the pty that Emacs uses to talk with that terminal.  */)
1237   (register Lisp_Object process)
1238 {
1239   CHECK_PROCESS (process);
1240   return XPROCESS (process)->tty_name;
1241 }
1242 
1243 static void
update_process_mark(struct Lisp_Process * p)1244 update_process_mark (struct Lisp_Process *p)
1245 {
1246   Lisp_Object buffer = p->buffer;
1247   if (BUFFERP (buffer))
1248     set_marker_both (p->mark, buffer,
1249 		     BUF_ZV (XBUFFER (buffer)),
1250 		     BUF_ZV_BYTE (XBUFFER (buffer)));
1251 }
1252 
1253 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1254        2, 2, 0,
1255        doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1256 Return BUFFER.  */)
1257   (register Lisp_Object process, Lisp_Object buffer)
1258 {
1259   struct Lisp_Process *p;
1260 
1261   CHECK_PROCESS (process);
1262   if (!NILP (buffer))
1263     CHECK_BUFFER (buffer);
1264   p = XPROCESS (process);
1265   if (!EQ (p->buffer, buffer))
1266     {
1267       pset_buffer (p, buffer);
1268       update_process_mark (p);
1269     }
1270   if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1271     pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1272   setup_process_coding_systems (process);
1273   return buffer;
1274 }
1275 
1276 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1277        1, 1, 0,
1278        doc: /* Return the buffer PROCESS is associated with.
1279 The default process filter inserts output from PROCESS into this buffer.  */)
1280   (register Lisp_Object process)
1281 {
1282   CHECK_PROCESS (process);
1283   return XPROCESS (process)->buffer;
1284 }
1285 
1286 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1287        1, 1, 0,
1288        doc: /* Return the marker for the end of the last output from PROCESS.  */)
1289   (register Lisp_Object process)
1290 {
1291   CHECK_PROCESS (process);
1292   return XPROCESS (process)->mark;
1293 }
1294 
1295 static void
set_process_filter_masks(struct Lisp_Process * p)1296 set_process_filter_masks (struct Lisp_Process *p)
1297 {
1298   if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1299     delete_read_fd (p->infd);
1300   else if (EQ (p->filter, Qt)
1301 	   /* Network or serial process not stopped:  */
1302 	   && !EQ (p->command, Qt))
1303     add_process_read_fd (p->infd);
1304 }
1305 
1306 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1307        2, 2, 0,
1308        doc: /* Give PROCESS the filter function FILTER; nil means default.
1309 A value of t means stop accepting output from the process.
1310 
1311 When a process has a non-default filter, its buffer is not used for output.
1312 Instead, each time it does output, the entire string of output is
1313 passed to the filter.
1314 
1315 The filter gets two arguments: the process and the string of output.
1316 The string argument is normally a multibyte string, except:
1317 - if the process's input coding system is no-conversion or raw-text,
1318   it is a unibyte string (the non-converted input).  */)
1319   (Lisp_Object process, Lisp_Object filter)
1320 {
1321   CHECK_PROCESS (process);
1322   struct Lisp_Process *p = XPROCESS (process);
1323 
1324   /* Don't signal an error if the process's input file descriptor
1325      is closed.  This could make debugging Lisp more difficult,
1326      for example when doing something like
1327 
1328      (setq process (start-process ...))
1329      (debug)
1330      (set-process-filter process ...)  */
1331 
1332   if (NILP (filter))
1333     filter = Qinternal_default_process_filter;
1334 
1335   if (p->infd >= 0)
1336     {
1337       /* If filter WILL be t, stop reading output.  */
1338       if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1339         delete_read_fd (p->infd);
1340       else if (/* If filter WAS t, then resume reading output.  */
1341                EQ (p->filter, Qt)
1342                /* Network or serial process not stopped:  */
1343                && !EQ (p->command, Qt))
1344         add_process_read_fd (p->infd);
1345     }
1346 
1347   pset_filter (p, filter);
1348 
1349   if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1350     pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1351   setup_process_coding_systems (process);
1352   return filter;
1353 }
1354 
1355 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1356        1, 1, 0,
1357        doc: /* Return the filter function of PROCESS.
1358 See `set-process-filter' for more info on filter functions.  */)
1359   (register Lisp_Object process)
1360 {
1361   CHECK_PROCESS (process);
1362   return XPROCESS (process)->filter;
1363 }
1364 
1365 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1366        2, 2, 0,
1367        doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1368 The sentinel is called as a function when the process changes state.
1369 It gets two arguments: the process, and a string describing the change.  */)
1370   (register Lisp_Object process, Lisp_Object sentinel)
1371 {
1372   struct Lisp_Process *p;
1373 
1374   CHECK_PROCESS (process);
1375   p = XPROCESS (process);
1376 
1377   if (NILP (sentinel))
1378     sentinel = Qinternal_default_process_sentinel;
1379 
1380   pset_sentinel (p, sentinel);
1381   if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1382     pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1383   return sentinel;
1384 }
1385 
1386 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1387        1, 1, 0,
1388        doc: /* Return the sentinel of PROCESS.
1389 See `set-process-sentinel' for more info on sentinels.  */)
1390   (register Lisp_Object process)
1391 {
1392   CHECK_PROCESS (process);
1393   return XPROCESS (process)->sentinel;
1394 }
1395 
1396 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1397        2, 2, 0,
1398        doc: /* Set the locking thread of PROCESS to be THREAD.
1399 If THREAD is nil, the process is unlocked.  */)
1400   (Lisp_Object process, Lisp_Object thread)
1401 {
1402   struct Lisp_Process *proc;
1403   struct thread_state *tstate;
1404 
1405   CHECK_PROCESS (process);
1406   if (NILP (thread))
1407     tstate = NULL;
1408   else
1409     {
1410       CHECK_THREAD (thread);
1411       tstate = XTHREAD (thread);
1412     }
1413 
1414   proc = XPROCESS (process);
1415   pset_thread (proc, thread);
1416   eassert (proc->infd < FD_SETSIZE);
1417   if (proc->infd >= 0)
1418     fd_callback_info[proc->infd].thread = tstate;
1419   eassert (proc->outfd < FD_SETSIZE);
1420   if (proc->outfd >= 0)
1421     fd_callback_info[proc->outfd].thread = tstate;
1422 
1423   return thread;
1424 }
1425 
1426 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1427        1, 1, 0,
1428        doc: /* Return the locking thread of PROCESS.
1429 If PROCESS is unlocked, this function returns nil.  */)
1430   (Lisp_Object process)
1431 {
1432   CHECK_PROCESS (process);
1433   return XPROCESS (process)->thread;
1434 }
1435 
1436 DEFUN ("set-process-window-size", Fset_process_window_size,
1437        Sset_process_window_size, 3, 3, 0,
1438        doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1439 Value is t if PROCESS was successfully told about the window size,
1440 nil otherwise.  */)
1441   (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1442 {
1443   CHECK_PROCESS (process);
1444 
1445   /* All known platforms store window sizes as 'unsigned short'.  */
1446   unsigned short h = check_uinteger_max (height, USHRT_MAX);
1447   unsigned short w = check_uinteger_max (width, USHRT_MAX);
1448 
1449   if (NETCONN_P (process)
1450       || XPROCESS (process)->infd < 0
1451       || set_window_size (XPROCESS (process)->infd, h, w) < 0)
1452     return Qnil;
1453   else
1454     return Qt;
1455 }
1456 
1457 DEFUN ("set-process-inherit-coding-system-flag",
1458        Fset_process_inherit_coding_system_flag,
1459        Sset_process_inherit_coding_system_flag, 2, 2, 0,
1460        doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1461 If the second argument FLAG is non-nil, then the variable
1462 `buffer-file-coding-system' of the buffer associated with PROCESS
1463 will be bound to the value of the coding system used to decode
1464 the process output.
1465 
1466 This is useful when the coding system specified for the process buffer
1467 leaves either the character code conversion or the end-of-line conversion
1468 unspecified, or if the coding system used to decode the process output
1469 is more appropriate for saving the process buffer.
1470 
1471 Binding the variable `inherit-process-coding-system' to non-nil before
1472 starting the process is an alternative way of setting the inherit flag
1473 for the process which will run.
1474 
1475 This function returns FLAG.  */)
1476   (register Lisp_Object process, Lisp_Object flag)
1477 {
1478   CHECK_PROCESS (process);
1479   XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1480   return flag;
1481 }
1482 
1483 DEFUN ("set-process-query-on-exit-flag",
1484        Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1485        2, 2, 0,
1486        doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1487 If the second argument FLAG is non-nil, Emacs will query the user before
1488 exiting or killing a buffer if PROCESS is running.  This function
1489 returns FLAG.  */)
1490   (register Lisp_Object process, Lisp_Object flag)
1491 {
1492   CHECK_PROCESS (process);
1493   XPROCESS (process)->kill_without_query = NILP (flag);
1494   return flag;
1495 }
1496 
1497 DEFUN ("process-query-on-exit-flag",
1498        Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1499        1, 1, 0,
1500        doc: /* Return the current value of query-on-exit flag for PROCESS.  */)
1501   (register Lisp_Object process)
1502 {
1503   CHECK_PROCESS (process);
1504   return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1505 }
1506 
1507 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1508        1, 3, 0,
1509        doc: /* Return the contact info of PROCESS; t for a real child.
1510 For a network or serial or pipe connection, the value depends on the
1511 optional KEY arg.  If KEY is nil, value is a cons cell of the form
1512 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1513 connection; it is t for a pipe connection.  If KEY is t, the complete
1514 contact information for the connection is returned, else the specific
1515 value for the keyword KEY is returned.  See `make-network-process',
1516 `make-serial-process', or `make-pipe-process' for the list of keywords.
1517 
1518 If PROCESS is a non-blocking network process that hasn't been fully
1519 set up yet, this function will block until socket setup has completed.
1520 If the optional NO-BLOCK parameter is specified, return nil instead of
1521 waiting for the process to be fully set up.*/)
1522   (Lisp_Object process, Lisp_Object key, Lisp_Object no_block)
1523 {
1524   Lisp_Object contact;
1525 
1526   CHECK_PROCESS (process);
1527   contact = XPROCESS (process)->childp;
1528 
1529 #ifdef DATAGRAM_SOCKETS
1530 
1531   if (NETCONN_P (process) && XPROCESS (process)->infd < 0)
1532     {
1533       /* Usually wait for the network process to finish being set
1534        * up. */
1535       if (!NILP (no_block))
1536 	return Qnil;
1537 
1538       wait_for_socket_fds (process, "process-contact");
1539     }
1540 
1541   if (DATAGRAM_CONN_P (process)
1542       && (EQ (key, Qt) || EQ (key, QCremote)))
1543     contact = Fplist_put (contact, QCremote,
1544 			  Fprocess_datagram_address (process));
1545 #endif
1546 
1547   if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1548       || EQ (key, Qt))
1549     return contact;
1550   if (NILP (key) && NETCONN_P (process))
1551     return list2 (Fplist_get (contact, QChost),
1552 		  Fplist_get (contact, QCservice));
1553   if (NILP (key) && SERIALCONN_P (process))
1554     return list2 (Fplist_get (contact, QCport),
1555 		  Fplist_get (contact, QCspeed));
1556   /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1557      if the pipe process is useful for purposes other than receiving
1558      stderr.  */
1559   if (NILP (key) && PIPECONN_P (process))
1560     return Qt;
1561   return Fplist_get (contact, key);
1562 }
1563 
1564 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1565        1, 1, 0,
1566        doc: /* Return the plist of PROCESS.  */)
1567   (register Lisp_Object process)
1568 {
1569   CHECK_PROCESS (process);
1570   return XPROCESS (process)->plist;
1571 }
1572 
1573 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1574        2, 2, 0,
1575        doc: /* Replace the plist of PROCESS with PLIST.  Return PLIST.  */)
1576   (Lisp_Object process, Lisp_Object plist)
1577 {
1578   CHECK_PROCESS (process);
1579   CHECK_LIST (plist);
1580 
1581   pset_plist (XPROCESS (process), plist);
1582   return plist;
1583 }
1584 
1585 #if 0 /* Turned off because we don't currently record this info
1586 	 in the process.  Perhaps add it.  */
1587 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1588        doc: /* Return the connection type of PROCESS.
1589 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1590 a socket connection.  */)
1591   (Lisp_Object process)
1592 {
1593   return XPROCESS (process)->type;
1594 }
1595 #endif
1596 
1597 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1598        doc: /* Return the connection type of PROCESS.
1599 The value is either the symbol `real', `network', `serial', or `pipe'.
1600 PROCESS may be a process, a buffer, the name of a process or buffer, or
1601 nil, indicating the current buffer's process.  */)
1602   (Lisp_Object process)
1603 {
1604   Lisp_Object proc;
1605   proc = get_process (process);
1606   return XPROCESS (proc)->type;
1607 }
1608 
1609 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1610        1, 2, 0,
1611        doc: /* Convert network ADDRESS from internal format to a string.
1612 A 4 or 5 element vector represents an IPv4 address (with port number).
1613 An 8 or 9 element vector represents an IPv6 address (with port number).
1614 If optional second argument OMIT-PORT is non-nil, don't include a port
1615 number in the string, even when present in ADDRESS.
1616 Return nil if format of ADDRESS is invalid.  */)
1617   (Lisp_Object address, Lisp_Object omit_port)
1618 {
1619   if (NILP (address))
1620     return Qnil;
1621 
1622   if (STRINGP (address))  /* AF_LOCAL */
1623     return address;
1624 
1625   if (VECTORP (address))  /* AF_INET or AF_INET6 */
1626     {
1627       register struct Lisp_Vector *p = XVECTOR (address);
1628       ptrdiff_t size = p->header.size;
1629       Lisp_Object args[10];
1630       int nargs, i;
1631       char const *format;
1632 
1633       if (size == 4 || (size == 5 && !NILP (omit_port)))
1634 	{
1635 	  format = "%d.%d.%d.%d";
1636 	  nargs = 4;
1637 	}
1638       else if (size == 5)
1639 	{
1640 	  format = "%d.%d.%d.%d:%d";
1641 	  nargs = 5;
1642 	}
1643       else if (size == 8 || (size == 9 && !NILP (omit_port)))
1644 	{
1645 	  format = "%x:%x:%x:%x:%x:%x:%x:%x";
1646 	  nargs = 8;
1647 	}
1648       else if (size == 9)
1649 	{
1650 	  format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1651 	  nargs = 9;
1652 	}
1653       else
1654 	return Qnil;
1655 
1656       AUTO_STRING (format_obj, format);
1657       args[0] = format_obj;
1658 
1659       for (i = 0; i < nargs; i++)
1660 	{
1661 	  if (! RANGED_FIXNUMP (0, p->contents[i], 65535))
1662 	    return Qnil;
1663 
1664 	  if (nargs <= 5         /* IPv4 */
1665 	      && i < 4           /* host, not port */
1666 	      && XFIXNUM (p->contents[i]) > 255)
1667 	    return Qnil;
1668 
1669 	  args[i + 1] = p->contents[i];
1670 	}
1671 
1672       return Fformat (nargs + 1, args);
1673     }
1674 
1675   if (CONSP (address))
1676     {
1677       AUTO_STRING (format, "<Family %d>");
1678       return CALLN (Fformat, format, Fcar (address));
1679     }
1680 
1681   return Qnil;
1682 }
1683 
1684 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1685        doc: /* Return a list of all processes that are Emacs sub-processes.  */)
1686   (void)
1687 {
1688   return Fmapcar (Qcdr, Vprocess_alist);
1689 }
1690 
1691 
1692 /* Starting asynchronous inferior processes.  */
1693 
1694 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1695        doc: /* Start a program in a subprocess.  Return the process object for it.
1696 
1697 This is similar to `start-process', but arguments are specified as
1698 keyword/argument pairs.  The following arguments are defined:
1699 
1700 :name NAME -- NAME is name for process.  It is modified if necessary
1701 to make it unique.
1702 
1703 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1704 with the process.  Process output goes at end of that buffer, unless
1705 you specify a filter function to handle the output.  BUFFER may be
1706 also nil, meaning that this process is not associated with any buffer.
1707 
1708 :command COMMAND -- COMMAND is a list starting with the program file
1709 name, followed by strings to give to the program as arguments.  If the
1710 program file name is not an absolute file name, `make-process' will
1711 look for the program file name in `exec-path' (which is a list of
1712 directories).
1713 
1714 :coding CODING -- If CODING is a symbol, it specifies the coding
1715 system used for both reading and writing for this process.  If CODING
1716 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1717 ENCODING is used for writing.
1718 
1719 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1720 the process is running.  If BOOL is not given, query before exiting.
1721 
1722 :stop BOOL -- BOOL must be nil.  The `:stop' key is ignored otherwise
1723 and is retained for compatibility with other process types such as
1724 pipe processes.  Asynchronous subprocesses never start in the
1725 `stopped' state.  Use `stop-process' and `continue-process' to send
1726 signals to stop and continue a process.
1727 
1728 :connection-type TYPE -- TYPE is control type of device used to
1729 communicate with subprocesses.  Values are `pipe' to use a pipe, `pty'
1730 to use a pty, or nil to use the default specified through
1731 `process-connection-type'.
1732 
1733 :filter FILTER -- Install FILTER as the process filter.
1734 
1735 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1736 
1737 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1738 to the standard error of subprocess.  Specifying this implies
1739 `:connection-type' is set to `pipe'.  If STDERR is nil, standard error
1740 is mixed with standard output and sent to BUFFER or FILTER.  (Note
1741 that specifying :stderr will create a new, separate (but associated)
1742 process, with its own filter and sentinel.  See
1743 Info node `(elisp) Asynchronous Processes' for more details.)
1744 
1745 :file-handler FILE-HANDLER -- If FILE-HANDLER is non-nil, then look
1746 for a file name handler for the current buffer's `default-directory'
1747 and invoke that file name handler to make the process.  If there is no
1748 such handler, proceed as if FILE-HANDLER were nil.
1749 
1750 usage: (make-process &rest ARGS)  */)
1751   (ptrdiff_t nargs, Lisp_Object *args)
1752 {
1753   Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1754   Lisp_Object xstderr, stderrproc;
1755   ptrdiff_t count = SPECPDL_INDEX ();
1756 
1757   if (nargs == 0)
1758     return Qnil;
1759 
1760   /* Save arguments for process-contact and clone-process.  */
1761   contact = Flist (nargs, args);
1762 
1763   if (!NILP (Fplist_get (contact, QCfile_handler)))
1764     {
1765       Lisp_Object file_handler
1766         = Ffind_file_name_handler (BVAR (current_buffer, directory),
1767                                    Qmake_process);
1768       if (!NILP (file_handler))
1769         return CALLN (Fapply, file_handler, Qmake_process, contact);
1770     }
1771 
1772   buffer = Fplist_get (contact, QCbuffer);
1773   if (!NILP (buffer))
1774     buffer = Fget_buffer_create (buffer, Qnil);
1775 
1776   /* Make sure that the child will be able to chdir to the current
1777      buffer's current directory, or its unhandled equivalent.  We
1778      can't just have the child check for an error when it does the
1779      chdir, since it's in a vfork.  */
1780   current_dir = get_current_directory (true);
1781 
1782   name = Fplist_get (contact, QCname);
1783   CHECK_STRING (name);
1784 
1785   command = Fplist_get (contact, QCcommand);
1786   if (CONSP (command))
1787     program = XCAR (command);
1788   else
1789     program = Qnil;
1790 
1791   if (!NILP (program))
1792     CHECK_STRING (program);
1793 
1794   bool query_on_exit = NILP (Fplist_get (contact, QCnoquery));
1795 
1796   stderrproc = Qnil;
1797   xstderr = Fplist_get (contact, QCstderr);
1798   if (PROCESSP (xstderr))
1799     {
1800       if (!PIPECONN_P (xstderr))
1801 	error ("Process is not a pipe process");
1802       stderrproc = xstderr;
1803     }
1804   else if (!NILP (xstderr))
1805     {
1806       CHECK_STRING (program);
1807       stderrproc = CALLN (Fmake_pipe_process,
1808 			  QCname,
1809 			  concat2 (name, build_string (" stderr")),
1810 			  QCbuffer,
1811 			  Fget_buffer_create (xstderr, Qnil),
1812 			  QCnoquery,
1813 			  query_on_exit ? Qnil : Qt);
1814     }
1815 
1816   proc = make_process (name);
1817   record_unwind_protect (start_process_unwind, proc);
1818 
1819   pset_childp (XPROCESS (proc), Qt);
1820   eassert (NILP (XPROCESS (proc)->plist));
1821   pset_type (XPROCESS (proc), Qreal);
1822   pset_buffer (XPROCESS (proc), buffer);
1823   pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1824   pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1825   pset_command (XPROCESS (proc), Fcopy_sequence (command));
1826 
1827   if (!query_on_exit)
1828     XPROCESS (proc)->kill_without_query = 1;
1829   tem = Fplist_get (contact, QCstop);
1830   /* Normal processes can't be started in a stopped state, see
1831      Bug#30460.  */
1832   CHECK_TYPE (NILP (tem), Qnull, tem);
1833 
1834   tem = Fplist_get (contact, QCconnection_type);
1835   if (EQ (tem, Qpty))
1836     XPROCESS (proc)->pty_flag = true;
1837   else if (EQ (tem, Qpipe))
1838     XPROCESS (proc)->pty_flag = false;
1839   else if (NILP (tem))
1840     XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1841   else
1842     report_file_error ("Unknown connection type", tem);
1843 
1844   if (!NILP (stderrproc))
1845     {
1846       pset_stderrproc (XPROCESS (proc), stderrproc);
1847 
1848       XPROCESS (proc)->pty_flag = false;
1849     }
1850 
1851 #ifdef HAVE_GNUTLS
1852   /* AKA GNUTLS_INITSTAGE(proc).  */
1853   verify (GNUTLS_STAGE_EMPTY == 0);
1854   eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1855   eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1856 #endif
1857 
1858   XPROCESS (proc)->adaptive_read_buffering
1859     = (NILP (Vprocess_adaptive_read_buffering) ? 0
1860        : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1861 
1862   /* Make the process marker point into the process buffer (if any).  */
1863   update_process_mark (XPROCESS (proc));
1864 
1865   USE_SAFE_ALLOCA;
1866 
1867   {
1868     /* Decide coding systems for communicating with the process.  Here
1869        we don't setup the structure coding_system nor pay attention to
1870        unibyte mode.  They are done in create_process.  */
1871 
1872     /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
1873     Lisp_Object coding_systems = Qt;
1874     Lisp_Object val, *args2;
1875 
1876     tem = Fplist_get (contact, QCcoding);
1877     if (!NILP (tem))
1878       {
1879 	val = tem;
1880 	if (CONSP (val))
1881 	  val = XCAR (val);
1882       }
1883     else
1884       val = Vcoding_system_for_read;
1885     if (NILP (val))
1886       {
1887 	ptrdiff_t nargs2 = 3 + list_length (command);
1888 	Lisp_Object tem2;
1889 	SAFE_ALLOCA_LISP (args2, nargs2);
1890 	ptrdiff_t i = 0;
1891 	args2[i++] = Qstart_process;
1892 	args2[i++] = name;
1893 	args2[i++] = buffer;
1894 	for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1895 	  args2[i++] = XCAR (tem2);
1896 	if (!NILP (program))
1897 	  coding_systems = Ffind_operation_coding_system (nargs2, args2);
1898 	if (CONSP (coding_systems))
1899 	  val = XCAR (coding_systems);
1900 	else if (CONSP (Vdefault_process_coding_system))
1901 	  val = XCAR (Vdefault_process_coding_system);
1902       }
1903     pset_decode_coding_system (XPROCESS (proc), val);
1904 
1905     if (!NILP (tem))
1906       {
1907 	val = tem;
1908 	if (CONSP (val))
1909 	  val = XCDR (val);
1910       }
1911     else
1912       val = Vcoding_system_for_write;
1913     if (NILP (val))
1914       {
1915 	if (EQ (coding_systems, Qt))
1916 	  {
1917 	    ptrdiff_t nargs2 = 3 + list_length (command);
1918 	    Lisp_Object tem2;
1919 	    SAFE_ALLOCA_LISP (args2, nargs2);
1920 	    ptrdiff_t i = 0;
1921 	    args2[i++] = Qstart_process;
1922 	    args2[i++] = name;
1923 	    args2[i++] = buffer;
1924 	    for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1925 	      args2[i++] = XCAR (tem2);
1926 	    if (!NILP (program))
1927 	      coding_systems = Ffind_operation_coding_system (nargs2, args2);
1928 	  }
1929 	if (CONSP (coding_systems))
1930 	  val = XCDR (coding_systems);
1931 	else if (CONSP (Vdefault_process_coding_system))
1932 	  val = XCDR (Vdefault_process_coding_system);
1933       }
1934     pset_encode_coding_system (XPROCESS (proc), val);
1935     /* Note: At this moment, the above coding system may leave
1936        text-conversion or eol-conversion unspecified.  They will be
1937        decided after we read output from the process and decode it by
1938        some coding system, or just before we actually send a text to
1939        the process.  */
1940   }
1941 
1942 
1943   pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1944   eassert (XPROCESS (proc)->decoding_carryover == 0);
1945   pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1946 
1947   XPROCESS (proc)->inherit_coding_system_flag
1948     = !(NILP (buffer) || !inherit_process_coding_system);
1949 
1950   if (!NILP (program))
1951     {
1952       Lisp_Object program_args = XCDR (command);
1953 
1954       /* If program file name is not absolute, search our path for it.
1955 	 Put the name we will really use in TEM.  */
1956       if (!IS_DIRECTORY_SEP (SREF (program, 0))
1957 	  && !(SCHARS (program) > 1
1958 	       && IS_DEVICE_SEP (SREF (program, 1))))
1959 	{
1960 	  tem = Qnil;
1961 	  openp (Vexec_path, program, Vexec_suffixes, &tem,
1962 		 make_fixnum (X_OK), false, false);
1963 	  if (NILP (tem))
1964 	    report_file_error ("Searching for program", program);
1965 	  tem = Fexpand_file_name (tem, Qnil);
1966 	}
1967       else
1968 	{
1969 	  if (!NILP (Ffile_directory_p (program)))
1970 	    error ("Specified program for new process is a directory");
1971 	  tem = program;
1972 	}
1973 
1974       /* Remove "/:" from TEM.  */
1975       tem = remove_slash_colon (tem);
1976 
1977       Lisp_Object arg_encoding = Qnil;
1978 
1979       /* Encode the file name and put it in NEW_ARGV.
1980 	 That's where the child will use it to execute the program.  */
1981       tem = list1 (ENCODE_FILE (tem));
1982       ptrdiff_t new_argc = 1;
1983 
1984       /* Here we encode arguments by the coding system used for sending
1985 	 data to the process.  We don't support using different coding
1986 	 systems for encoding arguments and for encoding data sent to the
1987 	 process.  */
1988 
1989       for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1990 	{
1991 	  Lisp_Object arg = XCAR (tem2);
1992 	  CHECK_STRING (arg);
1993 	  if (STRING_MULTIBYTE (arg))
1994 	    {
1995 	      if (NILP (arg_encoding))
1996 		arg_encoding = (complement_process_encoding_system
1997 				(XPROCESS (proc)->encode_coding_system));
1998 	      arg = code_convert_string_norecord (arg, arg_encoding, 1);
1999 	    }
2000 	  tem = Fcons (arg, tem);
2001 	  new_argc++;
2002 	}
2003 
2004       /* Now that everything is encoded we can collect the strings into
2005 	 NEW_ARGV.  */
2006       char **new_argv;
2007       SAFE_NALLOCA (new_argv, 1, new_argc + 1);
2008       new_argv[new_argc] = 0;
2009 
2010       for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
2011 	{
2012 	  new_argv[i] = SSDATA (XCAR (tem));
2013 	  tem = XCDR (tem);
2014 	}
2015 
2016       create_process (proc, new_argv, current_dir);
2017     }
2018   else
2019     create_pty (proc);
2020 
2021   return SAFE_FREE_UNBIND_TO (count, proc);
2022 }
2023 
2024 /* If PROC doesn't have its pid set, then an error was signaled and
2025    the process wasn't started successfully, so remove it.  */
2026 static void
start_process_unwind(Lisp_Object proc)2027 start_process_unwind (Lisp_Object proc)
2028 {
2029   if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
2030     remove_process (proc);
2031 }
2032 
2033 /* If *FD_ADDR is nonnegative, close it, and mark it as closed.  */
2034 
2035 static void
close_process_fd(int * fd_addr)2036 close_process_fd (int *fd_addr)
2037 {
2038   int fd = *fd_addr;
2039   if (0 <= fd)
2040     {
2041       *fd_addr = -1;
2042       emacs_close (fd);
2043     }
2044 }
2045 
2046 void
dissociate_controlling_tty(void)2047 dissociate_controlling_tty (void)
2048 {
2049   if (setsid () < 0)
2050     {
2051 #ifdef TIOCNOTTY
2052       /* Needed on Darwin after vfork, since setsid fails in a vforked
2053 	 child that has not execed.
2054 	 I wonder: would just ioctl (fd, TIOCNOTTY, 0) work here, for
2055 	 some fd that the caller already has?  */
2056       int ttyfd = emacs_open (DEV_TTY, O_RDWR, 0);
2057       if (0 <= ttyfd)
2058 	{
2059 	  ioctl (ttyfd, TIOCNOTTY, 0);
2060 	  emacs_close (ttyfd);
2061 	}
2062 #endif
2063     }
2064 }
2065 
2066 /* Indexes of file descriptors in open_fds.  */
2067 enum
2068   {
2069     /* The pipe from Emacs to its subprocess.  */
2070     SUBPROCESS_STDIN,
2071     WRITE_TO_SUBPROCESS,
2072 
2073     /* The main pipe from the subprocess to Emacs.  */
2074     READ_FROM_SUBPROCESS,
2075     SUBPROCESS_STDOUT,
2076 
2077     /* The pipe from the subprocess to Emacs that is closed when the
2078        subprocess execs.  */
2079     READ_FROM_EXEC_MONITOR,
2080     EXEC_MONITOR_OUTPUT
2081   };
2082 
2083 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
2084 
2085 static void
create_process(Lisp_Object process,char ** new_argv,Lisp_Object current_dir)2086 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
2087 {
2088   struct Lisp_Process *p = XPROCESS (process);
2089   int inchannel, outchannel;
2090   pid_t pid = -1;
2091   int vfork_errno;
2092   int forkin, forkout, forkerr = -1;
2093   bool pty_flag = 0;
2094   char pty_name[PTY_NAME_SIZE];
2095   Lisp_Object lisp_pty_name = Qnil;
2096   sigset_t oldset;
2097 
2098   /* Ensure that the SIGCHLD handler can notify
2099      `wait_reading_process_output'.  */
2100   child_signal_init ();
2101 
2102   inchannel = outchannel = -1;
2103 
2104   if (p->pty_flag)
2105     outchannel = inchannel = allocate_pty (pty_name);
2106 
2107   if (inchannel >= 0)
2108     {
2109       p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
2110 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2111       /* On most USG systems it does not work to open the pty's tty here,
2112 	 then close it and reopen it in the child.  */
2113       /* Don't let this terminal become our controlling terminal
2114 	 (in case we don't have one).  */
2115       forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2116       if (forkin < 0)
2117 	report_file_error ("Opening pty", Qnil);
2118       p->open_fd[SUBPROCESS_STDIN] = forkin;
2119 #else
2120       forkin = forkout = -1;
2121 #endif /* not USG, or USG_SUBTTY_WORKS */
2122       pty_flag = 1;
2123       lisp_pty_name = build_string (pty_name);
2124     }
2125   else
2126     {
2127       if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2128 	  || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2129 	report_file_error ("Creating pipe", Qnil);
2130       forkin = p->open_fd[SUBPROCESS_STDIN];
2131       outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2132       inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2133       forkout = p->open_fd[SUBPROCESS_STDOUT];
2134 
2135       if (!NILP (p->stderrproc))
2136 	{
2137 	  struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2138 
2139 	  forkerr = pp->open_fd[SUBPROCESS_STDOUT];
2140 
2141 	  /* Close unnecessary file descriptors.  */
2142 	  close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
2143 	  close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
2144 	}
2145     }
2146 
2147   if (FD_SETSIZE <= inchannel || FD_SETSIZE <= outchannel)
2148     report_file_errno ("Creating pipe", Qnil, EMFILE);
2149 
2150 #ifndef WINDOWSNT
2151   if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
2152     report_file_error ("Creating pipe", Qnil);
2153 #endif
2154 
2155   fcntl (inchannel, F_SETFL, O_NONBLOCK);
2156   fcntl (outchannel, F_SETFL, O_NONBLOCK);
2157 
2158   /* Record this as an active process, with its channels.  */
2159   eassert (0 <= inchannel && inchannel < FD_SETSIZE);
2160   chan_process[inchannel] = process;
2161   p->infd = inchannel;
2162   p->outfd = outchannel;
2163 
2164   /* Previously we recorded the tty descriptor used in the subprocess.
2165      It was only used for getting the foreground tty process, so now
2166      we just reopen the device (see emacs_get_tty_pgrp) as this is
2167      more portable (see USG_SUBTTY_WORKS above).  */
2168 
2169   p->pty_flag = pty_flag;
2170   pset_status (p, Qrun);
2171 
2172   if (!EQ (p->command, Qt)
2173       && !EQ (p->filter, Qt))
2174     add_process_read_fd (inchannel);
2175 
2176   ptrdiff_t count = SPECPDL_INDEX ();
2177 
2178   /* This may signal an error.  */
2179   setup_process_coding_systems (process);
2180   char **env = make_environment_block (current_dir);
2181 
2182   block_input ();
2183   block_child_signal (&oldset);
2184 
2185   pty_flag = p->pty_flag;
2186   eassert (pty_flag == ! NILP (lisp_pty_name));
2187 
2188   vfork_errno
2189     = emacs_spawn (&pid, forkin, forkout, forkerr, new_argv, env,
2190                    SSDATA (current_dir),
2191                    pty_flag ? SSDATA (lisp_pty_name) : NULL, &oldset);
2192 
2193   eassert ((vfork_errno == 0) == (0 < pid));
2194 
2195   p->pid = pid;
2196   if (pid >= 0)
2197     p->alive = 1;
2198 
2199   /* Stop blocking in the parent.  */
2200   unblock_child_signal (&oldset);
2201   unblock_input ();
2202 
2203   /* Environment block no longer needed.  */
2204   unbind_to (count, Qnil);
2205 
2206   if (pid < 0)
2207     report_file_errno (CHILD_SETUP_ERROR_DESC, Qnil, vfork_errno);
2208   else
2209     {
2210       /* vfork succeeded.  */
2211 
2212       /* Close the pipe ends that the child uses, or the child's pty.  */
2213       close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2214       close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2215 
2216 #ifdef WINDOWSNT
2217       register_child (pid, inchannel);
2218 #endif /* WINDOWSNT */
2219 
2220       pset_tty_name (p, lisp_pty_name);
2221 
2222 #ifndef WINDOWSNT
2223       /* Wait for child_setup to complete in case that vfork is
2224 	 actually defined as fork.  The descriptor
2225 	 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2226 	 of a pipe is closed at the child side either by close-on-exec
2227 	 on successful execve or the _exit call in child_setup.  */
2228       {
2229 	char dummy;
2230 
2231 	close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2232 	emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2233 	close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2234       }
2235 #endif
2236       if (!NILP (p->stderrproc))
2237 	{
2238 	  struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2239 	  close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2240 	}
2241     }
2242 }
2243 
2244 static void
create_pty(Lisp_Object process)2245 create_pty (Lisp_Object process)
2246 {
2247   struct Lisp_Process *p = XPROCESS (process);
2248   char pty_name[PTY_NAME_SIZE];
2249   int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2250 
2251   if (pty_fd >= 0)
2252     {
2253       p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2254       if (FD_SETSIZE <= pty_fd)
2255 	report_file_errno ("Opening pty", Qnil, EMFILE);
2256 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2257       /* On most USG systems it does not work to open the pty's tty here,
2258 	 then close it and reopen it in the child.  */
2259       /* Don't let this terminal become our controlling terminal
2260 	 (in case we don't have one).  */
2261       int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2262       if (forkout < 0)
2263 	report_file_error ("Opening pty", Qnil);
2264       p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2265 #if defined (DONT_REOPEN_PTY)
2266       /* In the case that vfork is defined as fork, the parent process
2267 	 (Emacs) may send some data before the child process completes
2268 	 tty options setup.  So we setup tty before forking.  */
2269       child_setup_tty (forkout);
2270 #endif /* DONT_REOPEN_PTY */
2271 #endif /* not USG, or USG_SUBTTY_WORKS */
2272 
2273       fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2274 
2275       /* Record this as an active process, with its channels.
2276 	 As a result, child_setup will close Emacs's side of the pipes.  */
2277       eassert (0 <= pty_fd && pty_fd < FD_SETSIZE);
2278       chan_process[pty_fd] = process;
2279       p->infd = pty_fd;
2280       p->outfd = pty_fd;
2281 
2282       /* Previously we recorded the tty descriptor used in the subprocess.
2283 	 It was only used for getting the foreground tty process, so now
2284 	 we just reopen the device (see emacs_get_tty_pgrp) as this is
2285 	 more portable (see USG_SUBTTY_WORKS above).  */
2286 
2287       p->pty_flag = 1;
2288       pset_status (p, Qrun);
2289       setup_process_coding_systems (process);
2290 
2291       if (!EQ (p->filter, Qt))
2292 	add_process_read_fd (pty_fd);
2293 
2294       pset_tty_name (p, build_string (pty_name));
2295     }
2296 
2297   p->pid = -2;
2298 }
2299 
2300 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2301        0, MANY, 0,
2302        doc: /* Create and return a bidirectional pipe process.
2303 
2304 In Emacs, pipes are represented by process objects, so input and
2305 output work as for subprocesses, and `delete-process' closes a pipe.
2306 However, a pipe process has no process id, it cannot be signaled,
2307 and the status codes are different from normal processes.
2308 
2309 Arguments are specified as keyword/argument pairs.  The following
2310 arguments are defined:
2311 
2312 :name NAME -- NAME is the name of the process.  It is modified if necessary to make it unique.
2313 
2314 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2315 with the process.  Process output goes at the end of that buffer,
2316 unless you specify a filter function to handle the output.  If BUFFER
2317 is not given, the value of NAME is used.
2318 
2319 :coding CODING -- If CODING is a symbol, it specifies the coding
2320 system used for both reading and writing for this process.  If CODING
2321 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2322 ENCODING is used for writing.
2323 
2324 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2325 the process is running.  If BOOL is not given, query before exiting.
2326 
2327 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2328 In the stopped state, a pipe process does not accept incoming data,
2329 but you can send outgoing data.  The stopped state is cleared by
2330 `continue-process' and set by `stop-process'.
2331 
2332 :filter FILTER -- Install FILTER as the process filter.
2333 
2334 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2335 
2336 usage:  (make-pipe-process &rest ARGS)  */)
2337   (ptrdiff_t nargs, Lisp_Object *args)
2338 {
2339   Lisp_Object proc, contact;
2340   struct Lisp_Process *p;
2341   Lisp_Object name, buffer;
2342   Lisp_Object tem;
2343   ptrdiff_t specpdl_count;
2344   int inchannel, outchannel;
2345 
2346   if (nargs == 0)
2347     return Qnil;
2348 
2349   contact = Flist (nargs, args);
2350 
2351   name = Fplist_get (contact, QCname);
2352   CHECK_STRING (name);
2353   proc = make_process (name);
2354   specpdl_count = SPECPDL_INDEX ();
2355   record_unwind_protect (remove_process, proc);
2356   p = XPROCESS (proc);
2357 
2358   if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2359       || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2360     report_file_error ("Creating pipe", Qnil);
2361   outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2362   inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2363 
2364   if (FD_SETSIZE <= inchannel || FD_SETSIZE <= outchannel)
2365     report_file_errno ("Creating pipe", Qnil, EMFILE);
2366 
2367   fcntl (inchannel, F_SETFL, O_NONBLOCK);
2368   fcntl (outchannel, F_SETFL, O_NONBLOCK);
2369 
2370 #ifdef WINDOWSNT
2371   register_aux_fd (inchannel);
2372 #endif
2373 
2374   /* Record this as an active process, with its channels.  */
2375   eassert (0 <= inchannel && inchannel < FD_SETSIZE);
2376   chan_process[inchannel] = proc;
2377   p->infd = inchannel;
2378   p->outfd = outchannel;
2379 
2380   if (inchannel > max_desc)
2381     max_desc = inchannel;
2382 
2383   buffer = Fplist_get (contact, QCbuffer);
2384   if (NILP (buffer))
2385     buffer = name;
2386   buffer = Fget_buffer_create (buffer, Qnil);
2387   pset_buffer (p, buffer);
2388 
2389   pset_childp (p, contact);
2390   pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2391   pset_type (p, Qpipe);
2392   pset_sentinel (p, Fplist_get (contact, QCsentinel));
2393   pset_filter (p, Fplist_get (contact, QCfilter));
2394   eassert (NILP (p->log));
2395   if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2396     p->kill_without_query = 1;
2397   if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2398     pset_command (p, Qt);
2399   eassert (! p->pty_flag);
2400 
2401   if (!EQ (p->command, Qt)
2402       && !EQ (p->filter, Qt))
2403     add_process_read_fd (inchannel);
2404   p->adaptive_read_buffering
2405     = (NILP (Vprocess_adaptive_read_buffering) ? 0
2406        : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2407 
2408   /* Make the process marker point into the process buffer (if any).  */
2409   update_process_mark (p);
2410 
2411   {
2412     /* Setup coding systems for communicating with the network stream.  */
2413 
2414     /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
2415     Lisp_Object coding_systems = Qt;
2416     Lisp_Object val;
2417 
2418     tem = Fplist_get (contact, QCcoding);
2419     val = Qnil;
2420     if (!NILP (tem))
2421       {
2422 	val = tem;
2423 	if (CONSP (val))
2424 	  val = XCAR (val);
2425       }
2426     else if (!NILP (Vcoding_system_for_read))
2427       val = Vcoding_system_for_read;
2428     else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2429 	     || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2430       /* We dare not decode end-of-line format by setting VAL to
2431 	 Qraw_text, because the existing Emacs Lisp libraries
2432 	 assume that they receive bare code including a sequence of
2433 	 CR LF.  */
2434       val = Qnil;
2435     else
2436       {
2437 	if (CONSP (coding_systems))
2438 	  val = XCAR (coding_systems);
2439 	else if (CONSP (Vdefault_process_coding_system))
2440 	  val = XCAR (Vdefault_process_coding_system);
2441 	else
2442 	  val = Qnil;
2443       }
2444     pset_decode_coding_system (p, val);
2445 
2446     if (!NILP (tem))
2447       {
2448 	val = tem;
2449 	if (CONSP (val))
2450 	  val = XCDR (val);
2451       }
2452     else if (!NILP (Vcoding_system_for_write))
2453       val = Vcoding_system_for_write;
2454     else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2455       val = Qnil;
2456     else
2457       {
2458 	if (CONSP (coding_systems))
2459 	  val = XCDR (coding_systems);
2460 	else if (CONSP (Vdefault_process_coding_system))
2461 	  val = XCDR (Vdefault_process_coding_system);
2462 	else
2463 	  val = Qnil;
2464       }
2465     pset_encode_coding_system (p, val);
2466   }
2467   /* This may signal an error.  */
2468   setup_process_coding_systems (proc);
2469 
2470   pset_decoding_buf (p, empty_unibyte_string);
2471   eassert (p->decoding_carryover == 0);
2472   pset_encoding_buf (p, empty_unibyte_string);
2473 
2474   specpdl_ptr = specpdl + specpdl_count;
2475 
2476   return proc;
2477 }
2478 
2479 
2480 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2481    The address family of sa is not included in the result.  */
2482 
2483 Lisp_Object
conv_sockaddr_to_lisp(struct sockaddr * sa,ptrdiff_t len)2484 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2485 {
2486   Lisp_Object address;
2487   unsigned char *cp;
2488   struct Lisp_Vector *p;
2489 
2490   /* Workaround for a bug in getsockname on BSD: Names bound to
2491      sockets in the UNIX domain are inaccessible; getsockname returns
2492      a zero length name.  */
2493   if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2494     return empty_unibyte_string;
2495 
2496   switch (sa->sa_family)
2497     {
2498     case AF_INET:
2499       {
2500 	DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2501 	len = sizeof (sin->sin_addr) + 1;
2502 	address = make_uninit_vector (len);
2503 	p = XVECTOR (address);
2504 	p->contents[--len] = make_fixnum (ntohs (sin->sin_port));
2505 	cp = (unsigned char *) &sin->sin_addr;
2506 	break;
2507       }
2508 #ifdef AF_INET6
2509     case AF_INET6:
2510       {
2511 	DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2512 	DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2513 	len = sizeof (sin6->sin6_addr) / 2 + 1;
2514 	address = make_uninit_vector (len);
2515 	p = XVECTOR (address);
2516 	p->contents[--len] = make_fixnum (ntohs (sin6->sin6_port));
2517 	for (ptrdiff_t i = 0; i < len; i++)
2518 	  p->contents[i] = make_fixnum (ntohs (ip6[i]));
2519 	return address;
2520       }
2521 #endif
2522 #ifdef HAVE_LOCAL_SOCKETS
2523     case AF_LOCAL:
2524       {
2525 	DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2526         ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2527         /* If the first byte is NUL, the name is a Linux abstract
2528            socket name, and the name can contain embedded NULs.  If
2529            it's not, we have a NUL-terminated string.  Be careful not
2530            to walk past the end of the object looking for the name
2531            terminator, however.  */
2532         if (name_length > 0 && sockun->sun_path[0] != '\0')
2533           {
2534             const char *terminator
2535 	      = memchr (sockun->sun_path, '\0', name_length);
2536 
2537             if (terminator)
2538               name_length = terminator - (const char *) sockun->sun_path;
2539           }
2540 
2541 	return make_unibyte_string (sockun->sun_path, name_length);
2542       }
2543 #endif
2544     default:
2545       len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2546       address = Fcons (make_fixnum (sa->sa_family), make_nil_vector (len));
2547       p = XVECTOR (XCDR (address));
2548       cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2549       break;
2550     }
2551 
2552   for (ptrdiff_t i = 0; i < len; i++)
2553     p->contents[i] = make_fixnum (*cp++);
2554 
2555   return address;
2556 }
2557 
2558 /* Convert an internal struct addrinfo to a Lisp object.  */
2559 
2560 static Lisp_Object
conv_addrinfo_to_lisp(struct addrinfo * res)2561 conv_addrinfo_to_lisp (struct addrinfo *res)
2562 {
2563   Lisp_Object protocol = make_fixnum (res->ai_protocol);
2564   eassert (XFIXNUM (protocol) == res->ai_protocol);
2565   return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2566 }
2567 
2568 
2569 /* Get family and required size for sockaddr structure to hold ADDRESS.  */
2570 
2571 static ptrdiff_t
get_lisp_to_sockaddr_size(Lisp_Object address,int * familyp)2572 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2573 {
2574   struct Lisp_Vector *p;
2575 
2576   if (VECTORP (address))
2577     {
2578       p = XVECTOR (address);
2579       if (p->header.size == 5)
2580 	{
2581 	  *familyp = AF_INET;
2582 	  return sizeof (struct sockaddr_in);
2583 	}
2584 #ifdef AF_INET6
2585       else if (p->header.size == 9)
2586 	{
2587 	  *familyp = AF_INET6;
2588 	  return sizeof (struct sockaddr_in6);
2589 	}
2590 #endif
2591     }
2592 #ifdef HAVE_LOCAL_SOCKETS
2593   else if (STRINGP (address))
2594     {
2595       *familyp = AF_LOCAL;
2596       return sizeof (struct sockaddr_un);
2597     }
2598 #endif
2599   else if (CONSP (address) && TYPE_RANGED_FIXNUMP (int, XCAR (address))
2600 	   && VECTORP (XCDR (address)))
2601     {
2602       struct sockaddr *sa;
2603       p = XVECTOR (XCDR (address));
2604       if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2605 	return 0;
2606       *familyp = XFIXNUM (XCAR (address));
2607       return p->header.size + sizeof (sa->sa_family);
2608     }
2609   return 0;
2610 }
2611 
2612 /* Convert an address object (vector or string) to an internal sockaddr.
2613 
2614    The address format has been basically validated by
2615    get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2616    it could have come from user data.  So if FAMILY is not valid,
2617    we return after zeroing *SA.  */
2618 
2619 static void
conv_lisp_to_sockaddr(int family,Lisp_Object address,struct sockaddr * sa,int len)2620 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2621 {
2622   register struct Lisp_Vector *p;
2623   register unsigned char *cp = NULL;
2624   register int i;
2625   EMACS_INT hostport;
2626 
2627   memset (sa, 0, len);
2628 
2629   if (VECTORP (address))
2630     {
2631       p = XVECTOR (address);
2632       if (family == AF_INET)
2633 	{
2634 	  DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2635 	  len = sizeof (sin->sin_addr) + 1;
2636 	  hostport = XFIXNUM (p->contents[--len]);
2637 	  sin->sin_port = htons (hostport);
2638 	  cp = (unsigned char *)&sin->sin_addr;
2639 	  sa->sa_family = family;
2640 	}
2641 #ifdef AF_INET6
2642       else if (family == AF_INET6)
2643 	{
2644 	  DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2645 	  DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2646 	  len = sizeof (sin6->sin6_addr) / 2 + 1;
2647 	  hostport = XFIXNUM (p->contents[--len]);
2648 	  sin6->sin6_port = htons (hostport);
2649 	  for (i = 0; i < len; i++)
2650 	    if (FIXNUMP (p->contents[i]))
2651 	      {
2652 		int j = XFIXNUM (p->contents[i]) & 0xffff;
2653 		ip6[i] = ntohs (j);
2654 	      }
2655 	  sa->sa_family = family;
2656 	  return;
2657 	}
2658 #endif
2659       else
2660 	return;
2661     }
2662   else if (STRINGP (address))
2663     {
2664 #ifdef HAVE_LOCAL_SOCKETS
2665       if (family == AF_LOCAL)
2666 	{
2667 	  DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2668 	  cp = SDATA (address);
2669 	  for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2670 	    sockun->sun_path[i] = *cp++;
2671 	  sa->sa_family = family;
2672 	}
2673 #endif
2674       return;
2675     }
2676   else
2677     {
2678       p = XVECTOR (XCDR (address));
2679       cp = (unsigned char *)sa + sizeof (sa->sa_family);
2680     }
2681 
2682   for (i = 0; i < len; i++)
2683     if (FIXNUMP (p->contents[i]))
2684       *cp++ = XFIXNAT (p->contents[i]) & 0xff;
2685 }
2686 
2687 #ifdef DATAGRAM_SOCKETS
2688 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2689        1, 1, 0,
2690        doc: /* Get the current datagram address associated with PROCESS.
2691 If PROCESS is a non-blocking network process that hasn't been fully
2692 set up yet, this function will block until socket setup has completed.  */)
2693   (Lisp_Object process)
2694 {
2695   int channel;
2696 
2697   CHECK_PROCESS (process);
2698 
2699   if (NETCONN_P (process))
2700     wait_for_socket_fds (process, "process-datagram-address");
2701 
2702   if (!DATAGRAM_CONN_P (process))
2703     return Qnil;
2704 
2705   channel = XPROCESS (process)->infd;
2706   eassert (0 <= channel && channel < FD_SETSIZE);
2707   return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2708 				datagram_address[channel].len);
2709 }
2710 
2711 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2712        2, 2, 0,
2713        doc: /* Set the datagram address for PROCESS to ADDRESS.
2714 Return nil upon error setting address, ADDRESS otherwise.
2715 
2716 If PROCESS is a non-blocking network process that hasn't been fully
2717 set up yet, this function will block until socket setup has completed.  */)
2718   (Lisp_Object process, Lisp_Object address)
2719 {
2720   int channel;
2721   int family;
2722   ptrdiff_t len;
2723 
2724   CHECK_PROCESS (process);
2725 
2726   if (NETCONN_P (process))
2727     wait_for_socket_fds (process, "set-process-datagram-address");
2728 
2729   if (!DATAGRAM_CONN_P (process))
2730     return Qnil;
2731 
2732   channel = XPROCESS (process)->infd;
2733 
2734   len = get_lisp_to_sockaddr_size (address, &family);
2735   eassert (0 <= channel && channel < FD_SETSIZE);
2736   if (len == 0 || datagram_address[channel].len != len)
2737     return Qnil;
2738   conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2739   return address;
2740 }
2741 #endif
2742 
2743 
2744 static const struct socket_options {
2745   /* The name of this option.  Should be lowercase version of option
2746      name without SO_ prefix.  */
2747   const char *name;
2748   /* Option level SOL_...  */
2749   int optlevel;
2750   /* Option number SO_...  */
2751   int optnum;
2752   enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2753   enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2754 } socket_options[] =
2755   {
2756 #ifdef SO_BINDTODEVICE
2757     { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2758 #endif
2759 #ifdef SO_BROADCAST
2760     { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2761 #endif
2762 #ifdef SO_DONTROUTE
2763     { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2764 #endif
2765 #ifdef SO_KEEPALIVE
2766     { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2767 #endif
2768 #ifdef SO_LINGER
2769     { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2770 #endif
2771 #ifdef SO_OOBINLINE
2772     { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2773 #endif
2774 #ifdef SO_PRIORITY
2775     { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2776 #endif
2777 #ifdef SO_REUSEADDR
2778     { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2779 #endif
2780     { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2781   };
2782 
2783 /* Set option OPT to value VAL on socket S.
2784 
2785    Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2786    Signals an error if setting a known option fails.
2787 */
2788 
2789 static int
set_socket_option(int s,Lisp_Object opt,Lisp_Object val)2790 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2791 {
2792   char *name;
2793   const struct socket_options *sopt;
2794   int ret = 0;
2795 
2796   CHECK_SYMBOL (opt);
2797 
2798   name = SSDATA (SYMBOL_NAME (opt));
2799   for (sopt = socket_options; sopt->name; sopt++)
2800     if (strcmp (name, sopt->name) == 0)
2801       break;
2802 
2803   switch (sopt->opttype)
2804     {
2805     case SOPT_BOOL:
2806       {
2807 	int optval;
2808 	optval = NILP (val) ? 0 : 1;
2809 	ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2810 			  &optval, sizeof (optval));
2811 	break;
2812       }
2813 
2814     case SOPT_INT:
2815       {
2816 	int optval;
2817 	if (TYPE_RANGED_FIXNUMP (int, val))
2818 	  optval = XFIXNUM (val);
2819 	else
2820 	  error ("Bad option value for %s", name);
2821 	ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2822 			  &optval, sizeof (optval));
2823 	break;
2824       }
2825 
2826 #ifdef SO_BINDTODEVICE
2827     case SOPT_IFNAME:
2828       {
2829 	char devname[IFNAMSIZ + 1];
2830 
2831 	/* This is broken, at least in the Linux 2.4 kernel.
2832 	   To unbind, the arg must be a zero integer, not the empty string.
2833 	   This should work on all systems.   KFS. 2003-09-23.  */
2834 	memset (devname, 0, sizeof devname);
2835 	if (STRINGP (val))
2836 	  memcpy (devname, SDATA (val), min (SBYTES (val), IFNAMSIZ));
2837 	else if (!NILP (val))
2838 	  error ("Bad option value for %s", name);
2839 	ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2840 			  devname, IFNAMSIZ);
2841 	break;
2842       }
2843 #endif
2844 
2845 #ifdef SO_LINGER
2846     case SOPT_LINGER:
2847       {
2848 	struct linger linger;
2849 
2850 	linger.l_onoff = 1;
2851 	linger.l_linger = 0;
2852 	if (TYPE_RANGED_FIXNUMP (int, val))
2853 	  linger.l_linger = XFIXNUM (val);
2854 	else
2855 	  linger.l_onoff = NILP (val) ? 0 : 1;
2856 	ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2857 			  &linger, sizeof (linger));
2858 	break;
2859       }
2860 #endif
2861 
2862     default:
2863       return 0;
2864     }
2865 
2866   if (ret < 0)
2867     {
2868       int setsockopt_errno = errno;
2869       report_file_errno ("Cannot set network option", list2 (opt, val),
2870 			 setsockopt_errno);
2871     }
2872 
2873   return (1 << sopt->optbit);
2874 }
2875 
2876 
2877 DEFUN ("set-network-process-option",
2878        Fset_network_process_option, Sset_network_process_option,
2879        3, 4, 0,
2880        doc: /* For network process PROCESS set option OPTION to value VALUE.
2881 See `make-network-process' for a list of options and values.
2882 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2883 OPTION is not a supported option, return nil instead; otherwise return t.
2884 
2885 If PROCESS is a non-blocking network process that hasn't been fully
2886 set up yet, this function will block until socket setup has completed. */)
2887   (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2888 {
2889   int s;
2890   struct Lisp_Process *p;
2891 
2892   CHECK_PROCESS (process);
2893   p = XPROCESS (process);
2894   if (!NETCONN1_P (p))
2895     error ("Process is not a network process");
2896 
2897   wait_for_socket_fds (process, "set-network-process-option");
2898 
2899   s = p->infd;
2900   if (s < 0)
2901     error ("Process is not running");
2902 
2903   if (set_socket_option (s, option, value))
2904     {
2905       pset_childp (p, Fplist_put (p->childp, option, value));
2906       return Qt;
2907     }
2908 
2909   if (NILP (no_error))
2910     error ("Unknown or unsupported option");
2911 
2912   return Qnil;
2913 }
2914 
2915 
2916 DEFUN ("serial-process-configure",
2917        Fserial_process_configure,
2918        Sserial_process_configure,
2919        0, MANY, 0,
2920        doc: /* Configure speed, bytesize, etc. of a serial process.
2921 
2922 Arguments are specified as keyword/argument pairs.  Attributes that
2923 are not given are re-initialized from the process's current
2924 configuration (available via the function `process-contact') or set to
2925 reasonable default values.  The following arguments are defined:
2926 
2927 :process PROCESS
2928 :name NAME
2929 :buffer BUFFER
2930 :port PORT
2931 -- Any of these arguments can be given to identify the process that is
2932 to be configured.  If none of these arguments is given, the current
2933 buffer's process is used.
2934 
2935 :speed SPEED -- SPEED is the speed of the serial port in bits per
2936 second, also called baud rate.  Any value can be given for SPEED, but
2937 most serial ports work only at a few defined values between 1200 and
2938 115200, with 9600 being the most common value.  If SPEED is nil, the
2939 serial port is not configured any further, i.e., all other arguments
2940 are ignored.  This may be useful for special serial ports such as
2941 Bluetooth-to-serial converters which can only be configured through AT
2942 commands.  A value of nil for SPEED can be used only when passed
2943 through `make-serial-process' or `serial-term'.
2944 
2945 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2946 can be 7 or 8.  If BYTESIZE is not given or nil, a value of 8 is used.
2947 
2948 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2949 `odd' (use odd parity), or the symbol `even' (use even parity).  If
2950 PARITY is not given, no parity is used.
2951 
2952 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2953 terminate a byte transmission.  STOPBITS can be 1 or 2.  If STOPBITS
2954 is not given or nil, 1 stopbit is used.
2955 
2956 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2957 flowcontrol to be used, which is either nil (don't use flowcontrol),
2958 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2959 \(use XON/XOFF software flowcontrol).  If FLOWCONTROL is not given, no
2960 flowcontrol is used.
2961 
2962 `serial-process-configure' is called by `make-serial-process' for the
2963 initial configuration of the serial port.
2964 
2965 Examples:
2966 
2967 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2968 
2969 \(serial-process-configure
2970     :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2971 
2972 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2973 
2974 usage: (serial-process-configure &rest ARGS)  */)
2975   (ptrdiff_t nargs, Lisp_Object *args)
2976 {
2977   struct Lisp_Process *p;
2978   Lisp_Object contact = Qnil;
2979   Lisp_Object proc = Qnil;
2980 
2981   contact = Flist (nargs, args);
2982 
2983   proc = Fplist_get (contact, QCprocess);
2984   if (NILP (proc))
2985     proc = Fplist_get (contact, QCname);
2986   if (NILP (proc))
2987     proc = Fplist_get (contact, QCbuffer);
2988   if (NILP (proc))
2989     proc = Fplist_get (contact, QCport);
2990   proc = get_process (proc);
2991   p = XPROCESS (proc);
2992   if (!EQ (p->type, Qserial))
2993     error ("Not a serial process");
2994 
2995   if (NILP (Fplist_get (p->childp, QCspeed)))
2996     return Qnil;
2997 
2998   serial_configure (p, contact);
2999   return Qnil;
3000 }
3001 
3002 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
3003        0, MANY, 0,
3004        doc: /* Create and return a serial port process.
3005 
3006 In Emacs, serial port connections are represented by process objects,
3007 so input and output work as for subprocesses, and `delete-process'
3008 closes a serial port connection.  However, a serial process has no
3009 process id, it cannot be signaled, and the status codes are different
3010 from normal processes.
3011 
3012 `make-serial-process' creates a process and a buffer, on which you
3013 probably want to use `process-send-string'.  Try \\[serial-term] for
3014 an interactive terminal.  See below for examples.
3015 
3016 Arguments are specified as keyword/argument pairs.  The following
3017 arguments are defined:
3018 
3019 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3020 For example, this could be "/dev/ttyS0" on Unix.  On Windows, this
3021 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3022 the backslashes in strings).
3023 
3024 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3025 which this function calls.
3026 
3027 :name NAME -- NAME is the name of the process.  If NAME is not given,
3028 the value of PORT is used.
3029 
3030 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3031 with the process.  Process output goes at the end of that buffer,
3032 unless you specify a filter function to handle the output.  If BUFFER
3033 is not given, the value of NAME is used.
3034 
3035 :coding CODING -- If CODING is a symbol, it specifies the coding
3036 system used for both reading and writing for this process.  If CODING
3037 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3038 ENCODING is used for writing.
3039 
3040 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3041 the process is running.  If BOOL is not given, query before exiting.
3042 
3043 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3044 In the stopped state, a serial process does not accept incoming data,
3045 but you can send outgoing data.  The stopped state is cleared by
3046 `continue-process' and set by `stop-process'.
3047 
3048 :filter FILTER -- Install FILTER as the process filter.
3049 
3050 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3051 
3052 :plist PLIST -- Install PLIST as the initial plist of the process.
3053 
3054 :bytesize
3055 :parity
3056 :stopbits
3057 :flowcontrol
3058 -- This function calls `serial-process-configure' to handle these
3059 arguments.
3060 
3061 The original argument list, possibly modified by later configuration,
3062 is available via the function `process-contact'.
3063 
3064 Examples:
3065 
3066 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3067 
3068 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3069 
3070 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3071 
3072 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3073 
3074 usage:  (make-serial-process &rest ARGS)  */)
3075   (ptrdiff_t nargs, Lisp_Object *args)
3076 {
3077   int fd = -1;
3078   Lisp_Object proc, contact, port;
3079   struct Lisp_Process *p;
3080   Lisp_Object name, buffer;
3081   Lisp_Object tem, val;
3082   ptrdiff_t specpdl_count;
3083 
3084   if (nargs == 0)
3085     return Qnil;
3086 
3087   contact = Flist (nargs, args);
3088 
3089   port = Fplist_get (contact, QCport);
3090   if (NILP (port))
3091     error ("No port specified");
3092   CHECK_STRING (port);
3093 
3094   if (NILP (Fplist_member (contact, QCspeed)))
3095     error (":speed not specified");
3096   if (!NILP (Fplist_get (contact, QCspeed)))
3097     CHECK_FIXNUM (Fplist_get (contact, QCspeed));
3098 
3099   name = Fplist_get (contact, QCname);
3100   if (NILP (name))
3101     name = port;
3102   CHECK_STRING (name);
3103   proc = make_process (name);
3104   specpdl_count = SPECPDL_INDEX ();
3105   record_unwind_protect (remove_process, proc);
3106   p = XPROCESS (proc);
3107 
3108   fd = serial_open (port);
3109   p->open_fd[SUBPROCESS_STDIN] = fd;
3110   if (FD_SETSIZE <= fd)
3111     report_file_errno ("Opening serial port", port, EMFILE);
3112   p->infd = fd;
3113   p->outfd = fd;
3114   if (fd > max_desc)
3115     max_desc = fd;
3116   eassert (0 <= fd && fd < FD_SETSIZE);
3117   chan_process[fd] = proc;
3118 
3119   buffer = Fplist_get (contact, QCbuffer);
3120   if (NILP (buffer))
3121     buffer = name;
3122   buffer = Fget_buffer_create (buffer, Qnil);
3123   pset_buffer (p, buffer);
3124 
3125   pset_childp (p, contact);
3126   pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3127   pset_type (p, Qserial);
3128   pset_sentinel (p, Fplist_get (contact, QCsentinel));
3129   pset_filter (p, Fplist_get (contact, QCfilter));
3130   eassert (NILP (p->log));
3131   if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3132     p->kill_without_query = 1;
3133   if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3134     pset_command (p, Qt);
3135   eassert (! p->pty_flag);
3136 
3137   if (!EQ (p->command, Qt)
3138       && !EQ (p->filter, Qt))
3139     add_process_read_fd (fd);
3140 
3141   update_process_mark (p);
3142 
3143   tem = Fplist_get (contact, QCcoding);
3144 
3145   val = Qnil;
3146   if (!NILP (tem))
3147     {
3148       val = tem;
3149       if (CONSP (val))
3150 	val = XCAR (val);
3151     }
3152   else if (!NILP (Vcoding_system_for_read))
3153     val = Vcoding_system_for_read;
3154   else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3155 	   || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3156     val = Qnil;
3157   pset_decode_coding_system (p, val);
3158 
3159   val = Qnil;
3160   if (!NILP (tem))
3161     {
3162       val = tem;
3163       if (CONSP (val))
3164 	val = XCDR (val);
3165     }
3166   else if (!NILP (Vcoding_system_for_write))
3167     val = Vcoding_system_for_write;
3168   else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3169 	   || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3170     val = Qnil;
3171   pset_encode_coding_system (p, val);
3172 
3173   setup_process_coding_systems (proc);
3174   pset_decoding_buf (p, empty_unibyte_string);
3175   eassert (p->decoding_carryover == 0);
3176   pset_encoding_buf (p, empty_unibyte_string);
3177   p->inherit_coding_system_flag
3178     = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3179 
3180   Fserial_process_configure (nargs, args);
3181 
3182   specpdl_ptr = specpdl + specpdl_count;
3183 
3184   return proc;
3185 }
3186 
3187 static void
set_network_socket_coding_system(Lisp_Object proc,Lisp_Object host,Lisp_Object service,Lisp_Object name)3188 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
3189 				  Lisp_Object service, Lisp_Object name)
3190 {
3191   Lisp_Object tem;
3192   struct Lisp_Process *p = XPROCESS (proc);
3193   Lisp_Object contact = p->childp;
3194   Lisp_Object coding_systems = Qt;
3195   Lisp_Object val;
3196 
3197   tem = Fplist_get (contact, QCcoding);
3198 
3199   /* Setup coding systems for communicating with the network stream.  */
3200   /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
3201 
3202   if (!NILP (tem))
3203     {
3204       val = tem;
3205       if (CONSP (val))
3206 	val = XCAR (val);
3207     }
3208   else if (!NILP (Vcoding_system_for_read))
3209     val = Vcoding_system_for_read;
3210   else if ((!NILP (p->buffer)
3211 	    && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3212 	   || (NILP (p->buffer)
3213 	       && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3214     /* We dare not decode end-of-line format by setting VAL to
3215        Qraw_text, because the existing Emacs Lisp libraries
3216        assume that they receive bare code including a sequence of
3217        CR LF.  */
3218     val = Qnil;
3219   else
3220     {
3221       if (NILP (host) || NILP (service))
3222 	coding_systems = Qnil;
3223       else
3224 	coding_systems = CALLN (Ffind_operation_coding_system,
3225 				Qopen_network_stream, name, p->buffer,
3226 				host, service);
3227       if (CONSP (coding_systems))
3228 	val = XCAR (coding_systems);
3229       else if (CONSP (Vdefault_process_coding_system))
3230 	val = XCAR (Vdefault_process_coding_system);
3231       else
3232 	val = Qnil;
3233     }
3234   pset_decode_coding_system (p, val);
3235 
3236   if (!NILP (tem))
3237     {
3238       val = tem;
3239       if (CONSP (val))
3240 	val = XCDR (val);
3241     }
3242   else if (!NILP (Vcoding_system_for_write))
3243     val = Vcoding_system_for_write;
3244   else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3245     val = Qnil;
3246   else
3247     {
3248       if (EQ (coding_systems, Qt))
3249 	{
3250 	  if (NILP (host) || NILP (service))
3251 	    coding_systems = Qnil;
3252 	  else
3253 	    coding_systems = CALLN (Ffind_operation_coding_system,
3254 				    Qopen_network_stream, name, p->buffer,
3255 				    host, service);
3256 	}
3257       if (CONSP (coding_systems))
3258 	val = XCDR (coding_systems);
3259       else if (CONSP (Vdefault_process_coding_system))
3260 	val = XCDR (Vdefault_process_coding_system);
3261       else
3262 	val = Qnil;
3263     }
3264   pset_encode_coding_system (p, val);
3265 
3266   pset_decoding_buf (p, empty_unibyte_string);
3267   p->decoding_carryover = 0;
3268   pset_encoding_buf (p, empty_unibyte_string);
3269 
3270   p->inherit_coding_system_flag
3271     = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3272 }
3273 
3274 #ifdef HAVE_GNUTLS
3275 static void
finish_after_tls_connection(Lisp_Object proc)3276 finish_after_tls_connection (Lisp_Object proc)
3277 {
3278   struct Lisp_Process *p = XPROCESS (proc);
3279   Lisp_Object contact = p->childp;
3280   Lisp_Object result = Qt;
3281 
3282   if (!NILP (Ffboundp (Qnsm_verify_connection)))
3283     result = call3 (Qnsm_verify_connection,
3284 		    proc,
3285 		    Fplist_get (contact, QChost),
3286 		    Fplist_get (contact, QCservice));
3287 
3288   eassert (p->outfd < FD_SETSIZE);
3289   if (NILP (result))
3290     {
3291       pset_status (p, list2 (Qfailed,
3292 			     build_string ("The Network Security Manager stopped the connections")));
3293       deactivate_process (proc);
3294     }
3295   else if (p->outfd < 0)
3296     {
3297       /* The counterparty may have closed the connection (especially
3298 	 if the NSM prompt above take a long time), so recheck the file
3299 	 descriptor here. */
3300       pset_status (p, Qfailed);
3301       deactivate_process (proc);
3302     }
3303   else if ((fd_callback_info[p->outfd].flags & NON_BLOCKING_CONNECT_FD) == 0)
3304     {
3305       /* If we cleared the connection wait mask before we did the TLS
3306 	 setup, then we have to say that the process is finally "open"
3307 	 here. */
3308       pset_status (p, Qrun);
3309       /* Execute the sentinel here.  If we had relied on status_notify
3310 	 to do it later, it will read input from the process before
3311 	 calling the sentinel.  */
3312       exec_sentinel (proc, build_string ("open\n"));
3313     }
3314 }
3315 #endif
3316 
3317 static void
connect_network_socket(Lisp_Object proc,Lisp_Object addrinfos,Lisp_Object use_external_socket_p)3318 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3319                         Lisp_Object use_external_socket_p)
3320 {
3321   int s = -1, outch, inch;
3322   int xerrno = 0;
3323   int family;
3324   int ret;
3325   ptrdiff_t addrlen UNINIT;
3326   struct Lisp_Process *p = XPROCESS (proc);
3327   Lisp_Object contact = p->childp;
3328   int optbits = 0;
3329   int socket_to_use = -1;
3330 
3331   if (!NILP (use_external_socket_p))
3332     {
3333       socket_to_use = external_sock_fd;
3334       eassert (socket_to_use < FD_SETSIZE);
3335 
3336       /* Ensure we don't consume the external socket twice.  */
3337       external_sock_fd = -1;
3338     }
3339 
3340   /* Do this in case we never enter the while-loop below.  */
3341   s = -1;
3342 
3343   struct sockaddr *sa = NULL;
3344   ptrdiff_t count = SPECPDL_INDEX ();
3345   record_unwind_protect_nothing ();
3346   ptrdiff_t count1 = SPECPDL_INDEX ();
3347 
3348   while (!NILP (addrinfos))
3349     {
3350       Lisp_Object addrinfo = XCAR (addrinfos);
3351       addrinfos = XCDR (addrinfos);
3352       int protocol = XFIXNUM (XCAR (addrinfo));
3353       Lisp_Object ip_address = XCDR (addrinfo);
3354 
3355 #ifdef WINDOWSNT
3356     retry_connect:
3357 #endif
3358 
3359       addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3360       sa = xrealloc (sa, addrlen);
3361       set_unwind_protect_ptr (count, xfree, sa);
3362       conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3363 
3364       s = socket_to_use;
3365       if (s < 0)
3366 	{
3367 	  int socktype = p->socktype | SOCK_CLOEXEC;
3368 	  if (p->is_non_blocking_client)
3369 	    socktype |= SOCK_NONBLOCK;
3370 	  s = socket (family, socktype, protocol);
3371 	  if (s < 0)
3372 	    {
3373 	      xerrno = errno;
3374 	      continue;
3375 	    }
3376 	  /* Reject file descriptors that would be too large.  */
3377 	  if (FD_SETSIZE <= s)
3378 	    {
3379 	      emacs_close (s);
3380 	      s = -1;
3381 	      xerrno = EMFILE;
3382 	      continue;
3383 	    }
3384 	}
3385 
3386       if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3387 	{
3388 	  ret = fcntl (s, F_SETFL, O_NONBLOCK);
3389 	  if (ret < 0)
3390 	    {
3391 	      xerrno = errno;
3392 	      emacs_close (s);
3393 	      s = -1;
3394 	      if (0 <= socket_to_use)
3395 		break;
3396 	      continue;
3397 	    }
3398 	}
3399 
3400 #ifdef DATAGRAM_SOCKETS
3401       if (!p->is_server && p->socktype == SOCK_DGRAM)
3402 	break;
3403 #endif /* DATAGRAM_SOCKETS */
3404 
3405       /* Make us close S if quit.  */
3406       record_unwind_protect_int (close_file_unwind, s);
3407 
3408       /* Parse network options in the arg list.  We simply ignore anything
3409 	 which isn't a known option (including other keywords).  An error
3410 	 is signaled if setting a known option fails.  */
3411       {
3412 	Lisp_Object params = contact, key, val;
3413 
3414 	while (!NILP (params))
3415 	  {
3416 	    key = XCAR (params);
3417 	    params = XCDR (params);
3418 	    val = XCAR (params);
3419 	    params = XCDR (params);
3420 	    optbits |= set_socket_option (s, key, val);
3421 	  }
3422       }
3423 
3424       if (p->is_server)
3425 	{
3426 	  /* Configure as a server socket.  */
3427 
3428 	  /* SO_REUSEADDR = 1 is default for server sockets; must specify
3429 	     explicit :reuseaddr key to override this.  */
3430 #ifdef HAVE_LOCAL_SOCKETS
3431 	  if (family != AF_LOCAL)
3432 #endif
3433 	    if (!(optbits & (1 << OPIX_REUSEADDR)))
3434 	      {
3435 		int optval = 1;
3436 		if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3437 		  report_file_error ("Cannot set reuse option on server socket", Qnil);
3438 	      }
3439 
3440           /* If passed a socket descriptor, it should be already bound. */
3441 	  if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3442 	    report_file_error ("Cannot bind server socket", Qnil);
3443 
3444 #ifdef HAVE_GETSOCKNAME
3445 	  if (p->port == 0
3446 #ifdef HAVE_LOCAL_SOCKETS
3447 	      && family != AF_LOCAL
3448 #endif
3449 	      )
3450 	    {
3451 	      struct sockaddr_in sa1;
3452 	      socklen_t len1 = sizeof (sa1);
3453 #ifdef AF_INET6
3454 	      /* The code below assumes the port is at the same offset
3455 		 and of the same width in both IPv4 and IPv6
3456 		 structures, but the standards don't guarantee that,
3457 		 so verify it here.  */
3458 	      struct sockaddr_in6 sa6;
3459 	      verify ((offsetof (struct sockaddr_in, sin_port)
3460 		       == offsetof (struct sockaddr_in6, sin6_port))
3461 		      && sizeof (sa1.sin_port) == sizeof (sa6.sin6_port));
3462 #endif
3463 	      DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3464 	      if (getsockname (s, psa1, &len1) == 0)
3465 		{
3466 		  Lisp_Object service = make_fixnum (ntohs (sa1.sin_port));
3467 		  contact = Fplist_put (contact, QCservice, service);
3468 		  /* Save the port number so that we can stash it in
3469 		     the process object later.  */
3470 		  DECLARE_POINTER_ALIAS (psa, struct sockaddr_in, sa);
3471 		  psa->sin_port = sa1.sin_port;
3472 		}
3473 	    }
3474 #endif
3475 
3476 	  if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3477 	    report_file_error ("Cannot listen on server socket", Qnil);
3478 
3479 	  break;
3480 	}
3481 
3482       maybe_quit ();
3483 
3484       ret = connect (s, sa, addrlen);
3485       xerrno = errno;
3486 
3487       if (ret == 0 || xerrno == EISCONN)
3488 	{
3489 	  /* The unwind-protect will be discarded afterwards.  */
3490 	  break;
3491 	}
3492 
3493       if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3494 	break;
3495 
3496 #ifndef WINDOWSNT
3497       if (xerrno == EINTR)
3498 	{
3499 	  /* Unlike most other syscalls connect() cannot be called
3500 	     again.  (That would return EALREADY.)  The proper way to
3501 	     wait for completion is pselect().  */
3502 	  int sc;
3503 	  socklen_t len;
3504 	  fd_set fdset;
3505 	retry_select:
3506 	  FD_ZERO (&fdset);
3507 	  FD_SET (s, &fdset);
3508 	  maybe_quit ();
3509 	  sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3510 	  if (sc == -1)
3511 	    {
3512 	      if (errno == EINTR)
3513 		goto retry_select;
3514 	      else
3515 		report_file_error ("Failed select", Qnil);
3516 	    }
3517 	  eassert (sc > 0);
3518 
3519 	  len = sizeof xerrno;
3520 	  eassert (FD_ISSET (s, &fdset));
3521 	  if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3522 	    report_file_error ("Failed getsockopt", Qnil);
3523 	  if (xerrno == 0)
3524 	    break;
3525 	  if (NILP (addrinfos))
3526 	    report_file_errno ("Failed connect", Qnil, xerrno);
3527 	}
3528 #endif /* !WINDOWSNT */
3529 
3530       /* Discard the unwind protect closing S.  */
3531       specpdl_ptr = specpdl + count1;
3532       emacs_close (s);
3533       s = -1;
3534       if (0 <= socket_to_use)
3535 	break;
3536 
3537 #ifdef WINDOWSNT
3538       if (xerrno == EINTR)
3539 	goto retry_connect;
3540 #endif
3541     }
3542 
3543   if (s >= 0)
3544     {
3545 #ifdef DATAGRAM_SOCKETS
3546       if (p->socktype == SOCK_DGRAM)
3547 	{
3548 	  eassert (0 <= s && s < FD_SETSIZE);
3549 	  if (datagram_address[s].sa)
3550 	    emacs_abort ();
3551 
3552 	  datagram_address[s].sa = xmalloc (addrlen);
3553 	  datagram_address[s].len = addrlen;
3554 	  if (p->is_server)
3555 	    {
3556 	      Lisp_Object remote;
3557 	      memset (datagram_address[s].sa, 0, addrlen);
3558 	      if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3559 		{
3560 		  int rfamily;
3561 		  ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3562 		  if (rlen != 0 && rfamily == family
3563 		      && rlen == addrlen)
3564 		    conv_lisp_to_sockaddr (rfamily, remote,
3565 					   datagram_address[s].sa, rlen);
3566 		}
3567 	    }
3568 	  else
3569 	    memcpy (datagram_address[s].sa, sa, addrlen);
3570 	}
3571 #endif
3572 
3573       contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3574 			    conv_sockaddr_to_lisp (sa, addrlen));
3575 #ifdef HAVE_GETSOCKNAME
3576       if (!p->is_server)
3577 	{
3578 	  struct sockaddr_storage sa1;
3579 	  socklen_t len1 = sizeof (sa1);
3580 	  DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3581 	  if (getsockname (s, psa1, &len1) == 0)
3582 	    contact = Fplist_put (contact, QClocal,
3583 				  conv_sockaddr_to_lisp (psa1, len1));
3584 	}
3585 #endif
3586     }
3587 
3588   if (s < 0)
3589     {
3590       const char *err = (p->is_server
3591 			 ? "make server process failed"
3592 			 : "make client process failed");
3593 
3594       /* If non-blocking got this far - and failed - assume non-blocking is
3595 	 not supported after all.  This is probably a wrong assumption, but
3596 	 the normal blocking calls to open-network-stream handles this error
3597 	 better.  */
3598       if (p->is_non_blocking_client)
3599 	{
3600 	  Lisp_Object data = get_file_errno_data (err, contact, xerrno);
3601 
3602 	  pset_status (p, list2 (Fcar (data), Fcdr (data)));
3603 	  unbind_to (count, Qnil);
3604 	  return;
3605 	}
3606 
3607       report_file_errno (err, contact, xerrno);
3608     }
3609 
3610   inch = s;
3611   outch = s;
3612 
3613   eassert (0 <= inch && inch < FD_SETSIZE);
3614   chan_process[inch] = proc;
3615 
3616   fcntl (inch, F_SETFL, O_NONBLOCK);
3617 
3618   p = XPROCESS (proc);
3619   p->open_fd[SUBPROCESS_STDIN] = inch;
3620   p->infd  = inch;
3621   p->outfd = outch;
3622 
3623   /* Discard the unwind protect for closing S, if any.  */
3624   specpdl_ptr = specpdl + count1;
3625 
3626   if (p->is_server && p->socktype != SOCK_DGRAM)
3627     pset_status (p, Qlisten);
3628 
3629   /* Make the process marker point into the process buffer (if any).  */
3630   update_process_mark (p);
3631 
3632   if (p->is_non_blocking_client)
3633     {
3634       /* We may get here if connect did succeed immediately.  However,
3635 	 in that case, we still need to signal this like a non-blocking
3636 	 connection.  */
3637       if (! (connecting_status (p->status)
3638 	     && EQ (XCDR (p->status), addrinfos)))
3639 	pset_status (p, Fcons (Qconnect, addrinfos));
3640       eassert (0 <= inch && inch < FD_SETSIZE);
3641       if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3642 	add_non_blocking_write_fd (inch);
3643     }
3644   else
3645     /* A server may have a client filter setting of Qt, but it must
3646        still listen for incoming connects unless it is stopped.  */
3647     if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3648 	|| (EQ (p->status, Qlisten) && NILP (p->command)))
3649       add_process_read_fd (inch);
3650 
3651   if (inch > max_desc)
3652     max_desc = inch;
3653 
3654   /* Set up the masks based on the process filter. */
3655   set_process_filter_masks (p);
3656 
3657   setup_process_coding_systems (proc);
3658 
3659 #ifdef HAVE_GNUTLS
3660   /* Continue the asynchronous connection. */
3661   if (!NILP (p->gnutls_boot_parameters))
3662     {
3663       Lisp_Object boot, params = p->gnutls_boot_parameters;
3664 
3665       boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3666 
3667       if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3668         {
3669           p->gnutls_boot_parameters = Qnil;
3670 	  /* Run sentinels, etc. */
3671 	  finish_after_tls_connection (proc);
3672         }
3673       else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3674 	{
3675 	  deactivate_process (proc);
3676 	  if (NILP (boot))
3677 	    pset_status (p, list2 (Qfailed,
3678 				   build_string ("TLS negotiation failed")));
3679 	  else
3680 	    pset_status (p, list2 (Qfailed, boot));
3681 	}
3682     }
3683 #endif
3684 
3685   unbind_to (count, Qnil);
3686 }
3687 
3688 /* Create a network stream/datagram client/server process.  Treated
3689    exactly like a normal process when reading and writing.  Primary
3690    differences are in status display and process deletion.  A network
3691    connection has no PID; you cannot signal it.  All you can do is
3692    stop/continue it and deactivate/close it via delete-process.  */
3693 
3694 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3695        0, MANY, 0,
3696        doc: /* Create and return a network server or client process.
3697 
3698 In Emacs, network connections are represented by process objects, so
3699 input and output work as for subprocesses and `delete-process' closes
3700 a network connection.  However, a network process has no process id,
3701 it cannot be signaled, and the status codes are different from normal
3702 processes.
3703 
3704 Arguments are specified as keyword/argument pairs.  The following
3705 arguments are defined:
3706 
3707 :name NAME -- NAME is name for process.  It is modified if necessary
3708 to make it unique.
3709 
3710 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3711 with the process.  Process output goes at end of that buffer, unless
3712 you specify a filter function to handle the output.  BUFFER may be
3713 also nil, meaning that this process is not associated with any buffer.
3714 
3715 :host HOST -- HOST is name of the host to connect to, or its IP
3716 address.  The symbol `local' specifies the local host.  If specified
3717 for a server process, it must be a valid name or address for the local
3718 host, and only clients connecting to that address will be accepted.
3719 If all interfaces should be bound, an address of \"0.0.0.0\" (for
3720 IPv4) or \"::\" (for IPv6) can be used.  (On some operating systems,
3721 using \"::\" listens on both IPv4 and IPv6.)  `local' will use IPv4 by
3722 default, use a FAMILY of `ipv6' to override this.
3723 
3724 :service SERVICE -- SERVICE is name of the service desired, or an
3725 integer specifying a port number to connect to.  If SERVICE is t,
3726 a random port number is selected for the server.  A port number can
3727 be specified as an integer string, e.g., "80", as well as an integer.
3728 
3729 :type TYPE -- TYPE is the type of connection.  The default (nil) is a
3730 stream type connection, `datagram' creates a datagram type connection,
3731 `seqpacket' creates a reliable datagram connection.
3732 
3733 :family FAMILY -- FAMILY is the address (and protocol) family for the
3734 service specified by HOST and SERVICE.  The default (nil) is to use
3735 whatever address family (IPv4 or IPv6) that is defined for the host
3736 and port number specified by HOST and SERVICE.  Other address families
3737 supported are:
3738   local -- for a local (i.e. UNIX) address specified by SERVICE.
3739   ipv4  -- use IPv4 address family only.
3740   ipv6  -- use IPv6 address family only.
3741 
3742 :local ADDRESS -- ADDRESS is the local address used for the connection.
3743 This parameter is ignored when opening a client process. When specified
3744 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3745 
3746 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3747 connection.  This parameter is ignored when opening a stream server
3748 process.  For a datagram server process, it specifies the initial
3749 setting of the remote datagram address.  When specified for a client
3750 process, the FAMILY, HOST, and SERVICE args are ignored.
3751 
3752 The format of ADDRESS depends on the address family:
3753 - An IPv4 address is represented as a vector of integers [A B C D P]
3754 corresponding to numeric IP address A.B.C.D and port number P.
3755 - An IPv6 address has the same format as an IPv4 address but with 9
3756 elements rather than 5.
3757 - A local address is represented as a string with the address in the
3758 local address space.
3759 - An "unsupported family" address is represented by a cons (F . AV)
3760 where F is the family number and AV is a vector containing the socket
3761 address data with one element per address data byte.  Do not rely on
3762 this format in portable code, as it may depend on implementation
3763 defined constants, data sizes, and data structure alignment.
3764 
3765 :coding CODING -- If CODING is a symbol, it specifies the coding
3766 system used for both reading and writing for this process.  If CODING
3767 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3768 ENCODING is used for writing.
3769 
3770 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3771 process, return without waiting for the connection to complete;
3772 instead, the sentinel function will be called with second arg matching
3773 "open" (if successful) or "failed" when the connect completes.
3774 Default is to use a blocking connect (i.e. wait) for stream type
3775 connections.
3776 
3777 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3778 running when Emacs is exited.
3779 
3780 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3781 In the stopped state, a server process does not accept new
3782 connections, and a client process does not handle incoming traffic.
3783 The stopped state is cleared by `continue-process' and set by
3784 `stop-process'.
3785 
3786 :filter FILTER -- Install FILTER as the process filter.
3787 
3788 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3789 process filter are multibyte, otherwise they are unibyte.
3790 If this keyword is not specified, the strings are multibyte.
3791 
3792 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3793 
3794 :log LOG -- Install LOG as the server process log function.  This
3795 function is called when the server accepts a network connection from a
3796 client.  The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3797 is the server process, CLIENT is the new process for the connection,
3798 and MESSAGE is a string.
3799 
3800 :plist PLIST -- Install PLIST as the new process's initial plist.
3801 
3802 :tls-parameters LIST -- is a list that should be supplied if you're
3803 opening a TLS connection.  The first element is the TLS type (either
3804 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3805 be a keyword list accepted by gnutls-boot (as returned by
3806 `gnutls-boot-parameters').
3807 
3808 :server QLEN -- if QLEN is non-nil, create a server process for the
3809 specified FAMILY, SERVICE, and connection type (stream or datagram).
3810 If QLEN is an integer, it is used as the max. length of the server's
3811 pending connection queue (also known as the backlog); the default
3812 queue length is 5.  Default is to create a client process.
3813 
3814 The following network options can be specified for this connection:
3815 
3816 :broadcast BOOL    -- Allow send and receive of datagram broadcasts.
3817 :dontroute BOOL    -- Only send to directly connected hosts.
3818 :keepalive BOOL    -- Send keep-alive messages on network stream.
3819 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3820 :oobinline BOOL    -- Place out-of-band data in receive data stream.
3821 :priority INT      -- Set protocol defined priority for sent packets.
3822 :reuseaddr BOOL    -- Allow reusing a recently used local address
3823                       (this is allowed by default for a server process).
3824 :bindtodevice NAME -- bind to interface NAME.  Using this may require
3825                       special privileges on some systems.
3826 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3827                              been passed to Emacs.  If Emacs wasn't
3828                              passed a socket, this option is silently
3829                              ignored.
3830 
3831 
3832 Consult the relevant system programmer's manual pages for more
3833 information on using these options.
3834 
3835 
3836 A server process will listen for and accept connections from clients.
3837 When a client connection is accepted, a new network process is created
3838 for the connection with the following parameters:
3839 
3840 - The client's process name is constructed by concatenating the server
3841 process's NAME and a client identification string.
3842 - If the FILTER argument is non-nil, the client process will not get a
3843 separate process buffer; otherwise, the client's process buffer is a newly
3844 created buffer named after the server process's BUFFER name or process
3845 NAME concatenated with the client identification string.
3846 - The connection type and the process filter and sentinel parameters are
3847 inherited from the server process's TYPE, FILTER and SENTINEL.
3848 - The client process's contact info is set according to the client's
3849 addressing information (typically an IP address and a port number).
3850 - The client process's plist is initialized from the server's plist.
3851 
3852 Notice that the FILTER and SENTINEL args are never used directly by
3853 the server process.  Also, the BUFFER argument is not used directly by
3854 the server process, but via the optional :log function, accepted (and
3855 failed) connections may be logged in the server process's buffer.
3856 
3857 The original argument list, modified with the actual connection
3858 information, is available via the `process-contact' function.
3859 
3860 usage: (make-network-process &rest ARGS)  */)
3861   (ptrdiff_t nargs, Lisp_Object *args)
3862 {
3863   Lisp_Object proc;
3864   Lisp_Object contact;
3865   struct Lisp_Process *p;
3866   const char *portstring UNINIT;
3867   char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3868 #ifdef HAVE_LOCAL_SOCKETS
3869   struct sockaddr_un address_un;
3870 #endif
3871   EMACS_INT port = 0;
3872   Lisp_Object tem;
3873   Lisp_Object name, buffer, host, service, address;
3874   Lisp_Object filter, sentinel, use_external_socket_p;
3875   Lisp_Object addrinfos = Qnil;
3876   int socktype;
3877   int family = -1;
3878   enum { any_protocol = 0 };
3879 #ifdef HAVE_GETADDRINFO_A
3880   struct gaicb *dns_request = NULL;
3881 #endif
3882   ptrdiff_t count = SPECPDL_INDEX ();
3883 
3884   if (nargs == 0)
3885     return Qnil;
3886 
3887   /* Save arguments for process-contact and clone-process.  */
3888   contact = Flist (nargs, args);
3889 
3890 #ifdef WINDOWSNT
3891   /* Ensure socket support is loaded if available.  */
3892   init_winsock (TRUE);
3893 #endif
3894 
3895   /* :type TYPE  (nil: stream, datagram */
3896   tem = Fplist_get (contact, QCtype);
3897   if (NILP (tem))
3898     socktype = SOCK_STREAM;
3899 #ifdef DATAGRAM_SOCKETS
3900   else if (EQ (tem, Qdatagram))
3901     socktype = SOCK_DGRAM;
3902 #endif
3903 #ifdef HAVE_SEQPACKET
3904   else if (EQ (tem, Qseqpacket))
3905     socktype = SOCK_SEQPACKET;
3906 #endif
3907   else
3908     error ("Unsupported connection type");
3909 
3910   name = Fplist_get (contact, QCname);
3911   buffer = Fplist_get (contact, QCbuffer);
3912   filter = Fplist_get (contact, QCfilter);
3913   sentinel = Fplist_get (contact, QCsentinel);
3914   use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3915   Lisp_Object server = Fplist_get (contact, QCserver);
3916   bool nowait = !NILP (Fplist_get (contact, QCnowait));
3917 
3918   if (!NILP (server) && nowait)
3919     error ("`:server' is incompatible with `:nowait'");
3920   CHECK_STRING (name);
3921 
3922   /* :local ADDRESS or :remote ADDRESS */
3923   if (NILP (server))
3924     address = Fplist_get (contact, QCremote);
3925   else
3926     address = Fplist_get (contact, QClocal);
3927   if (!NILP (address))
3928     {
3929       host = service = Qnil;
3930 
3931       if (!get_lisp_to_sockaddr_size (address, &family))
3932 	error ("Malformed :address");
3933 
3934       addrinfos = list1 (Fcons (make_fixnum (any_protocol), address));
3935       goto open_socket;
3936     }
3937 
3938   /* :family FAMILY -- nil (for Inet), local, or integer.  */
3939   tem = Fplist_get (contact, QCfamily);
3940   if (NILP (tem))
3941     {
3942 #ifdef AF_INET6
3943       family = AF_UNSPEC;
3944 #else
3945       family = AF_INET;
3946 #endif
3947     }
3948 #ifdef HAVE_LOCAL_SOCKETS
3949   else if (EQ (tem, Qlocal))
3950     family = AF_LOCAL;
3951 #endif
3952 #ifdef AF_INET6
3953   else if (EQ (tem, Qipv6))
3954     family = AF_INET6;
3955 #endif
3956   else if (EQ (tem, Qipv4))
3957     family = AF_INET;
3958   else if (TYPE_RANGED_FIXNUMP (int, tem))
3959     family = XFIXNUM (tem);
3960   else
3961     error ("Unknown address family");
3962 
3963   /* :service SERVICE -- string, integer (port number), or t (random port).  */
3964   service = Fplist_get (contact, QCservice);
3965 
3966   /* :host HOST -- hostname, ip address, or 'local for localhost.  */
3967   host = Fplist_get (contact, QChost);
3968   if (NILP (host))
3969     {
3970       /* The "connection" function gets it bind info from the address we're
3971 	 given, so use this dummy address if nothing is specified. */
3972 #ifdef HAVE_LOCAL_SOCKETS
3973       if (family != AF_LOCAL)
3974 #endif
3975         {
3976 #ifdef AF_INET6
3977         if (family == AF_INET6)
3978           host = build_string ("::1");
3979         else
3980 #endif
3981           host = build_string ("127.0.0.1");
3982         }
3983     }
3984   else
3985     {
3986       if (EQ (host, Qlocal))
3987         {
3988 	/* Depending on setup, "localhost" may map to different IPv4 and/or
3989 	   IPv6 addresses, so it's better to be explicit (Bug#6781).  */
3990 #ifdef AF_INET6
3991         if (family == AF_INET6)
3992           host = build_string ("::1");
3993         else
3994 #endif
3995           host = build_string ("127.0.0.1");
3996         }
3997       CHECK_STRING (host);
3998     }
3999 
4000 #ifdef HAVE_LOCAL_SOCKETS
4001   if (family == AF_LOCAL)
4002     {
4003       if (!NILP (host))
4004 	{
4005 	  message (":family local ignores the :host property");
4006 	  contact = Fplist_put (contact, QChost, Qnil);
4007 	  host = Qnil;
4008 	}
4009       CHECK_STRING (service);
4010       if (sizeof address_un.sun_path <= SBYTES (service))
4011 	error ("Service name too long");
4012       addrinfos = list1 (Fcons (make_fixnum (any_protocol), service));
4013       goto open_socket;
4014     }
4015 #endif
4016 
4017   /* Slow down polling to every ten seconds.
4018      Some kernels have a bug which causes retrying connect to fail
4019      after a connect.  Polling can interfere with gethostbyname too.  */
4020 #ifdef POLL_FOR_INPUT
4021   if (socktype != SOCK_DGRAM)
4022     {
4023       record_unwind_protect_void (run_all_atimers);
4024       bind_polling_period (10);
4025     }
4026 #endif
4027 
4028   if (!NILP (host))
4029     {
4030       MAYBE_UNUSED ptrdiff_t portstringlen;
4031 
4032       /* SERVICE can either be a string or int.
4033 	 Convert to a C string for later use by getaddrinfo.  */
4034       if (EQ (service, Qt))
4035 	{
4036 	  portstring = "0";
4037 	  portstringlen = 1;
4038 	}
4039       else if (FIXNUMP (service))
4040 	{
4041 	  portstring = portbuf;
4042 	  portstringlen = sprintf (portbuf, "%"pI"d", XFIXNUM (service));
4043 	}
4044       else
4045 	{
4046 	  CHECK_STRING (service);
4047 	  portstring = SSDATA (service);
4048 	  portstringlen = SBYTES (service);
4049 	}
4050 
4051 #ifdef HAVE_GETADDRINFO_A
4052       if (nowait)
4053 	{
4054 	  ptrdiff_t hostlen = SBYTES (host);
4055 	  struct req
4056 	  {
4057 	    struct gaicb gaicb;
4058 	    struct addrinfo hints;
4059 	    char str[FLEXIBLE_ARRAY_MEMBER];
4060 	  } *req = xmalloc (FLEXSIZEOF (struct req, str,
4061 					hostlen + 1 + portstringlen + 1));
4062 	  dns_request = &req->gaicb;
4063 	  dns_request->ar_name = req->str;
4064 	  dns_request->ar_service = req->str + hostlen + 1;
4065 	  dns_request->ar_request = &req->hints;
4066 	  dns_request->ar_result = NULL;
4067 	  memset (&req->hints, 0, sizeof req->hints);
4068 	  req->hints.ai_family = family;
4069 	  req->hints.ai_socktype = socktype;
4070 	  strcpy (req->str, SSDATA (host));
4071 	  strcpy (req->str + hostlen + 1, portstring);
4072 
4073 	  int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4074 	  if (ret)
4075 	    error ("%s/%s getaddrinfo_a error %d",
4076 		   SSDATA (host), portstring, ret);
4077 
4078 	  goto open_socket;
4079 	}
4080 #endif /* HAVE_GETADDRINFO_A */
4081     }
4082 
4083   /* If we have a host, use getaddrinfo to resolve both host and service.
4084      Otherwise, use getservbyname to lookup the service.  */
4085 
4086   if (!NILP (host))
4087     {
4088       struct addrinfo *res, *lres;
4089       Lisp_Object msg;
4090 
4091       maybe_quit ();
4092 
4093       struct addrinfo hints;
4094       memset (&hints, 0, sizeof hints);
4095       hints.ai_family = family;
4096       hints.ai_socktype = socktype;
4097 
4098       msg = network_lookup_address_info_1 (host, portstring, &hints, &res);
4099       if (!EQ (msg, Qt))
4100 	error ("%s", SSDATA (msg));
4101 
4102       for (lres = res; lres; lres = lres->ai_next)
4103 	addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4104 
4105       addrinfos = Fnreverse (addrinfos);
4106 
4107       freeaddrinfo (res);
4108 
4109       goto open_socket;
4110     }
4111 
4112   /* No hostname has been specified (e.g., a local server process).  */
4113 
4114   if (EQ (service, Qt))
4115     port = 0;
4116   else if (FIXNUMP (service))
4117     port = XFIXNUM (service);
4118   else
4119     {
4120       CHECK_STRING (service);
4121 
4122       port = -1;
4123       if (SBYTES (service) != 0)
4124 	{
4125 	  /* Allow the service to be a string containing the port number,
4126 	     because that's allowed if you have getaddrbyname.  */
4127 	  char *service_end;
4128 	  long int lport = strtol (SSDATA (service), &service_end, 10);
4129 	  if (service_end == SSDATA (service) + SBYTES (service))
4130 	    port = lport;
4131 	  else
4132 	    {
4133 	      struct servent *svc_info
4134 		= getservbyname (SSDATA (service),
4135 				 socktype == SOCK_DGRAM ? "udp" : "tcp");
4136 	      if (svc_info)
4137 		port = ntohs (svc_info->s_port);
4138 	    }
4139 	}
4140     }
4141 
4142   if (! (0 <= port && port < 1 << 16))
4143     {
4144       AUTO_STRING (unknown_service, "Unknown service: %s");
4145       xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4146     }
4147 
4148  open_socket:
4149 
4150   if (!NILP (buffer))
4151     buffer = Fget_buffer_create (buffer, Qnil);
4152 
4153   /* Unwind bind_polling_period.  */
4154   unbind_to (count, Qnil);
4155 
4156   proc = make_process (name);
4157   record_unwind_protect (remove_process, proc);
4158   p = XPROCESS (proc);
4159   pset_childp (p, contact);
4160   pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4161   pset_type (p, Qnetwork);
4162 
4163   pset_buffer (p, buffer);
4164   pset_sentinel (p, sentinel);
4165   pset_filter (p, filter);
4166   pset_log (p, Fplist_get (contact, QClog));
4167   if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4168     p->kill_without_query = 1;
4169   if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4170     pset_command (p, Qt);
4171   eassert (p->pid == 0);
4172   p->backlog = 5;
4173   eassert (! p->is_non_blocking_client);
4174   eassert (! p->is_server);
4175   p->port = port;
4176   p->socktype = socktype;
4177 #ifdef HAVE_GETADDRINFO_A
4178   eassert (! p->dns_request);
4179 #endif
4180 #ifdef HAVE_GNUTLS
4181   tem = Fplist_get (contact, QCtls_parameters);
4182   CHECK_LIST (tem);
4183   p->gnutls_boot_parameters = tem;
4184 #endif
4185 
4186   set_network_socket_coding_system (proc, host, service, name);
4187 
4188   /* :server QLEN */
4189   p->is_server = !NILP (server);
4190   if (TYPE_RANGED_FIXNUMP (int, server))
4191     p->backlog = XFIXNUM (server);
4192 
4193   /* :nowait BOOL */
4194   if (!p->is_server && socktype != SOCK_DGRAM && nowait)
4195     p->is_non_blocking_client = true;
4196 
4197   bool postpone_connection = false;
4198 #ifdef HAVE_GETADDRINFO_A
4199   /* With async address resolution, the list of addresses is empty, so
4200      postpone connecting to the server. */
4201   if (!p->is_server && NILP (addrinfos))
4202     {
4203       p->dns_request = dns_request;
4204       p->status = list1 (Qconnect);
4205       postpone_connection = true;
4206     }
4207 #endif
4208   if (! postpone_connection)
4209     connect_network_socket (proc, addrinfos, use_external_socket_p);
4210 
4211   specpdl_ptr = specpdl + count;
4212   return proc;
4213 }
4214 
4215 
4216 
4217 #ifdef HAVE_GETIFADDRS
4218 static Lisp_Object
network_interface_list(bool full,unsigned short match)4219 network_interface_list (bool full, unsigned short match)
4220 {
4221   Lisp_Object res = Qnil;
4222   struct ifaddrs *ifap;
4223 
4224   if (getifaddrs (&ifap) == -1)
4225     return Qnil;
4226 
4227   for (struct ifaddrs *it = ifap; it != NULL; it = it->ifa_next)
4228     {
4229       int len;
4230       int addr_len;
4231       uint32_t *maskp;
4232       uint32_t *addrp;
4233       Lisp_Object elt = Qnil;
4234 
4235       /* BSD can allegedly return interfaces with a NULL address.  */
4236       if (it->ifa_addr == NULL)
4237         continue;
4238       if (match && it->ifa_addr->sa_family != match)
4239         continue;
4240       if (it->ifa_addr->sa_family == AF_INET)
4241         {
4242           DECLARE_POINTER_ALIAS (sin1, struct sockaddr_in, it->ifa_netmask);
4243           maskp = (uint32_t *)&sin1->sin_addr;
4244           DECLARE_POINTER_ALIAS (sin2, struct sockaddr_in, it->ifa_addr);
4245           addrp = (uint32_t *)&sin2->sin_addr;
4246           len = sizeof (struct sockaddr_in);
4247           addr_len = 1;
4248         }
4249 #ifdef AF_INET6
4250       else if (it->ifa_addr->sa_family == AF_INET6)
4251         {
4252           DECLARE_POINTER_ALIAS (sin6_1, struct sockaddr_in6, it->ifa_netmask);
4253           maskp = (uint32_t *) &sin6_1->sin6_addr;
4254           DECLARE_POINTER_ALIAS (sin6_2, struct sockaddr_in6, it->ifa_addr);
4255           addrp = (uint32_t *) &sin6_2->sin6_addr;
4256           len = sizeof (struct sockaddr_in6);
4257           addr_len = 4;
4258         }
4259 #endif
4260       else
4261         continue;
4262 
4263       Lisp_Object addr = conv_sockaddr_to_lisp (it->ifa_addr, len);
4264 
4265       if (full)
4266         {
4267           elt = Fcons (conv_sockaddr_to_lisp (it->ifa_netmask, len), elt);
4268           /* There is an it->ifa_broadaddr field, but its contents are
4269              unreliable, so always calculate the broadcast address from
4270              the address and the netmask.  */
4271           int i;
4272           uint32_t mask;
4273           for (i = 0; i < addr_len; i++)
4274             {
4275               mask = maskp[i];
4276               maskp[i] = (addrp[i] & mask) | ~mask;
4277             }
4278           elt = Fcons (conv_sockaddr_to_lisp (it->ifa_netmask, len), elt);
4279           elt = Fcons (addr, elt);
4280         }
4281       else
4282         {
4283           elt = addr;
4284         }
4285       res = Fcons (Fcons (build_string (it->ifa_name), elt), res);
4286     }
4287 #ifdef HAVE_FREEIFADDRS
4288   freeifaddrs (ifap);
4289 #endif
4290 
4291   return res;
4292 }
4293 #endif  /* HAVE_GETIFADDRS */
4294 
4295 #ifdef HAVE_NET_IF_H
4296 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4297 
4298 struct ifflag_def {
4299   int flag_bit;
4300   const char *flag_sym;
4301 };
4302 
4303 static const struct ifflag_def ifflag_table[] = {
4304 #ifdef IFF_UP
4305   { IFF_UP,		"up" },
4306 #endif
4307 #ifdef IFF_BROADCAST
4308   { IFF_BROADCAST,	"broadcast" },
4309 #endif
4310 #ifdef IFF_DEBUG
4311   { IFF_DEBUG,		"debug" },
4312 #endif
4313 #ifdef IFF_LOOPBACK
4314   { IFF_LOOPBACK,	"loopback" },
4315 #endif
4316 #ifdef IFF_POINTOPOINT
4317   { IFF_POINTOPOINT,	"pointopoint" },
4318 #endif
4319 #ifdef IFF_RUNNING
4320   { IFF_RUNNING,	"running" },
4321 #endif
4322 #ifdef IFF_NOARP
4323   { IFF_NOARP,		"noarp" },
4324 #endif
4325 #ifdef IFF_PROMISC
4326   { IFF_PROMISC,	"promisc" },
4327 #endif
4328 #ifdef IFF_NOTRAILERS
4329 #ifdef NS_IMPL_COCOA
4330   /* Really means smart, notrailers is obsolete.  */
4331   { IFF_NOTRAILERS,	"smart" },
4332 #else
4333   { IFF_NOTRAILERS,	"notrailers" },
4334 #endif
4335 #endif
4336 #ifdef IFF_ALLMULTI
4337   { IFF_ALLMULTI,	"allmulti" },
4338 #endif
4339 #ifdef IFF_MASTER
4340   { IFF_MASTER,		"master" },
4341 #endif
4342 #ifdef IFF_SLAVE
4343   { IFF_SLAVE,		"slave" },
4344 #endif
4345 #ifdef IFF_MULTICAST
4346   { IFF_MULTICAST,	"multicast" },
4347 #endif
4348 #ifdef IFF_PORTSEL
4349   { IFF_PORTSEL,	"portsel" },
4350 #endif
4351 #ifdef IFF_AUTOMEDIA
4352   { IFF_AUTOMEDIA,	"automedia" },
4353 #endif
4354 #ifdef IFF_DYNAMIC
4355   { IFF_DYNAMIC,	"dynamic" },
4356 #endif
4357 #ifdef IFF_OACTIVE
4358   { IFF_OACTIVE,	"oactive" }, /* OpenBSD: transmission in progress.  */
4359 #endif
4360 #ifdef IFF_SIMPLEX
4361   { IFF_SIMPLEX,	"simplex" }, /* OpenBSD: can't hear own transmissions.  */
4362 #endif
4363 #ifdef IFF_LINK0
4364   { IFF_LINK0,		"link0" }, /* OpenBSD: per link layer defined bit.  */
4365 #endif
4366 #ifdef IFF_LINK1
4367   { IFF_LINK1,		"link1" }, /* OpenBSD: per link layer defined bit.  */
4368 #endif
4369 #ifdef IFF_LINK2
4370   { IFF_LINK2,		"link2" }, /* OpenBSD: per link layer defined bit.  */
4371 #endif
4372   { 0, 0 }
4373 };
4374 
4375 static Lisp_Object
network_interface_info(Lisp_Object ifname)4376 network_interface_info (Lisp_Object ifname)
4377 {
4378   struct ifreq rq;
4379   Lisp_Object res = Qnil;
4380   Lisp_Object elt;
4381   int s;
4382   bool any = false;
4383   ptrdiff_t count;
4384 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR)	\
4385      && defined HAVE_GETIFADDRS && defined LLADDR)
4386   struct ifaddrs *ifap;
4387 #endif
4388 
4389   CHECK_STRING (ifname);
4390 
4391   if (sizeof rq.ifr_name <= SBYTES (ifname))
4392     error ("interface name too long");
4393   lispstpcpy (rq.ifr_name, ifname);
4394 
4395   s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4396   if (s < 0)
4397     return Qnil;
4398   count = SPECPDL_INDEX ();
4399   record_unwind_protect_int (close_file_unwind, s);
4400 
4401   elt = Qnil;
4402 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4403   if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4404     {
4405       int flags = rq.ifr_flags;
4406       const struct ifflag_def *fp;
4407       int fnum;
4408 
4409       /* If flags is smaller than int (i.e. short) it may have the high bit set
4410          due to IFF_MULTICAST.  In that case, sign extending it into
4411          an int is wrong.  */
4412       if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4413         flags = (unsigned short) rq.ifr_flags;
4414 
4415       any = true;
4416       for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4417 	{
4418 	  if (flags & fp->flag_bit)
4419 	    {
4420 	      elt = Fcons (intern (fp->flag_sym), elt);
4421 	      flags -= fp->flag_bit;
4422 	    }
4423 	}
4424       for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4425 	{
4426 	  if (flags & 1)
4427 	    {
4428 	      elt = Fcons (make_fixnum (fnum), elt);
4429 	    }
4430 	}
4431     }
4432 #endif
4433   res = Fcons (elt, res);
4434 
4435   elt = Qnil;
4436 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4437   if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4438     {
4439       Lisp_Object hwaddr = make_uninit_vector (6);
4440       struct Lisp_Vector *p = XVECTOR (hwaddr);
4441 
4442       any = true;
4443       for (int n = 0; n < 6; n++)
4444 	p->contents[n] = make_fixnum (((unsigned char *)
4445 				       &rq.ifr_hwaddr.sa_data[0])
4446 				      [n]);
4447       elt = Fcons (make_fixnum (rq.ifr_hwaddr.sa_family), hwaddr);
4448     }
4449 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4450   if (getifaddrs (&ifap) != -1)
4451     {
4452       Lisp_Object hwaddr = make_nil_vector (6);
4453       struct Lisp_Vector *p = XVECTOR (hwaddr);
4454 
4455       for (struct ifaddrs *it = ifap; it != NULL; it = it->ifa_next)
4456         {
4457 	  DECLARE_POINTER_ALIAS (sdl, struct sockaddr_dl, it->ifa_addr);
4458           unsigned char linkaddr[6];
4459           int n;
4460 
4461           if (it->ifa_addr->sa_family != AF_LINK
4462               || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4463               || sdl->sdl_alen != 6)
4464             continue;
4465 
4466           memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4467           for (n = 0; n < 6; n++)
4468             p->contents[n] = make_fixnum (linkaddr[n]);
4469 
4470           elt = Fcons (make_fixnum (it->ifa_addr->sa_family), hwaddr);
4471           break;
4472         }
4473     }
4474 #ifdef HAVE_FREEIFADDRS
4475   freeifaddrs (ifap);
4476 #endif
4477 
4478 #endif /* HAVE_GETIFADDRS && LLADDR */
4479 
4480   res = Fcons (elt, res);
4481 
4482   elt = Qnil;
4483 #if (defined SIOCGIFNETMASK \
4484      && (defined HAVE_STRUCT_IFREQ_IFR_NETMASK \
4485 	 || defined HAVE_STRUCT_IFREQ_IFR_ADDR))
4486   if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4487     {
4488       any = true;
4489 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4490       elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4491 #else
4492       elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4493 #endif
4494     }
4495 #endif
4496   res = Fcons (elt, res);
4497 
4498   elt = Qnil;
4499 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4500   if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4501     {
4502       any = true;
4503       elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof rq.ifr_broadaddr);
4504     }
4505 #endif
4506   res = Fcons (elt, res);
4507 
4508   elt = Qnil;
4509 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4510   if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4511     {
4512       any = true;
4513       elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4514     }
4515 #endif
4516   res = Fcons (elt, res);
4517 
4518   return unbind_to (count, any ? res : Qnil);
4519 }
4520 #endif	/* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4521 #endif	/* defined (HAVE_NET_IF_H) */
4522 
4523 DEFUN ("network-interface-list", Fnetwork_interface_list,
4524        Snetwork_interface_list, 0, 2, 0,
4525        doc: /* Return an alist of all network interfaces and their network address.
4526 Each element is cons of the form (IFNAME . IP) where IFNAME is a
4527 string containing the interface name, and IP is the network address in
4528 internal format; see the description of ADDRESS in
4529 `make-network-process'.  The interface name is not guaranteed to be
4530 unique.
4531 
4532 Optional parameter FULL non-nil means return all IP address info for
4533 each interface.  Each element is then a list of the form
4534     (IFNAME IP BCAST MASK)
4535 where IFNAME is the interface name, IP the IP address,
4536 BCAST the broadcast address, and MASK the network mask.
4537 
4538 Optional parameter FAMILY controls the type of addresses to return.
4539 The default of nil means both IPv4 and IPv6, symbol `ipv4' means IPv4
4540 only, symbol `ipv6' means IPv6 only.
4541 
4542 See also `network-interface-info', which is limited to IPv4 only.
4543 
4544 If the information is not available, return nil.  */)
4545   (Lisp_Object full, Lisp_Object family)
4546 {
4547 #if defined HAVE_GETIFADDRS || defined WINDOWSNT
4548   unsigned short match;
4549   bool full_info = false;
4550 
4551   if (! NILP (full))
4552     full_info = true;
4553   if (NILP (family))
4554     match = 0;
4555   else if (EQ (family, Qipv4))
4556     match = AF_INET;
4557 #ifdef AF_INET6
4558   else if (EQ (family, Qipv6))
4559     match = AF_INET6;
4560 #endif
4561   else
4562     error ("Unsupported address family");
4563   return network_interface_list (full_info, match);
4564 #else
4565   return Qnil;
4566 #endif
4567 }
4568 
4569 DEFUN ("network-interface-info", Fnetwork_interface_info,
4570        Snetwork_interface_info, 1, 1, 0,
4571        doc: /* Return information about network interface named IFNAME.
4572 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4573 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4574 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4575 FLAGS is the current flags of the interface.
4576 
4577 Data that is unavailable is returned as nil.  */)
4578   (Lisp_Object ifname)
4579 {
4580 #if ((defined HAVE_NET_IF_H			       \
4581       && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4582 	  || defined SIOCGIFFLAGS))		       \
4583      || defined WINDOWSNT)
4584   return network_interface_info (ifname);
4585 #else
4586   return Qnil;
4587 #endif
4588 }
4589 
4590 static Lisp_Object
network_lookup_address_info_1(Lisp_Object host,const char * service,struct addrinfo * hints,struct addrinfo ** res)4591 network_lookup_address_info_1 (Lisp_Object host, const char *service,
4592                                struct addrinfo *hints, struct addrinfo **res)
4593 {
4594   Lisp_Object msg = Qt;
4595   int ret;
4596 
4597   if (STRING_MULTIBYTE (host) && SBYTES (host) != SCHARS (host))
4598     error ("Non-ASCII hostname %s detected, please use puny-encode-domain",
4599            SSDATA (host));
4600 
4601 #ifdef WINDOWSNT
4602   /* Ensure socket support is loaded if available.  */
4603   init_winsock (TRUE);
4604 #endif
4605 
4606   ret = getaddrinfo (SSDATA (host), service, hints, res);
4607   if (ret)
4608     {
4609       if (service == NULL)
4610         service = "0";
4611 #ifdef HAVE_GAI_STRERROR
4612       synchronize_system_messages_locale ();
4613       char const *str = gai_strerror (ret);
4614       if (! NILP (Vlocale_coding_system))
4615         str = SSDATA (code_convert_string_norecord
4616                       (build_string (str), Vlocale_coding_system, 0));
4617       AUTO_STRING (format, "%s/%s %s");
4618       msg = CALLN (Fformat, format, host, build_string (service),
4619 		   build_string (str));
4620 #else
4621       AUTO_STRING (format, "%s/%s getaddrinfo error %d");
4622       msg = CALLN (Fformat, format, host, build_string (service),
4623 		   make_int (ret));
4624 #endif
4625     }
4626    return msg;
4627 }
4628 
4629 DEFUN ("network-lookup-address-info", Fnetwork_lookup_address_info,
4630        Snetwork_lookup_address_info, 1, 2, 0,
4631        doc: /* Look up Internet Protocol (IP) address info of NAME.
4632 Optional parameter FAMILY controls whether to look up IPv4 or IPv6
4633 addresses.  The default of nil means both, symbol `ipv4' means IPv4
4634 only, symbol `ipv6' means IPv6 only.  Returns a list of addresses, or
4635 nil if none were found.  Each address is a vector of integers, as per
4636 the description of ADDRESS in `make-network-process'.  In case of
4637 error displays the error message.  */)
4638      (Lisp_Object name, Lisp_Object family)
4639 {
4640   Lisp_Object addresses = Qnil;
4641   Lisp_Object msg = Qnil;
4642 
4643   struct addrinfo *res, *lres;
4644   struct addrinfo hints;
4645 
4646   memset (&hints, 0, sizeof hints);
4647   if (EQ (family, Qnil))
4648     hints.ai_family = AF_UNSPEC;
4649   else if (EQ (family, Qipv4))
4650     hints.ai_family = AF_INET;
4651 #ifdef AF_INET6
4652   else if (EQ (family, Qipv6))
4653     hints.ai_family = AF_INET6;
4654 #endif
4655   else
4656     error ("Unsupported lookup type");
4657   hints.ai_socktype = SOCK_DGRAM;
4658 
4659   msg = network_lookup_address_info_1 (name, NULL, &hints, &res);
4660   if (!EQ (msg, Qt))
4661     message ("%s", SSDATA(msg));
4662   else
4663     {
4664       for (lres = res; lres; lres = lres->ai_next)
4665         {
4666 #ifndef AF_INET6
4667           if (lres->ai_family != AF_INET)
4668             continue;
4669 #endif
4670           addresses = Fcons (conv_sockaddr_to_lisp (lres->ai_addr,
4671                                                     lres->ai_addrlen),
4672                              addresses);
4673         }
4674       addresses = Fnreverse (addresses);
4675 
4676       freeaddrinfo (res);
4677     }
4678   return addresses;
4679 }
4680 
4681 /* Turn off input and output for process PROC.  */
4682 
4683 static void
deactivate_process(Lisp_Object proc)4684 deactivate_process (Lisp_Object proc)
4685 {
4686   int inchannel;
4687   struct Lisp_Process *p = XPROCESS (proc);
4688   int i;
4689 
4690 #ifdef HAVE_GNUTLS
4691   /* Delete GnuTLS structures in PROC, if any.  */
4692   emacs_gnutls_deinit (proc);
4693 #endif /* HAVE_GNUTLS */
4694 
4695   if (p->read_output_delay > 0)
4696     {
4697       if (--process_output_delay_count < 0)
4698 	process_output_delay_count = 0;
4699       p->read_output_delay = 0;
4700       p->read_output_skip = 0;
4701     }
4702 
4703   /* Beware SIGCHLD hereabouts.  */
4704 
4705   for (i = 0; i < PROCESS_OPEN_FDS; i++)
4706     close_process_fd (&p->open_fd[i]);
4707 
4708   inchannel = p->infd;
4709   eassert (inchannel < FD_SETSIZE);
4710   if (inchannel >= 0)
4711     {
4712       p->infd  = -1;
4713       p->outfd = -1;
4714 #ifdef DATAGRAM_SOCKETS
4715       if (DATAGRAM_CHAN_P (inchannel))
4716 	{
4717 	  xfree (datagram_address[inchannel].sa);
4718 	  datagram_address[inchannel].sa = 0;
4719 	  datagram_address[inchannel].len = 0;
4720 	}
4721 #endif
4722       chan_process[inchannel] = Qnil;
4723       delete_read_fd (inchannel);
4724       if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4725 	delete_write_fd (inchannel);
4726       if (inchannel == max_desc)
4727 	recompute_max_desc ();
4728     }
4729 }
4730 
4731 
4732 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4733        0, 4, 0,
4734        doc: /* Allow any pending output from subprocesses to be read by Emacs.
4735 It is given to their filter functions.
4736 Optional argument PROCESS means to return only after output is
4737 received from PROCESS or PROCESS closes the connection.
4738 
4739 Optional second argument SECONDS and third argument MILLISEC
4740 specify a timeout; return after that much time even if there is
4741 no subprocess output.  If SECONDS is a floating point number,
4742 it specifies a fractional number of seconds to wait.
4743 The MILLISEC argument is obsolete and should be avoided.
4744 
4745 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4746 from PROCESS only, suspending reading output from other processes.
4747 If JUST-THIS-ONE is an integer, don't run any timers either.
4748 Return non-nil if we received any output from PROCESS (or, if PROCESS
4749 is nil, from any process) before the timeout expired or the
4750 corresponding connection was closed.  */)
4751   (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4752    Lisp_Object just_this_one)
4753 {
4754   intmax_t secs;
4755   int nsecs;
4756 
4757   if (! NILP (process))
4758     {
4759       CHECK_PROCESS (process);
4760       struct Lisp_Process *proc = XPROCESS (process);
4761 
4762       /* Can't wait for a process that is dedicated to a different
4763 	 thread.  */
4764       if (!NILP (proc->thread) && !EQ (proc->thread, Fcurrent_thread ()))
4765 	{
4766 	  Lisp_Object proc_thread_name = XTHREAD (proc->thread)->name;
4767 
4768 	  error ("Attempt to accept output from process %s locked to thread %s",
4769 		 SDATA (proc->name),
4770 		 STRINGP (proc_thread_name)
4771 		 ? SDATA (proc_thread_name)
4772 		 : SDATA (Fprin1_to_string (proc->thread, Qt)));
4773 	}
4774     }
4775   else
4776     just_this_one = Qnil;
4777 
4778   if (!NILP (millisec))
4779     { /* Obsolete calling convention using integers rather than floats.  */
4780       CHECK_FIXNUM (millisec);
4781       if (NILP (seconds))
4782 	seconds = make_float (XFIXNUM (millisec) / 1000.0);
4783       else
4784 	{
4785 	  CHECK_FIXNUM (seconds);
4786 	  seconds = make_float (XFIXNUM (millisec) / 1000.0 + XFIXNUM (seconds));
4787 	}
4788     }
4789 
4790   secs = 0;
4791   nsecs = -1;
4792 
4793   if (!NILP (seconds))
4794     {
4795       if (FIXNUMP (seconds))
4796 	{
4797 	  if (XFIXNUM (seconds) > 0)
4798 	    {
4799 	      secs = XFIXNUM (seconds);
4800 	      nsecs = 0;
4801 	    }
4802 	}
4803       else if (FLOATP (seconds))
4804 	{
4805 	  if (XFLOAT_DATA (seconds) > 0)
4806 	    {
4807 	      struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4808 	      secs = min (t.tv_sec, WAIT_READING_MAX);
4809 	      nsecs = t.tv_nsec;
4810 	    }
4811 	}
4812       else
4813 	wrong_type_argument (Qnumberp, seconds);
4814     }
4815   else if (! NILP (process))
4816     nsecs = 0;
4817 
4818   return
4819     ((wait_reading_process_output (secs, nsecs, 0, 0,
4820 				   Qnil,
4821 				   !NILP (process) ? XPROCESS (process) : NULL,
4822 				   (NILP (just_this_one) ? 0
4823 				    : !FIXNUMP (just_this_one) ? 1 : -1))
4824       <= 0)
4825      ? Qnil : Qt);
4826 }
4827 
4828 /* Accept a connection for server process SERVER on CHANNEL.  */
4829 
4830 static EMACS_INT connect_counter = 0;
4831 
4832 static void
server_accept_connection(Lisp_Object server,int channel)4833 server_accept_connection (Lisp_Object server, int channel)
4834 {
4835   Lisp_Object buffer;
4836   Lisp_Object contact, host, service;
4837   struct Lisp_Process *ps = XPROCESS (server);
4838   struct Lisp_Process *p;
4839   int s;
4840   union u_sockaddr saddr;
4841   socklen_t len = sizeof saddr;
4842   ptrdiff_t count;
4843 
4844   s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4845 
4846   if (FD_SETSIZE <= s)
4847     {
4848       emacs_close (s);
4849       s = -1;
4850       errno = EMFILE;
4851     }
4852 
4853   if (s < 0)
4854     {
4855       int code = errno;
4856       if (!would_block (code) && !NILP (ps->log))
4857 	call3 (ps->log, server, Qnil,
4858 	       concat3 (build_string ("accept failed with code"),
4859 			Fnumber_to_string (make_fixnum (code)),
4860 			build_string ("\n")));
4861       return;
4862     }
4863 
4864   count = SPECPDL_INDEX ();
4865   record_unwind_protect_int (close_file_unwind, s);
4866 
4867   connect_counter++;
4868 
4869   /* Setup a new process to handle the connection.  */
4870 
4871   /* Generate a unique identification of the caller, and build contact
4872      information for this process.  */
4873   host = Qt;
4874   service = Qnil;
4875   Lisp_Object args[11];
4876   int nargs = 0;
4877   #define HOST_FORMAT_IN "%d.%d.%d.%d"
4878   #define HOST_FORMAT_IN6 "%x:%x:%x:%x:%x:%x:%x:%x"
4879   AUTO_STRING (host_format_in, HOST_FORMAT_IN);
4880   AUTO_STRING (host_format_in6, HOST_FORMAT_IN6);
4881   AUTO_STRING (procname_format_in, "%s <"HOST_FORMAT_IN":%d>");
4882   AUTO_STRING (procname_format_in6, "%s <["HOST_FORMAT_IN6"]:%d>");
4883   AUTO_STRING (procname_format_default, "%s <%d>");
4884   switch (saddr.sa.sa_family)
4885     {
4886     case AF_INET:
4887       {
4888 	args[nargs++] = procname_format_in;
4889 	args[nargs++] = host_format_in;
4890 	unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4891 	service = make_fixnum (ntohs (saddr.in.sin_port));
4892 	for (int i = 0; i < 4; i++)
4893 	  args[nargs++] = make_fixnum (ip[i]);
4894 	host = Fformat (5, args + 1);
4895 	args[nargs++] = service;
4896       }
4897       break;
4898 
4899 #ifdef AF_INET6
4900     case AF_INET6:
4901       {
4902 	args[nargs++] = procname_format_in6;
4903 	args[nargs++] = host_format_in6;
4904 	DECLARE_POINTER_ALIAS (ip6, uint16_t, &saddr.in6.sin6_addr);
4905 	service = make_fixnum (ntohs (saddr.in.sin_port));
4906 	for (int i = 0; i < 8; i++)
4907 	  args[nargs++] = make_fixnum (ip6[i]);
4908 	host = Fformat (9, args + 1);
4909 	args[nargs++] = service;
4910       }
4911       break;
4912 #endif
4913 
4914     default:
4915       args[nargs++] = procname_format_default;
4916       nargs++;
4917       args[nargs++] = make_fixnum (connect_counter);
4918       break;
4919     }
4920 
4921   /* Create a new buffer name for this process if it doesn't have a
4922      filter.  The new buffer name is based on the buffer name or
4923      process name of the server process concatenated with the caller
4924      identification.  */
4925 
4926   if (!(EQ (ps->filter, Qinternal_default_process_filter)
4927 	|| EQ (ps->filter, Qt)))
4928     buffer = Qnil;
4929   else
4930     {
4931       buffer = ps->buffer;
4932       if (!NILP (buffer))
4933 	buffer = Fbuffer_name (buffer);
4934       else
4935 	buffer = ps->name;
4936       if (!NILP (buffer))
4937 	{
4938 	  args[1] = buffer;
4939 	  buffer = Fget_buffer_create (Fformat (nargs, args), Qnil);
4940 	}
4941     }
4942 
4943   /* Generate a unique name for the new server process.  Combine the
4944      server process name with the caller identification.  */
4945 
4946   args[1] = ps->name;
4947   Lisp_Object name = Fformat (nargs, args);
4948   Lisp_Object proc = make_process (name);
4949 
4950   eassert (0 <= s && s < FD_SETSIZE);
4951   chan_process[s] = proc;
4952 
4953   fcntl (s, F_SETFL, O_NONBLOCK);
4954 
4955   p = XPROCESS (proc);
4956 
4957   /* Build new contact information for this setup.  */
4958   contact = Fcopy_sequence (ps->childp);
4959   contact = Fplist_put (contact, QCserver, Qnil);
4960   contact = Fplist_put (contact, QChost, host);
4961   if (!NILP (service))
4962     contact = Fplist_put (contact, QCservice, service);
4963   contact = Fplist_put (contact, QCremote,
4964 			conv_sockaddr_to_lisp (&saddr.sa, len));
4965 #ifdef HAVE_GETSOCKNAME
4966   len = sizeof saddr;
4967   if (getsockname (s, &saddr.sa, &len) == 0)
4968     contact = Fplist_put (contact, QClocal,
4969 			  conv_sockaddr_to_lisp (&saddr.sa, len));
4970 #endif
4971 
4972   pset_childp (p, contact);
4973   pset_plist (p, Fcopy_sequence (ps->plist));
4974   pset_type (p, Qnetwork);
4975 
4976   pset_buffer (p, buffer);
4977   pset_sentinel (p, ps->sentinel);
4978   pset_filter (p, ps->filter);
4979   eassert (NILP (p->command));
4980   eassert (p->pid == 0);
4981 
4982   /* Discard the unwind protect for closing S.  */
4983   specpdl_ptr = specpdl + count;
4984 
4985   p->open_fd[SUBPROCESS_STDIN] = s;
4986   p->infd  = s;
4987   p->outfd = s;
4988   pset_status (p, Qrun);
4989 
4990   /* Client processes for accepted connections are not stopped initially.  */
4991   if (!EQ (p->filter, Qt))
4992     add_process_read_fd (s);
4993   if (s > max_desc)
4994     max_desc = s;
4995 
4996   /* Setup coding system for new process based on server process.
4997      This seems to be the proper thing to do, as the coding system
4998      of the new process should reflect the settings at the time the
4999      server socket was opened; not the current settings.  */
5000 
5001   pset_decode_coding_system (p, ps->decode_coding_system);
5002   pset_encode_coding_system (p, ps->encode_coding_system);
5003   setup_process_coding_systems (proc);
5004 
5005   pset_decoding_buf (p, empty_unibyte_string);
5006   eassert (p->decoding_carryover == 0);
5007   pset_encoding_buf (p, empty_unibyte_string);
5008 
5009   p->inherit_coding_system_flag
5010     = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
5011 
5012   AUTO_STRING (dash, "-");
5013   AUTO_STRING (nl, "\n");
5014   Lisp_Object host_string = STRINGP (host) ? host : dash;
5015 
5016   if (!NILP (ps->log))
5017     {
5018       AUTO_STRING (accept_from, "accept from ");
5019       call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
5020     }
5021 
5022   AUTO_STRING (open_from, "open from ");
5023   exec_sentinel (proc, concat3 (open_from, host_string, nl));
5024 }
5025 
5026 #ifdef HAVE_GETADDRINFO_A
5027 static Lisp_Object
check_for_dns(Lisp_Object proc)5028 check_for_dns (Lisp_Object proc)
5029 {
5030   struct Lisp_Process *p = XPROCESS (proc);
5031   Lisp_Object addrinfos = Qnil;
5032 
5033   /* Sanity check. */
5034   if (! p->dns_request)
5035     return Qnil;
5036 
5037   int ret = gai_error (p->dns_request);
5038   if (ret == EAI_INPROGRESS)
5039     return Qt;
5040 
5041   /* We got a response. */
5042   if (ret == 0)
5043     {
5044       struct addrinfo *res;
5045 
5046       for (res = p->dns_request->ar_result; res; res = res->ai_next)
5047 	addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
5048 
5049       addrinfos = Fnreverse (addrinfos);
5050     }
5051   /* The DNS lookup failed. */
5052   else if (connecting_status (p->status))
5053     {
5054       deactivate_process (proc);
5055       pset_status (p, (list2
5056 		       (Qfailed,
5057 			concat3 (build_string ("Name lookup of "),
5058 				 build_string (p->dns_request->ar_name),
5059 				 build_string (" failed")))));
5060     }
5061 
5062   free_dns_request (proc);
5063 
5064   /* This process should not already be connected (or killed). */
5065   if (! connecting_status (p->status))
5066     return Qnil;
5067 
5068   return addrinfos;
5069 }
5070 
5071 #endif /* HAVE_GETADDRINFO_A */
5072 
5073 static void
wait_for_socket_fds(Lisp_Object process,char const * name)5074 wait_for_socket_fds (Lisp_Object process, char const *name)
5075 {
5076   while (XPROCESS (process)->infd < 0
5077 	 && connecting_status (XPROCESS (process)->status))
5078     {
5079       add_to_log ("Waiting for socket from %s...", build_string (name));
5080       wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
5081     }
5082 }
5083 
5084 static void
wait_while_connecting(Lisp_Object process)5085 wait_while_connecting (Lisp_Object process)
5086 {
5087   while (connecting_status (XPROCESS (process)->status))
5088     {
5089       add_to_log ("Waiting for connection...");
5090       wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
5091     }
5092 }
5093 
5094 static void
wait_for_tls_negotiation(Lisp_Object process)5095 wait_for_tls_negotiation (Lisp_Object process)
5096 {
5097 #ifdef HAVE_GNUTLS
5098   while (XPROCESS (process)->gnutls_p
5099 	 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
5100     {
5101       add_to_log ("Waiting for TLS...");
5102       wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
5103     }
5104 #endif
5105 }
5106 
5107 static void
wait_reading_process_output_unwind(int data)5108 wait_reading_process_output_unwind (int data)
5109 {
5110   clear_waiting_thread_info ();
5111   waiting_for_user_input_p = data;
5112 }
5113 
5114 /* This is here so breakpoints can be put on it.  */
5115 static void
wait_reading_process_output_1(void)5116 wait_reading_process_output_1 (void)
5117 {
5118 }
5119 
5120 /* Read and dispose of subprocess output while waiting for timeout to
5121    elapse and/or keyboard input to be available.
5122 
5123    TIME_LIMIT is:
5124      timeout in seconds
5125      If negative, gobble data immediately available but don't wait for any.
5126 
5127    NSECS is:
5128      an additional duration to wait, measured in nanoseconds
5129      If TIME_LIMIT is zero, then:
5130        If NSECS == 0, there is no limit.
5131        If NSECS > 0, the timeout consists of NSECS only.
5132        If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
5133 
5134    READ_KBD is:
5135      0 to ignore keyboard input, or
5136      1 to return when input is available, or
5137     -1 meaning caller will actually read the input, so don't throw to
5138        the quit handler
5139 
5140    DO_DISPLAY means redisplay should be done to show subprocess
5141      output that arrives.
5142 
5143    If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
5144      (and gobble terminal input into the buffer if any arrives).
5145 
5146    If WAIT_PROC is specified, wait until something arrives from that
5147      process.
5148 
5149    If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
5150      (suspending output from other processes).  A negative value
5151      means don't run any timers either.
5152 
5153    Return positive if we received input from WAIT_PROC (or from any
5154    process if WAIT_PROC is null), zero if we attempted to receive
5155    input but got none, and negative if we didn't even try.  */
5156 
5157 int
wait_reading_process_output(intmax_t time_limit,int nsecs,int read_kbd,bool do_display,Lisp_Object wait_for_cell,struct Lisp_Process * wait_proc,int just_wait_proc)5158 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
5159 			     bool do_display,
5160 			     Lisp_Object wait_for_cell,
5161 			     struct Lisp_Process *wait_proc, int just_wait_proc)
5162 {
5163   static int last_read_channel = -1;
5164   int channel, nfds;
5165   fd_set Available;
5166   fd_set Writeok;
5167   bool check_write;
5168   int check_delay;
5169   bool no_avail;
5170   int xerrno;
5171   Lisp_Object proc;
5172   struct timespec timeout, end_time, timer_delay;
5173   struct timespec got_output_end_time = invalid_timespec ();
5174   enum { MINIMUM = -1, TIMEOUT, FOREVER } wait;
5175   int got_some_output = -1;
5176   uintmax_t prev_wait_proc_nbytes_read = wait_proc ? wait_proc->nbytes_read : 0;
5177 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5178   bool retry_for_async;
5179 #endif
5180   ptrdiff_t count = SPECPDL_INDEX ();
5181 
5182   /* Close to the current time if known, an invalid timespec otherwise.  */
5183   struct timespec now = invalid_timespec ();
5184 
5185   eassert (wait_proc == NULL
5186 	   || NILP (wait_proc->thread)
5187 	   || XTHREAD (wait_proc->thread) == current_thread);
5188 
5189   FD_ZERO (&Available);
5190   FD_ZERO (&Writeok);
5191 
5192   if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
5193       && !(CONSP (wait_proc->status)
5194 	   && EQ (XCAR (wait_proc->status), Qexit)))
5195     message1 ("Blocking call to accept-process-output with quit inhibited!!");
5196 
5197   record_unwind_protect_int (wait_reading_process_output_unwind,
5198 			     waiting_for_user_input_p);
5199   waiting_for_user_input_p = read_kbd;
5200 
5201   if (TYPE_MAXIMUM (time_t) < time_limit)
5202     time_limit = TYPE_MAXIMUM (time_t);
5203 
5204   if (time_limit < 0 || nsecs < 0)
5205     wait = MINIMUM;
5206   else if (time_limit > 0 || nsecs > 0)
5207     {
5208       wait = TIMEOUT;
5209       now = current_timespec ();
5210       end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5211     }
5212   else
5213     wait = FOREVER;
5214 
5215   while (1)
5216     {
5217       bool process_skipped = false;
5218       bool wrapped;
5219       int channel_start;
5220 
5221       /* If calling from keyboard input, do not quit
5222 	 since we want to return C-g as an input character.
5223 	 Otherwise, do pending quit if requested.  */
5224       if (read_kbd >= 0)
5225 	maybe_quit ();
5226       else if (pending_signals)
5227 	process_pending_signals ();
5228 
5229       /* Exit now if the cell we're waiting for became non-nil.  */
5230       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5231 	break;
5232 
5233       eassert (max_desc < FD_SETSIZE);
5234 
5235 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5236       {
5237 	Lisp_Object process_list_head, aproc;
5238 	struct Lisp_Process *p;
5239 
5240 	retry_for_async = false;
5241 	FOR_EACH_PROCESS(process_list_head, aproc)
5242 	  {
5243 	    p = XPROCESS (aproc);
5244 
5245 	    if (! wait_proc || p == wait_proc)
5246 	      {
5247 #ifdef HAVE_GETADDRINFO_A
5248 		/* Check for pending DNS requests. */
5249 		if (p->dns_request)
5250 		  {
5251 		    Lisp_Object addrinfos = check_for_dns (aproc);
5252 		    if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5253 		      connect_network_socket (aproc, addrinfos, Qnil);
5254 		    else
5255 		      retry_for_async = true;
5256 		  }
5257 #endif
5258 #ifdef HAVE_GNUTLS
5259 		/* Continue TLS negotiation. */
5260 		if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5261 		    && p->is_non_blocking_client
5262 		    /* Don't proceed until we have established a connection. */
5263 		    && !(fd_callback_info[p->outfd].flags
5264 			 & NON_BLOCKING_CONNECT_FD))
5265 		  {
5266 		    gnutls_try_handshake (p);
5267 		    p->gnutls_handshakes_tried++;
5268 
5269 		    if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5270 		      {
5271 			gnutls_verify_boot (aproc, Qnil);
5272 			finish_after_tls_connection (aproc);
5273 		      }
5274 		    else
5275 		      {
5276 			retry_for_async = true;
5277 			if (p->gnutls_handshakes_tried
5278 			    > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5279 			  {
5280 			    deactivate_process (aproc);
5281 			    pset_status (p, list2 (Qfailed,
5282 						   build_string ("TLS negotiation failed")));
5283 			  }
5284 		      }
5285 		  }
5286 #endif
5287 	      }
5288 	  }
5289       }
5290 #endif /* GETADDRINFO_A or GNUTLS */
5291 
5292       /* Compute time from now till when time limit is up.  */
5293       /* Exit if already run out.  */
5294       if (wait == TIMEOUT)
5295 	{
5296 	  if (!timespec_valid_p (now))
5297 	    now = current_timespec ();
5298 	  if (timespec_cmp (end_time, now) <= 0)
5299 	    break;
5300 	  timeout = timespec_sub (end_time, now);
5301 	}
5302       else
5303 	timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5304 
5305       /* Normally we run timers here.
5306 	 But not if wait_for_cell; in those cases,
5307 	 the wait is supposed to be short,
5308 	 and those callers cannot handle running arbitrary Lisp code here.  */
5309       if (NILP (wait_for_cell)
5310 	  && just_wait_proc >= 0)
5311 	{
5312 	  do
5313 	    {
5314 	      unsigned old_timers_run = timers_run;
5315 
5316 	      timer_delay = timer_check ();
5317 
5318 	      if (timers_run != old_timers_run && do_display)
5319 		/* We must retry, since a timer may have requeued itself
5320 		   and that could alter the time_delay.  */
5321 		redisplay_preserve_echo_area (9);
5322 	      else
5323 		break;
5324 	    }
5325 	  while (!detect_input_pending ());
5326 
5327 	  /* If there is unread keyboard input, also return.  */
5328 	  if (read_kbd != 0
5329 	      && requeued_events_pending_p ())
5330 	    break;
5331 
5332           /* This is so a breakpoint can be put here.  */
5333           if (!timespec_valid_p (timer_delay))
5334               wait_reading_process_output_1 ();
5335         }
5336 
5337       /* Cause C-g signals to take immediate action,
5338 	 and cause input available signals to zero out timeout.
5339 
5340 	 It is important that we do this before checking for process
5341 	 activity.  If we get a SIGCHLD after the explicit checks for
5342 	 process activity, timeout is the only way we will know.  */
5343       if (read_kbd < 0 && kbd_is_ours ())
5344 	set_waiting_for_input (&timeout);
5345 
5346       /* If status of something has changed, and no input is
5347 	 available, notify the user of the change right away.  After
5348 	 this explicit check, we'll let the SIGCHLD handler zap
5349 	 timeout to get our attention.  */
5350       if (update_tick != process_tick)
5351 	{
5352 	  fd_set Atemp;
5353 	  fd_set Ctemp;
5354 
5355           if (kbd_on_hold_p ())
5356             FD_ZERO (&Atemp);
5357           else
5358             compute_input_wait_mask (&Atemp);
5359 	  compute_write_mask (&Ctemp);
5360 
5361 	  /* If a process status has changed, the child signal pipe
5362 	     will likely be readable.  We want to ignore it for now,
5363 	     because otherwise we wouldn't run into a timeout
5364 	     below.  */
5365 	  int fd = child_signal_read_fd;
5366 	  eassert (fd < FD_SETSIZE);
5367 	  if (0 <= fd)
5368 	    FD_CLR (fd, &Atemp);
5369 
5370 	  timeout = make_timespec (0, 0);
5371 	  if ((thread_select (pselect, max_desc + 1,
5372 			      &Atemp,
5373 			      (num_pending_connects > 0 ? &Ctemp : NULL),
5374 			      NULL, &timeout, NULL)
5375 	       <= 0))
5376 	    {
5377 	      /* It's okay for us to do this and then continue with
5378 		 the loop, since timeout has already been zeroed out.  */
5379 	      clear_waiting_for_input ();
5380 	      got_some_output = status_notify (NULL, wait_proc);
5381 	      if (do_display) redisplay_preserve_echo_area (13);
5382 	    }
5383 	}
5384 
5385       /* Don't wait for output from a non-running process.  Just
5386 	 read whatever data has already been received.  */
5387       if (wait_proc && wait_proc->raw_status_new)
5388 	update_status (wait_proc);
5389       if (wait_proc
5390 	  && ! EQ (wait_proc->status, Qrun)
5391 	  && ! connecting_status (wait_proc->status))
5392 	{
5393 	  bool read_some_bytes = false;
5394 
5395 	  clear_waiting_for_input ();
5396 
5397 	  /* If data can be read from the process, do so until exhausted.  */
5398 	  if (wait_proc->infd >= 0)
5399 	    {
5400 	      unsigned int count = 0;
5401 	      XSETPROCESS (proc, wait_proc);
5402 
5403 	      while (true)
5404 		{
5405 		  int nread = read_process_output (proc, wait_proc->infd);
5406 		  rarely_quit (++count);
5407 		  if (nread < 0)
5408 		    {
5409 		      if (errno != EINTR)
5410 			break;
5411 		    }
5412 		  else
5413 		    {
5414 		      if (got_some_output < nread)
5415 			got_some_output = nread;
5416 		      if (nread == 0)
5417 			break;
5418 		      read_some_bytes = true;
5419 		    }
5420 		}
5421 	    }
5422 
5423 	  if (read_some_bytes && do_display)
5424 	    redisplay_preserve_echo_area (10);
5425 
5426 	  break;
5427 	}
5428 
5429       /* Wait till there is something to do.  */
5430 
5431       if (wait_proc && just_wait_proc)
5432 	{
5433 	  if (wait_proc->infd < 0)  /* Terminated.  */
5434 	    break;
5435 	  FD_SET (wait_proc->infd, &Available);
5436 	  check_delay = 0;
5437           check_write = 0;
5438 	}
5439       else if (!NILP (wait_for_cell))
5440 	{
5441 	  compute_non_process_wait_mask (&Available);
5442 	  check_delay = 0;
5443 	  check_write = 0;
5444 	}
5445       else
5446 	{
5447 	  if (! read_kbd)
5448 	    compute_non_keyboard_wait_mask (&Available);
5449 	  else
5450 	    compute_input_wait_mask (&Available);
5451 	  compute_write_mask (&Writeok);
5452  	  check_delay = wait_proc ? 0 : process_output_delay_count;
5453 	  check_write = true;
5454 	}
5455 
5456       /* We have to be informed when we receive a SIGCHLD signal for
5457 	 an asynchronous process.  Otherwise this might deadlock if we
5458 	 receive a SIGCHLD during `pselect'.  */
5459       int child_fd = child_signal_read_fd;
5460       eassert (child_fd < FD_SETSIZE);
5461       if (0 <= child_fd)
5462         FD_SET (child_fd, &Available);
5463 
5464       /* If frame size has changed or the window is newly mapped,
5465 	 redisplay now, before we start to wait.  There is a race
5466 	 condition here; if a SIGIO arrives between now and the select
5467 	 and indicates that a frame is trashed, the select may block
5468 	 displaying a trashed screen.  */
5469       if (frame_garbaged && do_display)
5470 	{
5471 	  clear_waiting_for_input ();
5472 	  redisplay_preserve_echo_area (11);
5473 	  if (read_kbd < 0 && kbd_is_ours ())
5474 	    set_waiting_for_input (&timeout);
5475 	}
5476 
5477       /* Skip the `select' call if input is available and we're
5478 	 waiting for keyboard input or a cell change (which can be
5479 	 triggered by processing X events).  In the latter case, set
5480 	 nfds to 1 to avoid breaking the loop.  */
5481       no_avail = 0;
5482       if ((read_kbd || !NILP (wait_for_cell))
5483 	  && detect_input_pending ())
5484 	{
5485 	  nfds = read_kbd ? 0 : 1;
5486 	  no_avail = 1;
5487 	  FD_ZERO (&Available);
5488 	}
5489       else
5490 	{
5491 #ifdef HAVE_GNUTLS
5492 	  int tls_nfds;
5493 	  fd_set tls_available;
5494 #endif
5495 	  /* Set the timeout for adaptive read buffering if any
5496 	     process has non-zero read_output_skip and non-zero
5497 	     read_output_delay, and we are not reading output for a
5498 	     specific process.  It is not executed if
5499 	     Vprocess_adaptive_read_buffering is nil.  */
5500 	  if (process_output_skip && check_delay > 0)
5501 	    {
5502 	      int adaptive_nsecs = timeout.tv_nsec;
5503 	      if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5504 		adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5505 	      for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5506 		{
5507 		  proc = chan_process[channel];
5508 		  if (NILP (proc))
5509 		    continue;
5510 		  /* Find minimum non-zero read_output_delay among the
5511 		     processes with non-zero read_output_skip.  */
5512 		  if (XPROCESS (proc)->read_output_delay > 0)
5513 		    {
5514 		      check_delay--;
5515 		      if (!XPROCESS (proc)->read_output_skip)
5516 			continue;
5517 		      FD_CLR (channel, &Available);
5518 		      process_skipped = true;
5519 		      XPROCESS (proc)->read_output_skip = 0;
5520 		      if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5521 			adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5522 		    }
5523 		}
5524 	      timeout = make_timespec (0, adaptive_nsecs);
5525 	      process_output_skip = 0;
5526 	    }
5527 
5528 	  /* If we've got some output and haven't limited our timeout
5529 	     with adaptive read buffering, limit it. */
5530 	  if (got_some_output > 0 && !process_skipped
5531 	      && (timeout.tv_sec
5532 		  || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5533 	    timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5534 
5535 
5536 	  if (NILP (wait_for_cell) && just_wait_proc >= 0
5537 	      && timespec_valid_p (timer_delay)
5538 	      && timespec_cmp (timer_delay, timeout) < 0)
5539 	    {
5540 	      if (!timespec_valid_p (now))
5541 		now = current_timespec ();
5542 	      struct timespec timeout_abs = timespec_add (now, timeout);
5543 	      if (!timespec_valid_p (got_output_end_time)
5544 		  || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5545 		got_output_end_time = timeout_abs;
5546 	      timeout = timer_delay;
5547 	    }
5548 	  else
5549 	    got_output_end_time = invalid_timespec ();
5550 
5551 	  /* NOW can become inaccurate if time can pass during pselect.  */
5552 	  if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5553 	    now = invalid_timespec ();
5554 
5555 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5556 	  if (retry_for_async
5557 	      && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5558 	    {
5559 	      timeout.tv_sec = 0;
5560 	      timeout.tv_nsec = ASYNC_RETRY_NSEC;
5561 	    }
5562 #endif
5563 
5564 #ifdef HAVE_GNUTLS
5565           /* GnuTLS buffers data internally. We need to check if some
5566 	     data is available in the buffers manually before the select.
5567 	     And if so, we need to skip the select which could block. */
5568 	  FD_ZERO (&tls_available);
5569 	  tls_nfds = 0;
5570 	  for (channel = 0; channel < FD_SETSIZE; ++channel)
5571 	    if (! NILP (chan_process[channel])
5572 		&& FD_ISSET (channel, &Available))
5573 	      {
5574 		struct Lisp_Process *p = XPROCESS (chan_process[channel]);
5575 		if (p
5576 		    && p->gnutls_p && p->gnutls_state
5577 		    && emacs_gnutls_record_check_pending (p->gnutls_state) > 0)
5578 		  {
5579 		    tls_nfds++;
5580 		    eassert (p->infd == channel);
5581 		    FD_SET (p->infd, &tls_available);
5582 		  }
5583 	      }
5584 	  /* If wait_proc is somebody else, we have to wait in select
5585 	     as usual.  Otherwise, clobber the timeout. */
5586 	  if (tls_nfds > 0
5587 	      && (!wait_proc ||
5588 		  (wait_proc->infd >= 0
5589 		   && FD_ISSET (wait_proc->infd, &tls_available))))
5590 	    timeout = make_timespec (0, 0);
5591 #endif
5592 
5593 #if !defined USABLE_SIGIO && !defined WINDOWSNT
5594 	  /* If we're polling for input, don't get stuck in select for
5595 	     more than 25 msec. */
5596 	  struct timespec short_timeout = make_timespec (0, 25000000);
5597 	  if ((read_kbd || !NILP (wait_for_cell))
5598 	      && timespec_cmp (short_timeout, timeout) < 0)
5599 	    timeout = short_timeout;
5600 #endif
5601 
5602 	  /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c.  */
5603 #if defined HAVE_GLIB && !defined HAVE_NS
5604 	  nfds = xg_select (max_desc + 1,
5605 			    &Available, (check_write ? &Writeok : 0),
5606 			    NULL, &timeout, NULL);
5607 #elif defined HAVE_NS
5608           /* And NS builds call thread_select in ns_select. */
5609           nfds = ns_select (max_desc + 1,
5610 			    &Available, (check_write ? &Writeok : 0),
5611 			    NULL, &timeout, NULL);
5612 #else  /* !HAVE_GLIB */
5613 	  nfds = thread_select (pselect, max_desc + 1,
5614 				&Available,
5615 				(check_write ? &Writeok : 0),
5616 				NULL, &timeout, NULL);
5617 #endif	/* !HAVE_GLIB */
5618 
5619 #ifdef HAVE_GNUTLS
5620 	  /* Merge tls_available into Available. */
5621 	  if (tls_nfds > 0)
5622 	    {
5623 	      if (nfds == 0 || (nfds < 0 && errno == EINTR))
5624 		{
5625 		  /* Fast path, just copy. */
5626 		  nfds = tls_nfds;
5627 		  Available = tls_available;
5628 		}
5629 	      else if (nfds > 0)
5630 		/* Slow path, merge one by one.  Note: nfds does not need
5631 		   to be accurate, just positive is enough. */
5632 		for (channel = 0; channel < FD_SETSIZE; ++channel)
5633 		  if (FD_ISSET(channel, &tls_available))
5634 		    FD_SET(channel, &Available);
5635 	    }
5636 #endif
5637 	}
5638 
5639       xerrno = errno;
5640 
5641       /* Make C-g and alarm signals set flags again.  */
5642       clear_waiting_for_input ();
5643 
5644       /*  If we woke up due to SIGWINCH, actually change size now.  */
5645       do_pending_window_change (0);
5646 
5647       if (nfds == 0)
5648 	{
5649           /* Exit the main loop if we've passed the requested timeout,
5650              or have read some bytes from our wait_proc (either directly
5651              in this call or indirectly through timers / process filters),
5652              or aren't skipping processes and got some output and
5653              haven't lowered our timeout due to timers or SIGIO and
5654              have waited a long amount of time due to repeated
5655              timers.  */
5656 	  struct timespec huge_timespec
5657 	    = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_HZ);
5658 	  struct timespec cmp_time = huge_timespec;
5659 	  if (wait < TIMEOUT
5660               || (wait_proc
5661                   && wait_proc->nbytes_read != prev_wait_proc_nbytes_read))
5662 	    break;
5663 	  if (wait == TIMEOUT)
5664 	    cmp_time = end_time;
5665 	  if (!process_skipped && got_some_output > 0
5666 	      && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5667 	    {
5668 	      if (!timespec_valid_p (got_output_end_time))
5669 		break;
5670 	      if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5671 		cmp_time = got_output_end_time;
5672 	    }
5673 	  if (timespec_cmp (cmp_time, huge_timespec) < 0)
5674 	    {
5675 	      now = current_timespec ();
5676 	      if (timespec_cmp (cmp_time, now) <= 0)
5677 		break;
5678 	    }
5679 	}
5680 
5681       if (nfds < 0)
5682 	{
5683 	  if (xerrno == EINTR)
5684 	    no_avail = 1;
5685 	  else if (xerrno == EBADF)
5686 	    emacs_abort ();
5687 	  else
5688 	    report_file_errno ("Failed select", Qnil, xerrno);
5689 	}
5690 
5691       /* Check for keyboard input.  */
5692       /* If there is any, return immediately
5693 	 to give it higher priority than subprocesses.  */
5694 
5695       if (read_kbd != 0)
5696 	{
5697 	  bool leave = false;
5698 
5699 	  if (detect_input_pending_run_timers (do_display))
5700 	    {
5701 	      swallow_events (do_display);
5702 	      if (detect_input_pending_run_timers (do_display))
5703 		leave = true;
5704 	    }
5705 
5706 	  if (leave)
5707 	    break;
5708 	}
5709 
5710       /* If there is unread keyboard input, also return.  */
5711       if (read_kbd != 0
5712 	  && requeued_events_pending_p ())
5713 	break;
5714 
5715       /* If we are not checking for keyboard input now,
5716 	 do process events (but don't run any timers).
5717 	 This is so that X events will be processed.
5718 	 Otherwise they may have to wait until polling takes place.
5719 	 That would causes delays in pasting selections, for example.
5720 
5721 	 (We used to do this only if wait_for_cell.)  */
5722       if (read_kbd == 0 && detect_input_pending ())
5723 	{
5724 	  swallow_events (do_display);
5725 #if 0  /* Exiting when read_kbd doesn't request that seems wrong, though.  */
5726 	  if (detect_input_pending ())
5727 	    break;
5728 #endif
5729 	}
5730 
5731       /* Exit now if the cell we're waiting for became non-nil.  */
5732       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5733 	break;
5734 
5735 #if defined (USABLE_SIGIO) || defined (USABLE_SIGPOLL)
5736       /* If we think we have keyboard input waiting, but didn't get SIGIO,
5737 	 go read it.  This can happen with X on BSD after logging out.
5738 	 In that case, there really is no input and no SIGIO,
5739 	 but select says there is input.  */
5740 
5741       if (read_kbd && interrupt_input
5742 	  && keyboard_bit_set (&Available) && ! noninteractive)
5743 #ifdef USABLE_SIGIO
5744 	handle_input_available_signal (SIGIO);
5745 #else
5746 	handle_input_available_signal (SIGPOLL);
5747 #endif
5748 #endif
5749 
5750       /* If checking input just got us a size-change event from X,
5751 	 obey it now if we should.  */
5752       if (read_kbd || ! NILP (wait_for_cell))
5753 	do_pending_window_change (0);
5754 
5755       /* Check for data from a process.  */
5756       if (no_avail || nfds == 0)
5757 	continue;
5758 
5759       for (channel = 0; channel <= max_desc; ++channel)
5760         {
5761           struct fd_callback_data *d = &fd_callback_info[channel];
5762           if (d->func
5763 	      && ((d->flags & FOR_READ
5764 		   && FD_ISSET (channel, &Available))
5765 		  || ((d->flags & FOR_WRITE)
5766 		      && FD_ISSET (channel, &Writeok))))
5767             d->func (channel, d->data);
5768 	}
5769 
5770       /* Do round robin if `process-pritoritize-lower-fds' is nil. */
5771       channel_start
5772 	= process_prioritize_lower_fds ? 0 : last_read_channel + 1;
5773 
5774       for (channel = channel_start, wrapped = false;
5775 	   !wrapped || (channel < channel_start && channel <= max_desc);
5776 	   channel++)
5777 	{
5778 	  if (channel > max_desc)
5779 	    {
5780 	      wrapped = true;
5781 	      channel = -1;
5782 	      continue;
5783 	    }
5784 
5785 	  if (FD_ISSET (channel, &Available)
5786 	      && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5787 		  == PROCESS_FD))
5788 	    {
5789 	      int nread;
5790 
5791 	      /* If waiting for this channel, arrange to return as
5792 		 soon as no more input to be processed.  No more
5793 		 waiting.  */
5794 	      proc = chan_process[channel];
5795 	      if (NILP (proc))
5796 		continue;
5797 
5798 	      /* If this is a server stream socket, accept connection.  */
5799 	      if (EQ (XPROCESS (proc)->status, Qlisten))
5800 		{
5801 		  server_accept_connection (proc, channel);
5802 		  continue;
5803 		}
5804 
5805 	      /* Read data from the process, starting with our
5806 		 buffered-ahead character if we have one.  */
5807 
5808 	      nread = read_process_output (proc, channel);
5809 	      if ((!wait_proc || wait_proc == XPROCESS (proc))
5810 		  && got_some_output < nread)
5811 		got_some_output = nread;
5812 	      if (nread > 0)
5813 		{
5814 		  /* Vacuum up any leftovers without waiting.  */
5815 		  if (wait_proc == XPROCESS (proc))
5816 		    wait = MINIMUM;
5817 		  /* Since read_process_output can run a filter,
5818 		     which can call accept-process-output,
5819 		     don't try to read from any other processes
5820 		     before doing the select again.  */
5821 		  FD_ZERO (&Available);
5822 		  last_read_channel = channel;
5823 
5824 		  if (do_display)
5825 		    redisplay_preserve_echo_area (12);
5826 		}
5827 	      else if (nread == -1 && would_block (errno))
5828 		;
5829 #ifdef HAVE_PTYS
5830 	      /* On some OSs with ptys, when the process on one end of
5831 		 a pty exits, the other end gets an error reading with
5832 		 errno = EIO instead of getting an EOF (0 bytes read).
5833 		 Therefore, if we get an error reading and errno =
5834 		 EIO, just continue, because the child process has
5835 		 exited and should clean itself up soon (e.g. when we
5836 		 get a SIGCHLD).  */
5837 	      else if (nread == -1 && errno == EIO)
5838 		{
5839 		  struct Lisp_Process *p = XPROCESS (proc);
5840 
5841 		  /* Clear the descriptor now, so we only raise the
5842 		     signal once.  */
5843 		  delete_read_fd (channel);
5844 
5845 		  if (p->pid == -2)
5846 		    {
5847 		      /* If the EIO occurs on a pty, the SIGCHLD handler's
5848 			 waitpid call will not find the process object to
5849 			 delete.  Do it here.  */
5850 		      p->tick = ++process_tick;
5851 		      pset_status (p, Qfailed);
5852 		    }
5853 		}
5854 #endif /* HAVE_PTYS */
5855 	      /* If we can detect process termination, don't consider the
5856 		 process gone just because its pipe is closed.  */
5857 	      else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5858 		       && !PIPECONN_P (proc))
5859 		;
5860 	      else if (nread == 0 && PIPECONN_P (proc))
5861 		{
5862 		  /* Preserve status of processes already terminated.  */
5863 		  XPROCESS (proc)->tick = ++process_tick;
5864 		  deactivate_process (proc);
5865 		  if (EQ (XPROCESS (proc)->status, Qrun))
5866 		    pset_status (XPROCESS (proc),
5867 				 list2 (Qexit, make_fixnum (0)));
5868 		}
5869 	      else
5870 		{
5871 		  /* Preserve status of processes already terminated.  */
5872 		  XPROCESS (proc)->tick = ++process_tick;
5873 		  deactivate_process (proc);
5874 		  if (XPROCESS (proc)->raw_status_new)
5875 		    update_status (XPROCESS (proc));
5876 		  if (EQ (XPROCESS (proc)->status, Qrun))
5877 		    pset_status (XPROCESS (proc),
5878 				 list2 (Qexit, make_fixnum (256)));
5879 		}
5880 	    }
5881 	  if (FD_ISSET (channel, &Writeok)
5882 	      && (fd_callback_info[channel].flags
5883 		  & NON_BLOCKING_CONNECT_FD) != 0)
5884 	    {
5885 	      struct Lisp_Process *p;
5886 
5887 	      delete_write_fd (channel);
5888 
5889 	      proc = chan_process[channel];
5890 	      if (NILP (proc))
5891 		continue;
5892 
5893 	      p = XPROCESS (proc);
5894 
5895 #ifndef WINDOWSNT
5896 	      {
5897 		socklen_t xlen = sizeof (xerrno);
5898 		if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5899 		  xerrno = errno;
5900 	      }
5901 #else
5902 	      /* On MS-Windows, getsockopt clears the error for the
5903 		 entire process, which may not be the right thing; see
5904 		 w32.c.  Use getpeername instead.  */
5905 	      {
5906 		struct sockaddr pname;
5907 		socklen_t pnamelen = sizeof (pname);
5908 
5909 		/* If connection failed, getpeername will fail.  */
5910 		xerrno = 0;
5911 		if (getpeername (channel, &pname, &pnamelen) < 0)
5912 		  {
5913 		    /* Obtain connect failure code through error slippage.  */
5914 		    char dummy;
5915 		    xerrno = errno;
5916 		    if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5917 		      xerrno = errno;
5918 		  }
5919 	      }
5920 #endif
5921 	      if (xerrno)
5922 		{
5923 		  Lisp_Object addrinfos
5924 		    = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5925 		  if (!NILP (addrinfos))
5926 		    XSETCDR (p->status, XCDR (addrinfos));
5927 		  else
5928 		    {
5929 		      p->tick = ++process_tick;
5930 		      pset_status (p, list2 (Qfailed, make_fixnum (xerrno)));
5931 		    }
5932 		  deactivate_process (proc);
5933 		  if (!NILP (addrinfos))
5934 		    connect_network_socket (proc, addrinfos, Qnil);
5935 		}
5936 	      else
5937 		{
5938 #ifdef HAVE_GNUTLS
5939 		  /* If we have an incompletely set up TLS connection,
5940 		     then defer the sentinel signaling until
5941 		     later. */
5942 		  if (NILP (p->gnutls_boot_parameters)
5943 		      && !p->gnutls_p)
5944 #endif
5945 		    {
5946 		      pset_status (p, Qrun);
5947 		      /* Execute the sentinel here.  If we had relied on
5948 			 status_notify to do it later, it will read input
5949 			 from the process before calling the sentinel.  */
5950 		      exec_sentinel (proc, build_string ("open\n"));
5951 		    }
5952 
5953 		  if (0 <= p->infd && !EQ (p->filter, Qt)
5954 		      && !EQ (p->command, Qt))
5955 		    add_process_read_fd (p->infd);
5956 		}
5957 	    }
5958 	}			/* End for each file descriptor.  */
5959     }				/* End while exit conditions not met.  */
5960 
5961   unbind_to (count, Qnil);
5962 
5963   /* If calling from keyboard input, do not quit
5964      since we want to return C-g as an input character.
5965      Otherwise, do pending quit if requested.  */
5966   if (read_kbd >= 0)
5967     {
5968       /* Prevent input_pending from remaining set if we quit.  */
5969       clear_input_pending ();
5970       maybe_quit ();
5971     }
5972 
5973   /* Timers and/or process filters that we have run could have themselves called
5974      `accept-process-output' (and by that indirectly this function), thus
5975      possibly reading some (or all) output of wait_proc without us noticing it.
5976      This could potentially lead to an endless wait (dealt with earlier in the
5977      function) and/or a wrong return value (dealt with here).  */
5978   if (wait_proc && wait_proc->nbytes_read != prev_wait_proc_nbytes_read)
5979     got_some_output = min (INT_MAX, (wait_proc->nbytes_read
5980                                      - prev_wait_proc_nbytes_read));
5981 
5982   return got_some_output;
5983 }
5984 
5985 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS.  */
5986 
5987 static Lisp_Object
read_process_output_call(Lisp_Object fun_and_args)5988 read_process_output_call (Lisp_Object fun_and_args)
5989 {
5990   return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5991 }
5992 
5993 static Lisp_Object
read_process_output_error_handler(Lisp_Object error_val)5994 read_process_output_error_handler (Lisp_Object error_val)
5995 {
5996   cmd_error_internal (error_val, "error in process filter: ");
5997   Vinhibit_quit = Qt;
5998   update_echo_area ();
5999   if (process_error_pause_time > 0)
6000     Fsleep_for (make_fixnum (process_error_pause_time), Qnil);
6001   return Qt;
6002 }
6003 
6004 static void
6005 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
6006 				    ssize_t nbytes,
6007 				    struct coding_system *coding);
6008 
6009 /* Read pending output from the process channel,
6010    starting with our buffered-ahead character if we have one.
6011    Yield number of decoded characters read,
6012    or -1 (setting errno) if there is a read error.
6013 
6014    This function reads at most read_process_output_max bytes.
6015    If you want to read all available subprocess output,
6016    you must call it repeatedly until it returns zero.
6017 
6018    The characters read are decoded according to PROC's coding-system
6019    for decoding.  */
6020 
6021 static int
read_process_output(Lisp_Object proc,int channel)6022 read_process_output (Lisp_Object proc, int channel)
6023 {
6024   ssize_t nbytes;
6025   struct Lisp_Process *p = XPROCESS (proc);
6026   eassert (0 <= channel && channel < FD_SETSIZE);
6027   struct coding_system *coding = proc_decode_coding_system[channel];
6028   int carryover = p->decoding_carryover;
6029   ptrdiff_t readmax = clip_to_bounds (1, read_process_output_max, PTRDIFF_MAX);
6030   ptrdiff_t count = SPECPDL_INDEX ();
6031   Lisp_Object odeactivate;
6032   char *chars;
6033 
6034   USE_SAFE_ALLOCA;
6035   chars = SAFE_ALLOCA (sizeof coding->carryover + readmax);
6036 
6037   if (carryover)
6038     /* See the comment above.  */
6039     memcpy (chars, SDATA (p->decoding_buf), carryover);
6040 
6041 #ifdef DATAGRAM_SOCKETS
6042   /* We have a working select, so proc_buffered_char is always -1.  */
6043   if (DATAGRAM_CHAN_P (channel))
6044     {
6045       socklen_t len = datagram_address[channel].len;
6046       do
6047 	nbytes = recvfrom (channel, chars + carryover, readmax,
6048 			   0, datagram_address[channel].sa, &len);
6049       while (nbytes < 0 && errno == EINTR);
6050     }
6051   else
6052 #endif
6053     {
6054       bool buffered = proc_buffered_char[channel] >= 0;
6055       if (buffered)
6056 	{
6057 	  chars[carryover] = proc_buffered_char[channel];
6058 	  proc_buffered_char[channel] = -1;
6059 	}
6060 #ifdef HAVE_GNUTLS
6061       if (p->gnutls_p && p->gnutls_state)
6062 	nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
6063 				    readmax - buffered);
6064       else
6065 #endif
6066 	nbytes = emacs_read (channel, chars + carryover + buffered,
6067 			     readmax - buffered);
6068       if (nbytes > 0 && p->adaptive_read_buffering)
6069 	{
6070 	  int delay = p->read_output_delay;
6071 	  if (nbytes < 256)
6072 	    {
6073 	      if (delay < READ_OUTPUT_DELAY_MAX_MAX)
6074 		{
6075 		  if (delay == 0)
6076 		    process_output_delay_count++;
6077 		  delay += READ_OUTPUT_DELAY_INCREMENT * 2;
6078 		}
6079 	    }
6080 	  else if (delay > 0 && nbytes == readmax - buffered)
6081 	    {
6082 	      delay -= READ_OUTPUT_DELAY_INCREMENT;
6083 	      if (delay == 0)
6084 		process_output_delay_count--;
6085 	    }
6086 	  p->read_output_delay = delay;
6087 	  if (delay)
6088 	    {
6089 	      p->read_output_skip = 1;
6090 	      process_output_skip = 1;
6091 	    }
6092 	}
6093       nbytes += buffered;
6094       nbytes += buffered && nbytes <= 0;
6095     }
6096 
6097   p->decoding_carryover = 0;
6098 
6099   if (nbytes <= 0)
6100     {
6101       if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
6102 	{
6103 	  SAFE_FREE_UNBIND_TO (count, Qnil);
6104 	  return nbytes;
6105 	}
6106       coding->mode |= CODING_MODE_LAST_BLOCK;
6107     }
6108 
6109   /* At this point, NBYTES holds number of bytes just received
6110      (including the one in proc_buffered_char[channel]).  */
6111 
6112   /* Ignore carryover, it's been added by a previous iteration already.  */
6113   p->nbytes_read += nbytes;
6114 
6115   /* Now set NBYTES how many bytes we must decode.  */
6116   nbytes += carryover;
6117 
6118   odeactivate = Vdeactivate_mark;
6119   /* There's no good reason to let process filters change the current
6120      buffer, and many callers of accept-process-output, sit-for, and
6121      friends don't expect current-buffer to be changed from under them.  */
6122   record_unwind_current_buffer ();
6123 
6124   read_and_dispose_of_process_output (p, chars, nbytes, coding);
6125 
6126   /* Handling the process output should not deactivate the mark.  */
6127   Vdeactivate_mark = odeactivate;
6128 
6129   SAFE_FREE_UNBIND_TO (count, Qnil);
6130   return nbytes;
6131 }
6132 
6133 static void
read_and_dispose_of_process_output(struct Lisp_Process * p,char * chars,ssize_t nbytes,struct coding_system * coding)6134 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
6135 				    ssize_t nbytes,
6136 				    struct coding_system *coding)
6137 {
6138   Lisp_Object outstream = p->filter;
6139   Lisp_Object text;
6140   bool outer_running_asynch_code = running_asynch_code;
6141   int waiting = waiting_for_user_input_p;
6142 
6143 #if 0
6144   Lisp_Object obuffer, okeymap;
6145   XSETBUFFER (obuffer, current_buffer);
6146   okeymap = BVAR (current_buffer, keymap);
6147 #endif
6148 
6149   /* We inhibit quit here instead of just catching it so that
6150      hitting ^G when a filter happens to be running won't screw
6151      it up.  */
6152   specbind (Qinhibit_quit, Qt);
6153   specbind (Qlast_nonmenu_event, Qt);
6154 
6155   /* In case we get recursively called,
6156      and we already saved the match data nonrecursively,
6157      save the same match data in safely recursive fashion.  */
6158   if (outer_running_asynch_code)
6159     {
6160       Lisp_Object tem;
6161       /* Don't clobber the CURRENT match data, either!  */
6162       tem = Fmatch_data (Qnil, Qnil, Qnil);
6163       restore_search_regs ();
6164       record_unwind_save_match_data ();
6165       Fset_match_data (tem, Qt);
6166     }
6167 
6168   /* For speed, if a search happens within this code,
6169      save the match data in a special nonrecursive fashion.  */
6170   running_asynch_code = 1;
6171 
6172   decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
6173   text = coding->dst_object;
6174   Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6175   /* A new coding system might be found.  */
6176   if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
6177     {
6178       pset_decode_coding_system (p, Vlast_coding_system_used);
6179 
6180       /* Don't call setup_coding_system for
6181 	 proc_decode_coding_system[channel] here.  It is done in
6182 	 detect_coding called via decode_coding above.  */
6183 
6184       /* If a coding system for encoding is not yet decided, we set
6185 	 it as the same as coding-system for decoding.
6186 
6187 	 But, before doing that we must check if
6188 	 proc_encode_coding_system[p->outfd] surely points to a
6189 	 valid memory because p->outfd will be changed once EOF is
6190 	 sent to the process.  */
6191       eassert (p->outfd < FD_SETSIZE);
6192       if (NILP (p->encode_coding_system) && p->outfd >= 0
6193 	  && proc_encode_coding_system[p->outfd])
6194 	{
6195 	  pset_encode_coding_system
6196 	    (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
6197 	  setup_coding_system (p->encode_coding_system,
6198 			       proc_encode_coding_system[p->outfd]);
6199 	}
6200     }
6201 
6202   if (coding->carryover_bytes > 0)
6203     {
6204       if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
6205 	pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
6206       memcpy (SDATA (p->decoding_buf), coding->carryover,
6207 	      coding->carryover_bytes);
6208       p->decoding_carryover = coding->carryover_bytes;
6209     }
6210   if (SBYTES (text) > 0)
6211     /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6212        sometimes it's simply wrong to wrap (e.g. when called from
6213        accept-process-output).  */
6214     internal_condition_case_1 (read_process_output_call,
6215 			       list3 (outstream, make_lisp_proc (p), text),
6216 			       !NILP (Vdebug_on_error) ? Qnil : Qerror,
6217 			       read_process_output_error_handler);
6218 
6219   /* If we saved the match data nonrecursively, restore it now.  */
6220   restore_search_regs ();
6221   running_asynch_code = outer_running_asynch_code;
6222 
6223   /* Restore waiting_for_user_input_p as it was
6224      when we were called, in case the filter clobbered it.  */
6225   waiting_for_user_input_p = waiting;
6226 }
6227 
6228 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
6229        Sinternal_default_process_filter, 2, 2, 0,
6230        doc: /* Function used as default process filter.
6231 This inserts the process's output into its buffer, if there is one.
6232 Otherwise it discards the output.  */)
6233   (Lisp_Object proc, Lisp_Object text)
6234 {
6235   struct Lisp_Process *p;
6236   ptrdiff_t opoint;
6237 
6238   CHECK_PROCESS (proc);
6239   p = XPROCESS (proc);
6240   CHECK_STRING (text);
6241 
6242   if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6243     {
6244       Lisp_Object old_read_only;
6245       ptrdiff_t old_begv, old_zv;
6246       ptrdiff_t old_begv_byte, old_zv_byte;
6247       ptrdiff_t before, before_byte;
6248       ptrdiff_t opoint_byte;
6249       struct buffer *b;
6250 
6251       Fset_buffer (p->buffer);
6252       opoint = PT;
6253       opoint_byte = PT_BYTE;
6254       old_read_only = BVAR (current_buffer, read_only);
6255       old_begv = BEGV;
6256       old_zv = ZV;
6257       old_begv_byte = BEGV_BYTE;
6258       old_zv_byte = ZV_BYTE;
6259 
6260       bset_read_only (current_buffer, Qnil);
6261 
6262       /* Insert new output into buffer at the current end-of-output
6263 	 marker, thus preserving logical ordering of input and output.  */
6264       if (XMARKER (p->mark)->buffer)
6265 	set_point_from_marker (p->mark);
6266       else
6267 	SET_PT_BOTH (ZV, ZV_BYTE);
6268       before = PT;
6269       before_byte = PT_BYTE;
6270 
6271       /* If the output marker is outside of the visible region, save
6272 	 the restriction and widen.  */
6273       if (! (BEGV <= PT && PT <= ZV))
6274 	Fwiden ();
6275 
6276       /* Adjust the multibyteness of TEXT to that of the buffer.  */
6277       if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6278 	  != ! STRING_MULTIBYTE (text))
6279 	text = (STRING_MULTIBYTE (text)
6280 		? Fstring_as_unibyte (text)
6281 		: Fstring_to_multibyte (text));
6282       /* Insert before markers in case we are inserting where
6283 	 the buffer's mark is, and the user's next command is Meta-y.  */
6284       insert_from_string_before_markers (text, 0, 0,
6285 					 SCHARS (text), SBYTES (text), 0);
6286 
6287       /* Make sure the process marker's position is valid when the
6288 	 process buffer is changed in the signal_after_change above.
6289 	 W3 is known to do that.  */
6290       if (BUFFERP (p->buffer)
6291 	  && (b = XBUFFER (p->buffer), b != current_buffer))
6292 	set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6293       else
6294 	set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6295 
6296       update_mode_lines = 23;
6297 
6298       /* Make sure opoint and the old restrictions
6299 	 float ahead of any new text just as point would.  */
6300       if (opoint >= before)
6301 	{
6302 	  opoint += PT - before;
6303 	  opoint_byte += PT_BYTE - before_byte;
6304 	}
6305       if (old_begv > before)
6306 	{
6307 	  old_begv += PT - before;
6308 	  old_begv_byte += PT_BYTE - before_byte;
6309 	}
6310       if (old_zv >= before)
6311 	{
6312 	  old_zv += PT - before;
6313 	  old_zv_byte += PT_BYTE - before_byte;
6314 	}
6315 
6316       /* If the restriction isn't what it should be, set it.  */
6317       if (old_begv != BEGV || old_zv != ZV)
6318 	Fnarrow_to_region (make_fixnum (old_begv), make_fixnum (old_zv));
6319 
6320       bset_read_only (current_buffer, old_read_only);
6321       SET_PT_BOTH (opoint, opoint_byte);
6322     }
6323   return Qnil;
6324 }
6325 
6326 /* Sending data to subprocess.  */
6327 
6328 /* In send_process, when a write fails temporarily,
6329    wait_reading_process_output is called.  It may execute user code,
6330    e.g. timers, that attempts to write new data to the same process.
6331    We must ensure that data is sent in the right order, and not
6332    interspersed half-completed with other writes (Bug#10815).  This is
6333    handled by the write_queue element of struct process.  It is a list
6334    with each entry having the form
6335 
6336    (string . (offset . length))
6337 
6338    where STRING is a lisp string, OFFSET is the offset into the
6339    string's byte sequence from which we should begin to send, and
6340    LENGTH is the number of bytes left to send.  */
6341 
6342 /* Create a new entry in write_queue.
6343    INPUT_OBJ should be a buffer, string Qt, or Qnil.
6344    BUF is a pointer to the string sequence of the input_obj or a C
6345    string in case of Qt or Qnil.  */
6346 
6347 static void
write_queue_push(struct Lisp_Process * p,Lisp_Object input_obj,const char * buf,ptrdiff_t len,bool front)6348 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6349                   const char *buf, ptrdiff_t len, bool front)
6350 {
6351   ptrdiff_t offset;
6352   Lisp_Object entry, obj;
6353 
6354   if (STRINGP (input_obj))
6355     {
6356       offset = buf - SSDATA (input_obj);
6357       obj = input_obj;
6358     }
6359   else
6360     {
6361       offset = 0;
6362       obj = make_unibyte_string (buf, len);
6363     }
6364 
6365   entry = Fcons (obj, Fcons (make_fixnum (offset), make_fixnum (len)));
6366 
6367   if (front)
6368     pset_write_queue (p, Fcons (entry, p->write_queue));
6369   else
6370     pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6371 }
6372 
6373 /* Remove the first element in the write_queue of process P, put its
6374    contents in OBJ, BUF and LEN, and return true.  If the
6375    write_queue is empty, return false.  */
6376 
6377 static bool
write_queue_pop(struct Lisp_Process * p,Lisp_Object * obj,const char ** buf,ptrdiff_t * len)6378 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6379 		 const char **buf, ptrdiff_t *len)
6380 {
6381   Lisp_Object entry, offset_length;
6382   ptrdiff_t offset;
6383 
6384   if (NILP (p->write_queue))
6385     return 0;
6386 
6387   entry = XCAR (p->write_queue);
6388   pset_write_queue (p, XCDR (p->write_queue));
6389 
6390   *obj = XCAR (entry);
6391   offset_length = XCDR (entry);
6392 
6393   *len = XFIXNUM (XCDR (offset_length));
6394   offset = XFIXNUM (XCAR (offset_length));
6395   *buf = SSDATA (*obj) + offset;
6396 
6397   return 1;
6398 }
6399 
6400 /* Send some data to process PROC.
6401    BUF is the beginning of the data; LEN is the number of characters.
6402    OBJECT is the Lisp object that the data comes from.  If OBJECT is
6403    nil or t, it means that the data comes from C string.
6404 
6405    If OBJECT is not nil, the data is encoded by PROC's coding-system
6406    for encoding before it is sent.
6407 
6408    This function can evaluate Lisp code and can garbage collect.  */
6409 
6410 static void
send_process(Lisp_Object proc,const char * buf,ptrdiff_t len,Lisp_Object object)6411 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6412 	      Lisp_Object object)
6413 {
6414   struct Lisp_Process *p = XPROCESS (proc);
6415   ssize_t rv;
6416   struct coding_system *coding;
6417 
6418   if (NETCONN_P (proc))
6419     {
6420       wait_while_connecting (proc);
6421       wait_for_tls_negotiation (proc);
6422     }
6423 
6424   if (p->raw_status_new)
6425     update_status (p);
6426   if (! EQ (p->status, Qrun))
6427     error ("Process %s not running", SDATA (p->name));
6428   if (p->outfd < 0)
6429     error ("Output file descriptor of %s is closed", SDATA (p->name));
6430 
6431   eassert (p->outfd < FD_SETSIZE);
6432   coding = proc_encode_coding_system[p->outfd];
6433   Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6434 
6435   if ((STRINGP (object) && STRING_MULTIBYTE (object))
6436       || (BUFFERP (object)
6437 	  && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6438       || EQ (object, Qt))
6439     {
6440       pset_encode_coding_system
6441 	(p, complement_process_encoding_system (p->encode_coding_system));
6442       if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6443 	{
6444 	  /* The coding system for encoding was changed to raw-text
6445 	     because we sent a unibyte text previously.  Now we are
6446 	     sending a multibyte text, thus we must encode it by the
6447 	     original coding system specified for the current process.
6448 
6449 	     Another reason we come here is that the coding system
6450 	     was just complemented and a new one was returned by
6451 	     complement_process_encoding_system.  */
6452 	  setup_coding_system (p->encode_coding_system, coding);
6453 	  Vlast_coding_system_used = p->encode_coding_system;
6454 	}
6455       coding->src_multibyte = 1;
6456     }
6457   else
6458     {
6459       coding->src_multibyte = 0;
6460       /* For sending a unibyte text, character code conversion should
6461 	 not take place but EOL conversion should.  So, setup raw-text
6462 	 or one of the subsidiary if we have not yet done it.  */
6463       if (CODING_REQUIRE_ENCODING (coding))
6464 	{
6465 	  if (CODING_REQUIRE_FLUSHING (coding))
6466 	    {
6467 	      /* But, before changing the coding, we must flush out data.  */
6468 	      coding->mode |= CODING_MODE_LAST_BLOCK;
6469 	      send_process (proc, "", 0, Qt);
6470 	      coding->mode &= CODING_MODE_LAST_BLOCK;
6471 	    }
6472 	  setup_coding_system (raw_text_coding_system
6473 			       (Vlast_coding_system_used),
6474 			       coding);
6475 	  coding->src_multibyte = 0;
6476 	}
6477     }
6478   coding->dst_multibyte = 0;
6479 
6480   if (CODING_REQUIRE_ENCODING (coding))
6481     {
6482       coding->dst_object = Qt;
6483       if (BUFFERP (object))
6484 	{
6485 	  ptrdiff_t from_byte, from, to;
6486 	  ptrdiff_t save_pt, save_pt_byte;
6487 	  struct buffer *cur = current_buffer;
6488 
6489 	  set_buffer_internal (XBUFFER (object));
6490 	  save_pt = PT, save_pt_byte = PT_BYTE;
6491 
6492 	  from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6493 	  from = BYTE_TO_CHAR (from_byte);
6494 	  to = BYTE_TO_CHAR (from_byte + len);
6495 	  TEMP_SET_PT_BOTH (from, from_byte);
6496 	  encode_coding_object (coding, object, from, from_byte,
6497 				to, from_byte + len, Qt);
6498 	  TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6499 	  set_buffer_internal (cur);
6500 	}
6501       else if (STRINGP (object))
6502 	{
6503 	  encode_coding_object (coding, object, 0, 0, SCHARS (object),
6504 				SBYTES (object), Qt);
6505 	}
6506       else
6507 	{
6508 	  coding->dst_object = make_unibyte_string (buf, len);
6509 	  coding->produced = len;
6510 	}
6511 
6512       len = coding->produced;
6513       object = coding->dst_object;
6514       buf = SSDATA (object);
6515     }
6516 
6517   /* If there is already data in the write_queue, put the new data
6518      in the back of queue.  Otherwise, ignore it.  */
6519   if (!NILP (p->write_queue))
6520     write_queue_push (p, object, buf, len, 0);
6521 
6522   do   /* while !NILP (p->write_queue) */
6523     {
6524       ptrdiff_t cur_len = -1;
6525       const char *cur_buf;
6526       Lisp_Object cur_object;
6527 
6528       /* If write_queue is empty, ignore it.  */
6529       if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6530 	{
6531 	  cur_len = len;
6532 	  cur_buf = buf;
6533 	  cur_object = object;
6534 	}
6535 
6536       while (cur_len > 0)
6537 	{
6538 	  /* Send this batch, using one or more write calls.  */
6539 	  ptrdiff_t written = 0;
6540 	  int outfd = p->outfd;
6541           if (outfd < 0)
6542             error ("Output file descriptor of %s is closed",
6543                    SDATA (p->name));
6544 	  eassert (0 <= outfd && outfd < FD_SETSIZE);
6545 #ifdef DATAGRAM_SOCKETS
6546 	  if (DATAGRAM_CHAN_P (outfd))
6547 	    {
6548 	      while (true)
6549 		{
6550 		  rv = sendto (outfd, cur_buf, cur_len, 0,
6551 			       datagram_address[outfd].sa,
6552 			       datagram_address[outfd].len);
6553 		  if (! (rv < 0 && errno == EINTR))
6554 		    break;
6555 		  if (pending_signals)
6556 		    process_pending_signals ();
6557 		}
6558 
6559 	      if (rv >= 0)
6560 		written = rv;
6561 	      else if (errno == EMSGSIZE)
6562 		report_file_error ("Sending datagram", proc);
6563 	    }
6564 	  else
6565 #endif
6566 	    {
6567 #ifdef HAVE_GNUTLS
6568 	      if (p->gnutls_p && p->gnutls_state)
6569 		written = emacs_gnutls_write (p, cur_buf, cur_len);
6570 	      else
6571 #endif
6572 		written = emacs_write_sig (outfd, cur_buf, cur_len);
6573 	      rv = (written ? 0 : -1);
6574 	      if (p->read_output_delay > 0
6575 		  && p->adaptive_read_buffering == 1)
6576 		{
6577 		  p->read_output_delay = 0;
6578 		  process_output_delay_count--;
6579 		  p->read_output_skip = 0;
6580 		}
6581 	    }
6582 
6583 	  if (rv < 0)
6584 	    {
6585 	      if (would_block (errno))
6586 		/* Buffer is full.  Wait, accepting input;
6587 		   that may allow the program
6588 		   to finish doing output and read more.  */
6589 		{
6590 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6591 		  /* A gross hack to work around a bug in FreeBSD.
6592 		     In the following sequence, read(2) returns
6593 		     bogus data:
6594 
6595 		     write(2)	 1022 bytes
6596 		     write(2)   954 bytes, get EAGAIN
6597 		     read(2)   1024 bytes in process_read_output
6598 		     read(2)     11 bytes in process_read_output
6599 
6600 		     That is, read(2) returns more bytes than have
6601 		     ever been written successfully.  The 1033 bytes
6602 		     read are the 1022 bytes written successfully
6603 		     after processing (for example with CRs added if
6604 		     the terminal is set up that way which it is
6605 		     here).  The same bytes will be seen again in a
6606 		     later read(2), without the CRs.  */
6607 
6608 		  if (errno == EAGAIN)
6609 		    {
6610 		      int flags = FWRITE;
6611 		      ioctl (p->outfd, TIOCFLUSH, &flags);
6612 		    }
6613 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6614 
6615 		  /* Put what we should have written in write_queue.  */
6616 		  write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6617 		  wait_reading_process_output (0, 20 * 1000 * 1000,
6618 					       0, 0, Qnil, NULL, 0);
6619 		  /* Reread queue, to see what is left.  */
6620 		  break;
6621 		}
6622 	      else if (errno == EPIPE)
6623 		{
6624 		  p->raw_status_new = 0;
6625 		  pset_status (p, list2 (Qexit, make_fixnum (256)));
6626 		  p->tick = ++process_tick;
6627 		  deactivate_process (proc);
6628 		  error ("process %s no longer connected to pipe; closed it",
6629 			 SDATA (p->name));
6630 		}
6631 	      else
6632 		/* This is a real error.  */
6633 		report_file_error ("Writing to process", proc);
6634 	    }
6635 	  cur_buf += written;
6636 	  cur_len -= written;
6637 	}
6638     }
6639   while (!NILP (p->write_queue));
6640 }
6641 
6642 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6643        3, 3, 0,
6644        doc: /* Send current contents of region as input to PROCESS.
6645 PROCESS may be a process, a buffer, the name of a process or buffer, or
6646 nil, indicating the current buffer's process.
6647 Called from program, takes three arguments, PROCESS, START and END.
6648 If the region is larger than the input buffer of the process (the
6649 length of which depends on the process connection type and the
6650 operating system), it is sent in several bunches.  This may happen
6651 even for shorter regions.  Output from processes can arrive in between
6652 bunches.
6653 
6654 If PROCESS is a non-blocking network process that hasn't been fully
6655 set up yet, this function will block until socket setup has completed.  */)
6656   (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6657 {
6658   Lisp_Object proc = get_process (process);
6659   ptrdiff_t start_byte, end_byte;
6660 
6661   validate_region (&start, &end);
6662 
6663   start_byte = CHAR_TO_BYTE (XFIXNUM (start));
6664   end_byte = CHAR_TO_BYTE (XFIXNUM (end));
6665 
6666   if (XFIXNUM (start) < GPT && XFIXNUM (end) > GPT)
6667     move_gap_both (XFIXNUM (start), start_byte);
6668 
6669   if (NETCONN_P (proc))
6670     wait_while_connecting (proc);
6671 
6672   send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6673 		end_byte - start_byte, Fcurrent_buffer ());
6674 
6675   return Qnil;
6676 }
6677 
6678 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6679        2, 2, 0,
6680        doc: /* Send PROCESS the contents of STRING as input.
6681 PROCESS may be a process, a buffer, the name of a process or buffer, or
6682 nil, indicating the current buffer's process.
6683 If STRING is larger than the input buffer of the process (the length
6684 of which depends on the process connection type and the operating
6685 system), it is sent in several bunches.  This may happen even for
6686 shorter strings.  Output from processes can arrive in between bunches.
6687 
6688 If PROCESS is a non-blocking network process that hasn't been fully
6689 set up yet, this function will block until socket setup has completed.  */)
6690   (Lisp_Object process, Lisp_Object string)
6691 {
6692   CHECK_STRING (string);
6693   Lisp_Object proc = get_process (process);
6694   send_process (proc, SSDATA (string),
6695 		SBYTES (string), string);
6696   return Qnil;
6697 }
6698 
6699 /* Return the foreground process group for the tty/pty that
6700    the process P uses.  */
6701 static pid_t
emacs_get_tty_pgrp(struct Lisp_Process * p)6702 emacs_get_tty_pgrp (struct Lisp_Process *p)
6703 {
6704   pid_t gid = -1;
6705 
6706 #ifdef TIOCGPGRP
6707   if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6708     {
6709       int fd;
6710       /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6711 	 master side.  Try the slave side.  */
6712       fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6713 
6714       if (fd != -1)
6715 	{
6716 	  ioctl (fd, TIOCGPGRP, &gid);
6717 	  emacs_close (fd);
6718 	}
6719     }
6720 #endif /* defined (TIOCGPGRP ) */
6721 
6722   return gid;
6723 }
6724 
6725 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6726        Sprocess_running_child_p, 0, 1, 0,
6727        doc: /* Return non-nil if PROCESS has given the terminal to a
6728 child.  If the operating system does not make it possible to find out,
6729 return t.  If we can find out, return the numeric ID of the foreground
6730 process group.  */)
6731   (Lisp_Object process)
6732 {
6733   /* Initialize in case ioctl doesn't exist or gives an error,
6734      in a way that will cause returning t.  */
6735   Lisp_Object proc = get_process (process);
6736   struct Lisp_Process *p = XPROCESS (proc);
6737 
6738   if (!EQ (p->type, Qreal))
6739     error ("Process %s is not a subprocess",
6740 	   SDATA (p->name));
6741   if (p->infd < 0)
6742     error ("Process %s is not active",
6743 	   SDATA (p->name));
6744 
6745   pid_t gid = emacs_get_tty_pgrp (p);
6746 
6747   if (gid == p->pid)
6748     return Qnil;
6749   if (gid != -1)
6750     return make_fixnum (gid);
6751   return Qt;
6752 }
6753 
6754 /* Send a signal number SIGNO to PROCESS.
6755    If CURRENT_GROUP is t, that means send to the process group
6756    that currently owns the terminal being used to communicate with PROCESS.
6757    This is used for various commands in shell mode.
6758    If CURRENT_GROUP is lambda, that means send to the process group
6759    that currently owns the terminal, but only if it is NOT the shell itself.
6760 
6761    If NOMSG is false, insert signal-announcements into process's buffers
6762    right away.
6763 
6764    If we can, we try to signal PROCESS by sending control characters
6765    down the pty.  This allows us to signal inferiors who have changed
6766    their uid, for which kill would return an EPERM error.  */
6767 
6768 static void
process_send_signal(Lisp_Object process,int signo,Lisp_Object current_group,bool nomsg)6769 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6770 		     bool nomsg)
6771 {
6772   Lisp_Object proc;
6773   struct Lisp_Process *p;
6774   pid_t gid;
6775   bool no_pgrp = 0;
6776 
6777   proc = get_process (process);
6778   p = XPROCESS (proc);
6779 
6780   if (!EQ (p->type, Qreal))
6781     error ("Process %s is not a subprocess",
6782 	   SDATA (p->name));
6783   if (p->infd < 0)
6784     error ("Process %s is not active",
6785 	   SDATA (p->name));
6786 
6787   if (!p->pty_flag)
6788     current_group = Qnil;
6789 
6790   /* If we are using pgrps, get a pgrp number and make it negative.  */
6791   if (NILP (current_group))
6792     /* Send the signal to the shell's process group.  */
6793     gid = p->pid;
6794   else
6795     {
6796 #ifdef SIGNALS_VIA_CHARACTERS
6797       /* If possible, send signals to the entire pgrp
6798 	 by sending an input character to it.  */
6799 
6800       struct termios t;
6801       cc_t *sig_char = NULL;
6802 
6803       tcgetattr (p->infd, &t);
6804 
6805       switch (signo)
6806 	{
6807 	case SIGINT:
6808 	  sig_char = &t.c_cc[VINTR];
6809 	  break;
6810 
6811 	case SIGQUIT:
6812 	  sig_char = &t.c_cc[VQUIT];
6813 	  break;
6814 
6815   	case SIGTSTP:
6816 #ifdef VSWTCH
6817 	  sig_char = &t.c_cc[VSWTCH];
6818 #else
6819 	  sig_char = &t.c_cc[VSUSP];
6820 #endif
6821 	  break;
6822 	}
6823 
6824       if (sig_char && *sig_char != CDISABLE)
6825 	{
6826 	  send_process (proc, (char *) sig_char, 1, Qnil);
6827 	  return;
6828 	}
6829       /* If we can't send the signal with a character,
6830 	 fall through and send it another way.  */
6831 
6832       /* The code above may fall through if it can't
6833 	 handle the signal.  */
6834 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6835 
6836 #ifdef TIOCGPGRP
6837       /* Get the current pgrp using the tty itself, if we have that.
6838 	 Otherwise, use the pty to get the pgrp.
6839 	 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6840 	 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6841 	 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6842 	 His patch indicates that if TIOCGPGRP returns an error, then
6843 	 we should just assume that p->pid is also the process group id.  */
6844 
6845       gid = emacs_get_tty_pgrp (p);
6846 
6847       if (gid == -1)
6848 	/* If we can't get the information, assume
6849 	   the shell owns the tty.  */
6850 	gid = p->pid;
6851 
6852       /* It is not clear whether anything really can set GID to -1.
6853 	 Perhaps on some system one of those ioctls can or could do so.
6854 	 Or perhaps this is vestigial.  */
6855       if (gid == -1)
6856 	no_pgrp = 1;
6857 #else  /* ! defined (TIOCGPGRP) */
6858       /* Can't select pgrps on this system, so we know that
6859 	 the child itself heads the pgrp.  */
6860       gid = p->pid;
6861 #endif /* ! defined (TIOCGPGRP) */
6862 
6863       /* If current_group is lambda, and the shell owns the terminal,
6864 	 don't send any signal.  */
6865       if (EQ (current_group, Qlambda) && gid == p->pid)
6866 	return;
6867     }
6868 
6869 #ifdef SIGCONT
6870   if (signo == SIGCONT)
6871     {
6872       p->raw_status_new = 0;
6873       pset_status (p, Qrun);
6874       p->tick = ++process_tick;
6875       if (!nomsg)
6876 	{
6877 	  status_notify (NULL, NULL);
6878 	  redisplay_preserve_echo_area (13);
6879 	}
6880     }
6881 #endif
6882 
6883 #ifdef TIOCSIGSEND
6884   /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6885      We don't know whether the bug is fixed in later HP-UX versions.  */
6886   if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6887     return;
6888 #endif
6889 
6890   /* If we don't have process groups, send the signal to the immediate
6891      subprocess.  That isn't really right, but it's better than any
6892      obvious alternative.  */
6893   pid_t pid = no_pgrp ? gid : - gid;
6894 
6895   /* Do not kill an already-reaped process, as that could kill an
6896      innocent bystander that happens to have the same process ID.  */
6897   sigset_t oldset;
6898   block_child_signal (&oldset);
6899   if (p->alive)
6900     kill (pid, signo);
6901   unblock_child_signal (&oldset);
6902 }
6903 
6904 DEFUN ("internal-default-interrupt-process",
6905        Finternal_default_interrupt_process,
6906        Sinternal_default_interrupt_process, 0, 2, 0,
6907        doc: /* Default function to interrupt process PROCESS.
6908 It shall be the last element in list `interrupt-process-functions'.
6909 See function `interrupt-process' for more details on usage.  */)
6910   (Lisp_Object process, Lisp_Object current_group)
6911 {
6912   process_send_signal (process, SIGINT, current_group, 0);
6913   return process;
6914 }
6915 
6916 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6917        doc: /* Interrupt process PROCESS.
6918 PROCESS may be a process, a buffer, or the name of a process or buffer.
6919 No arg or nil means current buffer's process.
6920 Second arg CURRENT-GROUP non-nil means send signal to
6921 the current process-group of the process's controlling terminal
6922 rather than to the process's own process group.
6923 If the process is a shell, this means interrupt current subjob
6924 rather than the shell.
6925 
6926 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6927 don't send the signal.
6928 
6929 This function calls the functions of `interrupt-process-functions' in
6930 the order of the list, until one of them returns non-nil.  */)
6931   (Lisp_Object process, Lisp_Object current_group)
6932 {
6933   return CALLN (Frun_hook_with_args_until_success, Qinterrupt_process_functions,
6934 		process, current_group);
6935 }
6936 
6937 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6938        doc: /* Kill process PROCESS.  May be process or name of one.
6939 See function `interrupt-process' for more details on usage.  */)
6940   (Lisp_Object process, Lisp_Object current_group)
6941 {
6942   process_send_signal (process, SIGKILL, current_group, 0);
6943   return process;
6944 }
6945 
6946 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6947        doc: /* Send QUIT signal to process PROCESS.  May be process or name of one.
6948 See function `interrupt-process' for more details on usage.  */)
6949   (Lisp_Object process, Lisp_Object current_group)
6950 {
6951   process_send_signal (process, SIGQUIT, current_group, 0);
6952   return process;
6953 }
6954 
6955 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6956        doc: /* Stop process PROCESS.  May be process or name of one.
6957 See function `interrupt-process' for more details on usage.
6958 If PROCESS is a network or serial or pipe connection, inhibit handling
6959 of incoming traffic.  */)
6960   (Lisp_Object process, Lisp_Object current_group)
6961 {
6962   if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6963 			     || PIPECONN_P (process)))
6964     {
6965       struct Lisp_Process *p;
6966 
6967       p = XPROCESS (process);
6968       if (NILP (p->command)
6969 	  && p->infd >= 0)
6970 	delete_read_fd (p->infd);
6971       pset_command (p, Qt);
6972       return process;
6973     }
6974 #ifndef SIGTSTP
6975   error ("No SIGTSTP support");
6976 #else
6977   process_send_signal (process, SIGTSTP, current_group, 0);
6978 #endif
6979   return process;
6980 }
6981 
6982 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6983        doc: /* Continue process PROCESS.  May be process or name of one.
6984 See function `interrupt-process' for more details on usage.
6985 If PROCESS is a network or serial process, resume handling of incoming
6986 traffic.  */)
6987   (Lisp_Object process, Lisp_Object current_group)
6988 {
6989   if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6990 			     || PIPECONN_P (process)))
6991     {
6992       struct Lisp_Process *p;
6993 
6994       p = XPROCESS (process);
6995       eassert (p->infd < FD_SETSIZE);
6996       if (EQ (p->command, Qt)
6997 	  && p->infd >= 0
6998 	  && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6999 	{
7000 	  add_process_read_fd (p->infd);
7001 #ifdef WINDOWSNT
7002 	  if (fd_info[ p->infd ].flags & FILE_SERIAL)
7003 	    PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
7004 #else /* not WINDOWSNT */
7005 	  tcflush (p->infd, TCIFLUSH);
7006 #endif /* not WINDOWSNT */
7007 	}
7008       pset_command (p, Qnil);
7009       return process;
7010     }
7011 #ifdef SIGCONT
7012     process_send_signal (process, SIGCONT, current_group, 0);
7013 #else
7014     error ("No SIGCONT support");
7015 #endif
7016   return process;
7017 }
7018 
7019 /* Return the integer value of the signal whose abbreviation is ABBR,
7020    or a negative number if there is no such signal.  */
7021 static int
abbr_to_signal(char const * name)7022 abbr_to_signal (char const *name)
7023 {
7024   int i, signo;
7025   char sigbuf[20]; /* Large enough for all valid signal abbreviations.  */
7026 
7027   if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
7028     name += 3;
7029 
7030   for (i = 0; i < sizeof sigbuf; i++)
7031     {
7032       sigbuf[i] = c_toupper (name[i]);
7033       if (! sigbuf[i])
7034 	return str2sig (sigbuf, &signo) == 0 ? signo : -1;
7035     }
7036 
7037   return -1;
7038 }
7039 
7040 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
7041        2, 2, "sProcess (name or number): \nnSignal code: ",
7042        doc: /* Send PROCESS the signal with code SIGCODE.
7043 PROCESS may also be a number specifying the process id of the
7044 process to signal; in this case, the process need not be a child of
7045 this Emacs.
7046 SIGCODE may be an integer, or a symbol whose name is a signal name.  */)
7047   (Lisp_Object process, Lisp_Object sigcode)
7048 {
7049   pid_t pid;
7050   int signo;
7051 
7052   if (STRINGP (process))
7053     {
7054       Lisp_Object tem = Fget_process (process);
7055       if (NILP (tem))
7056 	{
7057 	  ptrdiff_t len;
7058 	  tem = string_to_number (SSDATA (process), 10, &len);
7059 	  if (NILP (tem) || len != SBYTES (process))
7060 	    return Qnil;
7061 	}
7062       process = tem;
7063     }
7064   else if (!NUMBERP (process))
7065     process = get_process (process);
7066 
7067   if (NILP (process))
7068     return process;
7069 
7070   if (NUMBERP (process))
7071     CONS_TO_INTEGER (process, pid_t, pid);
7072   else
7073     {
7074       CHECK_PROCESS (process);
7075       pid = XPROCESS (process)->pid;
7076       if (pid <= 0)
7077 	error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
7078     }
7079 
7080   if (FIXNUMP (sigcode))
7081     signo = check_integer_range (sigcode, INT_MIN, INT_MAX);
7082   else
7083     {
7084       char *name;
7085 
7086       CHECK_SYMBOL (sigcode);
7087       name = SSDATA (SYMBOL_NAME (sigcode));
7088 
7089       signo = abbr_to_signal (name);
7090       if (signo < 0)
7091 	error ("Undefined signal name %s", name);
7092     }
7093 
7094   return make_fixnum (kill (pid, signo));
7095 }
7096 
7097 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
7098        doc: /* Make PROCESS see end-of-file in its input.
7099 EOF comes after any text already sent to it.
7100 PROCESS may be a process, a buffer, the name of a process or buffer, or
7101 nil, indicating the current buffer's process.
7102 If PROCESS is a network connection, or is a process communicating
7103 through a pipe (as opposed to a pty), then you cannot send any more
7104 text to PROCESS after you call this function.
7105 If PROCESS is a serial process, wait until all output written to the
7106 process has been transmitted to the serial port.  */)
7107   (Lisp_Object process)
7108 {
7109   Lisp_Object proc;
7110   struct coding_system *coding = NULL;
7111   int outfd;
7112 
7113   proc = get_process (process);
7114 
7115   if (NETCONN_P (proc))
7116     wait_while_connecting (proc);
7117 
7118   if (DATAGRAM_CONN_P (proc))
7119     return process;
7120 
7121 
7122   outfd = XPROCESS (proc)->outfd;
7123   eassert (outfd < FD_SETSIZE);
7124   if (outfd >= 0)
7125     coding = proc_encode_coding_system[outfd];
7126 
7127   /* Make sure the process is really alive.  */
7128   if (XPROCESS (proc)->raw_status_new)
7129     update_status (XPROCESS (proc));
7130   if (! EQ (XPROCESS (proc)->status, Qrun))
7131     error ("Process %s not running", SDATA (XPROCESS (proc)->name));
7132 
7133   if (coding && CODING_REQUIRE_FLUSHING (coding))
7134     {
7135       coding->mode |= CODING_MODE_LAST_BLOCK;
7136       send_process (proc, "", 0, Qnil);
7137     }
7138 
7139   if (XPROCESS (proc)->pty_flag)
7140     send_process (proc, "\004", 1, Qnil);
7141   else if (EQ (XPROCESS (proc)->type, Qserial))
7142     {
7143 #ifndef WINDOWSNT
7144       if (tcdrain (XPROCESS (proc)->outfd) != 0)
7145 	report_file_error ("Failed tcdrain", Qnil);
7146 #endif /* not WINDOWSNT */
7147       /* Do nothing on Windows because writes are blocking.  */
7148     }
7149   else
7150     {
7151       struct Lisp_Process *p = XPROCESS (proc);
7152       int old_outfd = p->outfd;
7153       int new_outfd;
7154 
7155 #ifdef HAVE_SHUTDOWN
7156       /* If this is a network connection, or socketpair is used
7157 	 for communication with the subprocess, call shutdown to cause EOF.
7158 	 (In some old system, shutdown to socketpair doesn't work.
7159 	 Then we just can't win.)  */
7160       if (0 <= old_outfd
7161 	  && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
7162 	shutdown (old_outfd, 1);
7163 #endif
7164       close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
7165       new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
7166       if (new_outfd < 0)
7167 	report_file_error ("Opening null device", Qnil);
7168       p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
7169       p->outfd = new_outfd;
7170 
7171       eassert (0 <= new_outfd && new_outfd < FD_SETSIZE);
7172       if (!proc_encode_coding_system[new_outfd])
7173 	proc_encode_coding_system[new_outfd]
7174 	  = xmalloc (sizeof (struct coding_system));
7175       if (old_outfd >= 0)
7176 	{
7177 	  eassert (old_outfd < FD_SETSIZE);
7178 	  *proc_encode_coding_system[new_outfd]
7179 	    = *proc_encode_coding_system[old_outfd];
7180 	  memset (proc_encode_coding_system[old_outfd], 0,
7181 		  sizeof (struct coding_system));
7182 	}
7183       else
7184 	setup_coding_system (p->encode_coding_system,
7185 			     proc_encode_coding_system[new_outfd]);
7186     }
7187   return process;
7188 }
7189 
7190 /* The main Emacs thread records child processes in three places:
7191 
7192    - Vprocess_alist, for asynchronous subprocesses, which are child
7193      processes visible to Lisp.
7194 
7195    - deleted_pid_list, for child processes invisible to Lisp,
7196      typically because of delete-process.  These are recorded so that
7197      the processes can be reaped when they exit, so that the operating
7198      system's process table is not cluttered by zombies.
7199 
7200    - the local variable PID in Fcall_process, call_process_cleanup and
7201      call_process_kill, for synchronous subprocesses.
7202      record_unwind_protect is used to make sure this process is not
7203      forgotten: if the user interrupts call-process and the child
7204      process refuses to exit immediately even with two C-g's,
7205      call_process_kill adds PID's contents to deleted_pid_list before
7206      returning.
7207 
7208    The main Emacs thread invokes waitpid only on child processes that
7209    it creates and that have not been reaped.  This avoid races on
7210    platforms such as GTK, where other threads create their own
7211    subprocesses which the main thread should not reap.  For example,
7212    if the main thread attempted to reap an already-reaped child, it
7213    might inadvertently reap a GTK-created process that happened to
7214    have the same process ID.
7215 
7216    To avoid a deadlock when receiving SIGCHLD while
7217    'wait_reading_process_output' is in 'pselect', the SIGCHLD handler
7218    will notify the `pselect' using a self-pipe.  The deadlock could
7219    occur if SIGCHLD is delivered outside of the 'pselect' call, in
7220    which case 'pselect' will not be interrupted by the signal, and
7221    will therefore wait on the process's output descriptor for the
7222    output that will never come.
7223 
7224    WINDOWSNT doesn't need this facility because its 'pselect'
7225    emulation (see 'sys_select' in w32proc.c) waits on a subprocess
7226    handle, which becomes signaled when the process exits, and also
7227    because that emulation delays the delivery of the simulated SIGCHLD
7228    until all the output from the subprocess has been consumed.  */
7229 
7230 /* FIXME: On Unix-like systems that have a proper 'pselect'
7231    (HAVE_PSELECT), we should block SIGCHLD in
7232    'wait_reading_process_output' and pass a non-NULL signal mask to
7233    'pselect' to avoid the need for the self-pipe.  */
7234 
7235 /* Set up `child_signal_read_fd' and `child_signal_write_fd'.  */
7236 
7237 static void
child_signal_init(void)7238 child_signal_init (void)
7239 {
7240   /* Either both are initialized, or both are uninitialized.  */
7241   eassert ((child_signal_read_fd < 0) == (child_signal_write_fd < 0));
7242 
7243 #ifndef WINDOWSNT
7244   if (0 <= child_signal_read_fd)
7245     return; /* already done */
7246 
7247   int fds[2];
7248   if (emacs_pipe (fds) < 0)
7249     report_file_error ("Creating pipe for child signal", Qnil);
7250   if (FD_SETSIZE <= fds[0])
7251     {
7252       /* Since we need to `pselect' on the read end, it has to fit
7253 	 into an `fd_set'.  */
7254       emacs_close (fds[0]);
7255       emacs_close (fds[1]);
7256       report_file_errno ("Creating pipe for child signal", Qnil,
7257 			 EMFILE);
7258     }
7259 
7260   /* We leave the file descriptors open until the Emacs process
7261      exits.  */
7262   eassert (0 <= fds[0]);
7263   eassert (0 <= fds[1]);
7264   if (fcntl (fds[0], F_SETFL, O_NONBLOCK) != 0)
7265     emacs_perror ("fcntl");
7266   if (fcntl (fds[1], F_SETFL, O_NONBLOCK) != 0)
7267     emacs_perror ("fcntl");
7268   add_read_fd (fds[0], child_signal_read, NULL);
7269   fd_callback_info[fds[0]].flags &= ~KEYBOARD_FD;
7270   child_signal_read_fd = fds[0];
7271   child_signal_write_fd = fds[1];
7272 #endif	/* !WINDOWSNT */
7273 }
7274 
7275 #ifndef WINDOWSNT
7276 /* Consume a process status change.  */
7277 
7278 static void
child_signal_read(int fd,void * data)7279 child_signal_read (int fd, void *data)
7280 {
7281   eassert (0 <= fd);
7282   eassert (fd == child_signal_read_fd);
7283   char dummy;
7284   if (emacs_read (fd, &dummy, 1) < 0 && errno != EAGAIN)
7285     emacs_perror ("reading from child signal FD");
7286 }
7287 #endif	/* !WINDOWSNT */
7288 
7289 /* Notify `wait_reading_process_output' of a process status
7290    change.  */
7291 
7292 static void
child_signal_notify(void)7293 child_signal_notify (void)
7294 {
7295 #ifndef WINDOWSNT
7296   int fd = child_signal_write_fd;
7297   eassert (0 <= fd);
7298   char dummy = 0;
7299   if (emacs_write (fd, &dummy, 1) != 1)
7300     emacs_perror ("writing to child signal FD");
7301 #endif
7302 }
7303 
7304 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7305    its own SIGCHLD handling.  On POSIXish systems, glib needs this to
7306    keep track of its own children.  GNUstep is similar.  */
7307 
dummy_handler(int sig)7308 static void dummy_handler (int sig) {}
7309 static signal_handler_t volatile lib_child_handler;
7310 
7311 /* Handle a SIGCHLD signal by looking for known child processes of
7312    Emacs whose status have changed.  For each one found, record its
7313    new status.
7314 
7315    All we do is change the status; we do not run sentinels or print
7316    notifications.  That is saved for the next time keyboard input is
7317    done, in order to avoid timing errors.
7318 
7319    ** WARNING: this can be called during garbage collection.
7320    Therefore, it must not be fooled by the presence of mark bits in
7321    Lisp objects.
7322 
7323    ** USG WARNING: Although it is not obvious from the documentation
7324    in signal(2), on a USG system the SIGCLD handler MUST NOT call
7325    signal() before executing at least one wait(), otherwise the
7326    handler will be called again, resulting in an infinite loop.  The
7327    relevant portion of the documentation reads "SIGCLD signals will be
7328    queued and the signal-catching function will be continually
7329    reentered until the queue is empty".  Invoking signal() causes the
7330    kernel to reexamine the SIGCLD queue.  Fred Fish, UniSoft Systems
7331    Inc.
7332 
7333    ** Malloc WARNING: This should never call malloc either directly or
7334    indirectly; if it does, that is a bug.  */
7335 
7336 static void
handle_child_signal(int sig)7337 handle_child_signal (int sig)
7338 {
7339   Lisp_Object tail, proc;
7340   bool changed = false;
7341 
7342   /* Find the process that signaled us, and record its status.  */
7343 
7344   /* The process can have been deleted by Fdelete_process, or have
7345      been started asynchronously by Fcall_process.  */
7346   for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
7347     {
7348       bool all_pids_are_fixnums
7349 	= (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
7350 	   && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
7351       Lisp_Object head = XCAR (tail);
7352       Lisp_Object xpid;
7353       if (! CONSP (head))
7354 	continue;
7355       xpid = XCAR (head);
7356       if (all_pids_are_fixnums ? FIXNUMP (xpid) : INTEGERP (xpid))
7357 	{
7358 	  intmax_t deleted_pid;
7359 	  bool ok = integer_to_intmax (xpid, &deleted_pid);
7360 	  eassert (ok);
7361 	  if (child_status_changed (deleted_pid, 0, 0))
7362 	    {
7363 	      changed = true;
7364 	      if (STRINGP (XCDR (head)))
7365 		unlink (SSDATA (XCDR (head)));
7366 	      XSETCAR (tail, Qnil);
7367 	    }
7368 	}
7369     }
7370 
7371   /* Otherwise, if it is asynchronous, it is in Vprocess_alist.  */
7372   FOR_EACH_PROCESS (tail, proc)
7373     {
7374       struct Lisp_Process *p = XPROCESS (proc);
7375       int status;
7376 
7377       if (p->alive
7378 	  && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7379 	{
7380 	  /* Change the status of the process that was found.  */
7381 	  changed = true;
7382 	  p->tick = ++process_tick;
7383 	  p->raw_status = status;
7384 	  p->raw_status_new = 1;
7385 
7386 	  /* If process has terminated, stop waiting for its output.  */
7387 	  if (WIFSIGNALED (status) || WIFEXITED (status))
7388 	    {
7389 	      bool clear_desc_flag = 0;
7390 	      p->alive = 0;
7391 	      if (p->infd >= 0)
7392 		clear_desc_flag = 1;
7393 
7394 	      /* clear_desc_flag avoids a compiler bug in Microsoft C.  */
7395 	      if (clear_desc_flag)
7396 		delete_read_fd (p->infd);
7397 	    }
7398 	}
7399     }
7400 
7401   if (changed)
7402     /* Wake up `wait_reading_process_output'.  */
7403     child_signal_notify ();
7404 
7405   lib_child_handler (sig);
7406 #ifdef NS_IMPL_GNUSTEP
7407   /* NSTask in GNUstep sets its child handler each time it is called.
7408      So we must re-set ours.  */
7409   catch_child_signal ();
7410 #endif
7411 }
7412 
7413 static void
deliver_child_signal(int sig)7414 deliver_child_signal (int sig)
7415 {
7416   deliver_process_signal (sig, handle_child_signal);
7417 }
7418 
7419 
7420 static Lisp_Object
exec_sentinel_error_handler(Lisp_Object error_val)7421 exec_sentinel_error_handler (Lisp_Object error_val)
7422 {
7423   /* Make sure error_val is a cons cell, as all the rest of error
7424      handling expects that, and will barf otherwise.  */
7425   if (!CONSP (error_val))
7426     error_val = Fcons (Qerror, error_val);
7427   cmd_error_internal (error_val, "error in process sentinel: ");
7428   Vinhibit_quit = Qt;
7429   update_echo_area ();
7430   if (process_error_pause_time > 0)
7431     Fsleep_for (make_fixnum (process_error_pause_time), Qnil);
7432   return Qt;
7433 }
7434 
7435 static void
exec_sentinel(Lisp_Object proc,Lisp_Object reason)7436 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7437 {
7438   Lisp_Object sentinel, odeactivate;
7439   struct Lisp_Process *p = XPROCESS (proc);
7440   ptrdiff_t count = SPECPDL_INDEX ();
7441   bool outer_running_asynch_code = running_asynch_code;
7442   int waiting = waiting_for_user_input_p;
7443 
7444   if (inhibit_sentinels)
7445     return;
7446 
7447   odeactivate = Vdeactivate_mark;
7448 #if 0
7449   Lisp_Object obuffer, okeymap;
7450   XSETBUFFER (obuffer, current_buffer);
7451   okeymap = BVAR (current_buffer, keymap);
7452 #endif
7453 
7454   /* There's no good reason to let sentinels change the current
7455      buffer, and many callers of accept-process-output, sit-for, and
7456      friends don't expect current-buffer to be changed from under them.  */
7457   record_unwind_current_buffer ();
7458 
7459   sentinel = p->sentinel;
7460 
7461   /* Inhibit quit so that random quits don't screw up a running filter.  */
7462   specbind (Qinhibit_quit, Qt);
7463   specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef  */
7464 
7465   /* In case we get recursively called,
7466      and we already saved the match data nonrecursively,
7467      save the same match data in safely recursive fashion.  */
7468   if (outer_running_asynch_code)
7469     {
7470       Lisp_Object tem;
7471       tem = Fmatch_data (Qnil, Qnil, Qnil);
7472       restore_search_regs ();
7473       record_unwind_save_match_data ();
7474       Fset_match_data (tem, Qt);
7475     }
7476 
7477   /* For speed, if a search happens within this code,
7478      save the match data in a special nonrecursive fashion.  */
7479   running_asynch_code = 1;
7480 
7481   internal_condition_case_1 (read_process_output_call,
7482 			     list3 (sentinel, proc, reason),
7483 			     !NILP (Vdebug_on_error) ? Qnil : Qerror,
7484 			     exec_sentinel_error_handler);
7485 
7486   /* If we saved the match data nonrecursively, restore it now.  */
7487   restore_search_regs ();
7488   running_asynch_code = outer_running_asynch_code;
7489 
7490   Vdeactivate_mark = odeactivate;
7491 
7492   /* Restore waiting_for_user_input_p as it was
7493      when we were called, in case the filter clobbered it.  */
7494   waiting_for_user_input_p = waiting;
7495 
7496   unbind_to (count, Qnil);
7497 }
7498 
7499 /* Report all recent events of a change in process status
7500    (either run the sentinel or output a message).
7501    This is usually done while Emacs is waiting for keyboard input
7502    but can be done at other times.
7503 
7504    Return positive if any input was received from WAIT_PROC (or from
7505    any process if WAIT_PROC is null), zero if input was attempted but
7506    none received, and negative if we didn't even try.  */
7507 
7508 static int
status_notify(struct Lisp_Process * deleting_process,struct Lisp_Process * wait_proc)7509 status_notify (struct Lisp_Process *deleting_process,
7510 	       struct Lisp_Process *wait_proc)
7511 {
7512   Lisp_Object proc;
7513   Lisp_Object tail, msg;
7514   int got_some_output = -1;
7515 
7516   tail = Qnil;
7517   msg = Qnil;
7518 
7519   /* Set this now, so that if new processes are created by sentinels
7520      that we run, we get called again to handle their status changes.  */
7521   update_tick = process_tick;
7522 
7523   FOR_EACH_PROCESS (tail, proc)
7524     {
7525       Lisp_Object symbol;
7526       register struct Lisp_Process *p = XPROCESS (proc);
7527 
7528       if (p->tick != p->update_tick)
7529 	{
7530 	  p->update_tick = p->tick;
7531 
7532 	  /* If process is still active, read any output that remains.  */
7533 	  while (! EQ (p->filter, Qt)
7534 		 && ! connecting_status (p->status)
7535 		 && ! EQ (p->status, Qlisten)
7536 		 /* Network or serial process not stopped:  */
7537 		 && ! EQ (p->command, Qt)
7538 		 && p->infd >= 0
7539 		 && p != deleting_process)
7540 	    {
7541 	      int nread = read_process_output (proc, p->infd);
7542 	      if ((!wait_proc || wait_proc == XPROCESS (proc))
7543 		  && got_some_output < nread)
7544 		got_some_output = nread;
7545 	      if (nread <= 0)
7546 		break;
7547 	    }
7548 
7549 	  /* Get the text to use for the message.  */
7550 	  if (p->raw_status_new)
7551 	    update_status (p);
7552 	  msg = status_message (p);
7553 
7554 	  /* If process is terminated, deactivate it or delete it.  */
7555 	  symbol = p->status;
7556 	  if (CONSP (p->status))
7557 	    symbol = XCAR (p->status);
7558 
7559 	  if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7560 	      || EQ (symbol, Qclosed))
7561 	    {
7562 	      if (delete_exited_processes)
7563 		remove_process (proc);
7564 	      else
7565 		deactivate_process (proc);
7566 	    }
7567 
7568 	  /* The actions above may have further incremented p->tick.
7569 	     So set p->update_tick again so that an error in the sentinel will
7570 	     not cause this code to be run again.  */
7571 	  p->update_tick = p->tick;
7572 	  /* Now output the message suitably.  */
7573 	  exec_sentinel (proc, msg);
7574 	  if (BUFFERP (p->buffer))
7575 	    /* In case it uses %s in mode-line-format.  */
7576 	    bset_update_mode_line (XBUFFER (p->buffer));
7577 	}
7578     } /* end for */
7579 
7580   return got_some_output;
7581 }
7582 
7583 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7584        Sinternal_default_process_sentinel, 2, 2, 0,
7585        doc: /* Function used as default sentinel for processes.
7586 This inserts a status message into the process's buffer, if there is one.  */)
7587      (Lisp_Object proc, Lisp_Object msg)
7588 {
7589   Lisp_Object buffer, symbol;
7590   struct Lisp_Process *p;
7591   CHECK_PROCESS (proc);
7592   p = XPROCESS (proc);
7593   buffer = p->buffer;
7594   symbol = p->status;
7595   if (CONSP (symbol))
7596     symbol = XCAR (symbol);
7597 
7598   if (!EQ (symbol, Qrun) && !NILP (buffer))
7599     {
7600       Lisp_Object tem;
7601       struct buffer *old = current_buffer;
7602       ptrdiff_t opoint, opoint_byte;
7603       ptrdiff_t before, before_byte;
7604 
7605       /* Avoid error if buffer is deleted
7606 	 (probably that's why the process is dead, too).  */
7607       if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7608 	return Qnil;
7609       Fset_buffer (buffer);
7610 
7611       if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7612 	msg = (code_convert_string_norecord
7613 	       (msg, Vlocale_coding_system, 1));
7614 
7615       opoint = PT;
7616       opoint_byte = PT_BYTE;
7617       /* Insert new output into buffer
7618 	 at the current end-of-output marker,
7619 	 thus preserving logical ordering of input and output.  */
7620       if (XMARKER (p->mark)->buffer)
7621 	Fgoto_char (p->mark);
7622       else
7623 	SET_PT_BOTH (ZV, ZV_BYTE);
7624 
7625       before = PT;
7626       before_byte = PT_BYTE;
7627 
7628       tem = BVAR (current_buffer, read_only);
7629       bset_read_only (current_buffer, Qnil);
7630       insert_string ("\nProcess ");
7631       { /* FIXME: temporary kludge.  */
7632 	Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7633       insert_string (" ");
7634       Finsert (1, &msg);
7635       bset_read_only (current_buffer, tem);
7636       set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7637 
7638       if (opoint >= before)
7639 	SET_PT_BOTH (opoint + (PT - before),
7640 		     opoint_byte + (PT_BYTE - before_byte));
7641       else
7642 	SET_PT_BOTH (opoint, opoint_byte);
7643 
7644       set_buffer_internal (old);
7645     }
7646   return Qnil;
7647 }
7648 
7649 
7650 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7651        Sset_process_coding_system, 1, 3, 0,
7652        doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7653 DECODING will be used to decode subprocess output and ENCODING to
7654 encode subprocess input. */)
7655   (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7656 {
7657   CHECK_PROCESS (process);
7658 
7659   struct Lisp_Process *p = XPROCESS (process);
7660 
7661   Fcheck_coding_system (decoding);
7662   Fcheck_coding_system (encoding);
7663   encoding = coding_inherit_eol_type (encoding, Qnil);
7664   pset_decode_coding_system (p, decoding);
7665   pset_encode_coding_system (p, encoding);
7666 
7667   /* If the sockets haven't been set up yet, the final setup part of
7668      this will be called asynchronously. */
7669   if (p->infd < 0 || p->outfd < 0)
7670     return Qnil;
7671 
7672   setup_process_coding_systems (process);
7673 
7674   return Qnil;
7675 }
7676 
7677 DEFUN ("process-coding-system",
7678        Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7679        doc: /* Return a cons of coding systems for decoding and encoding of PROCESS.  */)
7680   (register Lisp_Object process)
7681 {
7682   CHECK_PROCESS (process);
7683   return Fcons (XPROCESS (process)->decode_coding_system,
7684 		XPROCESS (process)->encode_coding_system);
7685 }
7686 
7687 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7688        Sset_process_filter_multibyte, 2, 2, 0,
7689        doc: /* Set multibyteness of the strings given to PROCESS's filter.
7690 If FLAG is non-nil, the filter is given multibyte strings.
7691 If FLAG is nil, the filter is given unibyte strings.  In this case,
7692 all character code conversion except for end-of-line conversion is
7693 suppressed.  */)
7694   (Lisp_Object process, Lisp_Object flag)
7695 {
7696   CHECK_PROCESS (process);
7697 
7698   struct Lisp_Process *p = XPROCESS (process);
7699   if (NILP (flag))
7700     pset_decode_coding_system
7701       (p, raw_text_coding_system (p->decode_coding_system));
7702 
7703   /* If the sockets haven't been set up yet, the final setup part of
7704      this will be called asynchronously. */
7705   if (p->infd < 0 || p->outfd < 0)
7706     return Qnil;
7707 
7708   setup_process_coding_systems (process);
7709 
7710   return Qnil;
7711 }
7712 
7713 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7714        Sprocess_filter_multibyte_p, 1, 1, 0,
7715        doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7716   (Lisp_Object process)
7717 {
7718   CHECK_PROCESS (process);
7719   struct Lisp_Process *p = XPROCESS (process);
7720   if (p->infd < 0)
7721     return Qnil;
7722   eassert (p->infd < FD_SETSIZE);
7723   struct coding_system *coding = proc_decode_coding_system[p->infd];
7724   return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7725 }
7726 
7727 
7728 
7729 
7730 # ifdef HAVE_GPM
7731 
7732 void
add_gpm_wait_descriptor(int desc)7733 add_gpm_wait_descriptor (int desc)
7734 {
7735   add_keyboard_wait_descriptor (desc);
7736 }
7737 
7738 void
delete_gpm_wait_descriptor(int desc)7739 delete_gpm_wait_descriptor (int desc)
7740 {
7741   delete_keyboard_wait_descriptor (desc);
7742 }
7743 
7744 # endif
7745 
7746 #if defined (USABLE_SIGIO) || defined (USABLE_SIGPOLL)
7747 
7748 /* Return true if *MASK has a bit set
7749    that corresponds to one of the keyboard input descriptors.  */
7750 
7751 static bool
keyboard_bit_set(fd_set * mask)7752 keyboard_bit_set (fd_set *mask)
7753 {
7754   int fd;
7755 
7756   eassert (max_desc < FD_SETSIZE);
7757   for (fd = 0; fd <= max_desc; fd++)
7758     if (FD_ISSET (fd, mask)
7759 	&& ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7760 	    == (FOR_READ | KEYBOARD_FD)))
7761       return 1;
7762 
7763   return 0;
7764 }
7765 # endif
7766 
7767 #else  /* not subprocesses */
7768 
7769 /* This is referenced in thread.c:run_thread (which is never actually
7770    called, since threads are not enabled for this configuration.  */
7771 void
update_processes_for_thread_death(Lisp_Object dying_thread)7772 update_processes_for_thread_death (Lisp_Object dying_thread)
7773 {
7774 }
7775 
7776 /* Defined in msdos.c.  */
7777 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7778 		       struct timespec *, void *);
7779 
7780 /* Implementation of wait_reading_process_output, assuming that there
7781    are no subprocesses.  Used only by the MS-DOS build.
7782 
7783    Wait for timeout to elapse and/or keyboard input to be available.
7784 
7785    TIME_LIMIT is:
7786      timeout in seconds
7787      If negative, gobble data immediately available but don't wait for any.
7788 
7789    NSECS is:
7790      an additional duration to wait, measured in nanoseconds
7791      If TIME_LIMIT is zero, then:
7792        If NSECS == 0, there is no limit.
7793        If NSECS > 0, the timeout consists of NSECS only.
7794        If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7795 
7796    READ_KBD is:
7797      0 to ignore keyboard input, or
7798      1 to return when input is available, or
7799      -1 means caller will actually read the input, so don't throw to
7800        the quit handler.
7801 
7802    see full version for other parameters. We know that wait_proc will
7803      always be NULL, since `subprocesses' isn't defined.
7804 
7805    DO_DISPLAY means redisplay should be done to show subprocess
7806    output that arrives.
7807 
7808    Return -1 signifying we got no output and did not try.  */
7809 
7810 int
wait_reading_process_output(intmax_t time_limit,int nsecs,int read_kbd,bool do_display,Lisp_Object wait_for_cell,struct Lisp_Process * wait_proc,int just_wait_proc)7811 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7812 			     bool do_display,
7813 			     Lisp_Object wait_for_cell,
7814 			     struct Lisp_Process *wait_proc, int just_wait_proc)
7815 {
7816   register int nfds;
7817   struct timespec end_time, timeout;
7818   enum { MINIMUM = -1, TIMEOUT, FOREVER } wait;
7819 
7820   if (TYPE_MAXIMUM (time_t) < time_limit)
7821     time_limit = TYPE_MAXIMUM (time_t);
7822 
7823   if (time_limit < 0 || nsecs < 0)
7824     wait = MINIMUM;
7825   else if (time_limit > 0 || nsecs > 0)
7826     {
7827       wait = TIMEOUT;
7828       end_time = timespec_add (current_timespec (),
7829                                make_timespec (time_limit, nsecs));
7830     }
7831   else
7832     wait = FOREVER;
7833 
7834   /* Turn off periodic alarms (in case they are in use)
7835      and then turn off any other atimers,
7836      because the select emulator uses alarms.  */
7837   stop_polling ();
7838   turn_on_atimers (0);
7839 
7840   while (1)
7841     {
7842       bool timeout_reduced_for_timers = false;
7843       fd_set waitchannels;
7844       int xerrno;
7845 
7846       /* If calling from keyboard input, do not quit
7847 	 since we want to return C-g as an input character.
7848 	 Otherwise, do pending quit if requested.  */
7849       if (read_kbd >= 0)
7850 	maybe_quit ();
7851 
7852       /* Exit now if the cell we're waiting for became non-nil.  */
7853       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7854 	break;
7855 
7856       /* Compute time from now till when time limit is up.  */
7857       /* Exit if already run out.  */
7858       if (wait == TIMEOUT)
7859 	{
7860 	  struct timespec now = current_timespec ();
7861 	  if (timespec_cmp (end_time, now) <= 0)
7862 	    break;
7863 	  timeout = timespec_sub (end_time, now);
7864 	}
7865       else
7866 	timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7867 
7868       /* If our caller will not immediately handle keyboard events,
7869 	 run timer events directly.
7870 	 (Callers that will immediately read keyboard events
7871 	 call timer_delay on their own.)  */
7872       if (NILP (wait_for_cell))
7873 	{
7874 	  struct timespec timer_delay;
7875 
7876 	  do
7877 	    {
7878 	      unsigned old_timers_run = timers_run;
7879 	      timer_delay = timer_check ();
7880 	      if (timers_run != old_timers_run && do_display)
7881 		/* We must retry, since a timer may have requeued itself
7882 		   and that could alter the time delay.  */
7883 		redisplay_preserve_echo_area (14);
7884 	      else
7885 		break;
7886 	    }
7887 	  while (!detect_input_pending ());
7888 
7889 	  /* If there is unread keyboard input, also return.  */
7890 	  if (read_kbd != 0
7891 	      && requeued_events_pending_p ())
7892 	    break;
7893 
7894 	  if (timespec_valid_p (timer_delay))
7895 	    {
7896 	      if (timespec_cmp (timer_delay, timeout) < 0)
7897 		{
7898 		  timeout = timer_delay;
7899 		  timeout_reduced_for_timers = true;
7900 		}
7901 	    }
7902 	}
7903 
7904       /* Cause C-g and alarm signals to take immediate action,
7905 	 and cause input available signals to zero out timeout.  */
7906       if (read_kbd < 0)
7907 	set_waiting_for_input (&timeout);
7908 
7909       /* If a frame has been newly mapped and needs updating,
7910 	 reprocess its display stuff.  */
7911       if (frame_garbaged && do_display)
7912 	{
7913 	  clear_waiting_for_input ();
7914 	  redisplay_preserve_echo_area (15);
7915 	  if (read_kbd < 0)
7916 	    set_waiting_for_input (&timeout);
7917 	}
7918 
7919       /* Wait till there is something to do.  */
7920       FD_ZERO (&waitchannels);
7921       if (read_kbd && detect_input_pending ())
7922 	nfds = 0;
7923       else
7924 	{
7925 	  if (read_kbd || !NILP (wait_for_cell))
7926 	    FD_SET (0, &waitchannels);
7927 	  nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7928 	}
7929 
7930       xerrno = errno;
7931 
7932       /* Make C-g and alarm signals set flags again.  */
7933       clear_waiting_for_input ();
7934 
7935       /*  If we woke up due to SIGWINCH, actually change size now.  */
7936       do_pending_window_change (0);
7937 
7938       if (wait < FOREVER && nfds == 0 && ! timeout_reduced_for_timers)
7939 	/* We waited the full specified time, so return now.  */
7940 	break;
7941 
7942       if (nfds == -1)
7943 	{
7944 	  /* If the system call was interrupted, then go around the
7945 	     loop again.  */
7946 	  if (xerrno == EINTR)
7947 	    FD_ZERO (&waitchannels);
7948 	  else
7949 	    report_file_errno ("Failed select", Qnil, xerrno);
7950 	}
7951 
7952       /* Check for keyboard input.  */
7953 
7954       if (read_kbd
7955 	  && detect_input_pending_run_timers (do_display))
7956 	{
7957 	  swallow_events (do_display);
7958 	  if (detect_input_pending_run_timers (do_display))
7959 	    break;
7960 	}
7961 
7962       /* If there is unread keyboard input, also return.  */
7963       if (read_kbd
7964 	  && requeued_events_pending_p ())
7965 	break;
7966 
7967       /* If wait_for_cell. check for keyboard input
7968 	 but don't run any timers.
7969 	 ??? (It seems wrong to me to check for keyboard
7970 	 input at all when wait_for_cell, but the code
7971 	 has been this way since July 1994.
7972 	 Try changing this after version 19.31.)  */
7973       if (! NILP (wait_for_cell)
7974 	  && detect_input_pending ())
7975 	{
7976 	  swallow_events (do_display);
7977 	  if (detect_input_pending ())
7978 	    break;
7979 	}
7980 
7981       /* Exit now if the cell we're waiting for became non-nil.  */
7982       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7983 	break;
7984     }
7985 
7986   start_polling ();
7987 
7988   return -1;
7989 }
7990 
7991 #endif	/* not subprocesses */
7992 
7993 /* The following functions are needed even if async subprocesses are
7994    not supported.  Some of them are no-op stubs in that case.  */
7995 
7996 #ifdef HAVE_TIMERFD
7997 
7998 /* Add FD, which is a descriptor returned by timerfd_create,
7999    to the set of non-keyboard input descriptors.  */
8000 
8001 void
add_timer_wait_descriptor(int fd)8002 add_timer_wait_descriptor (int fd)
8003 {
8004   eassert (0 <= fd && fd < FD_SETSIZE);
8005   add_read_fd (fd, timerfd_callback, NULL);
8006   fd_callback_info[fd].flags &= ~KEYBOARD_FD;
8007 }
8008 
8009 #endif /* HAVE_TIMERFD */
8010 
8011 /* If program file NAME starts with /: for quoting a magic
8012    name, remove that, preserving the multibyteness of NAME.  */
8013 
8014 Lisp_Object
remove_slash_colon(Lisp_Object name)8015 remove_slash_colon (Lisp_Object name)
8016 {
8017   return
8018     (SREF (name, 0) == '/' && SREF (name, 1) == ':'
8019      ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
8020 			      SBYTES (name) - 2, STRING_MULTIBYTE (name))
8021      : name);
8022 }
8023 
8024 /* Add DESC to the set of keyboard input descriptors.  */
8025 
8026 void
add_keyboard_wait_descriptor(int desc)8027 add_keyboard_wait_descriptor (int desc)
8028 {
8029 #ifdef subprocesses /* Actually means "not MSDOS".  */
8030   eassert (desc >= 0 && desc < FD_SETSIZE);
8031   fd_callback_info[desc].flags &= ~PROCESS_FD;
8032   fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
8033   if (desc > max_desc)
8034     max_desc = desc;
8035 #endif
8036 }
8037 
8038 /* From now on, do not expect DESC to give keyboard input.  */
8039 
8040 void
delete_keyboard_wait_descriptor(int desc)8041 delete_keyboard_wait_descriptor (int desc)
8042 {
8043 #ifdef subprocesses
8044   eassert (desc >= 0 && desc < FD_SETSIZE);
8045 
8046   fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
8047 
8048   if (desc == max_desc)
8049     recompute_max_desc ();
8050 #endif
8051 }
8052 
8053 /* Setup coding systems of PROCESS.  */
8054 
8055 void
setup_process_coding_systems(Lisp_Object process)8056 setup_process_coding_systems (Lisp_Object process)
8057 {
8058 #ifdef subprocesses
8059   struct Lisp_Process *p = XPROCESS (process);
8060   int inch = p->infd;
8061   int outch = p->outfd;
8062   Lisp_Object coding_system;
8063 
8064   if (inch < 0 || outch < 0)
8065     return;
8066 
8067   eassert (0 <= inch && inch < FD_SETSIZE);
8068   if (!proc_decode_coding_system[inch])
8069     proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
8070   coding_system = p->decode_coding_system;
8071   if (EQ (p->filter, Qinternal_default_process_filter)
8072       && BUFFERP (p->buffer))
8073     {
8074       if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
8075 	coding_system = raw_text_coding_system (coding_system);
8076     }
8077   setup_coding_system (coding_system, proc_decode_coding_system[inch]);
8078 
8079   eassert (0 <= outch && outch < FD_SETSIZE);
8080   if (!proc_encode_coding_system[outch])
8081     proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
8082   setup_coding_system (p->encode_coding_system,
8083 		       proc_encode_coding_system[outch]);
8084 #endif
8085 }
8086 
8087 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
8088        doc: /* Return the (or a) live process associated with BUFFER.
8089 BUFFER may be a buffer or the name of one.
8090 Return nil if all processes associated with BUFFER have been
8091 deleted or killed.  */)
8092   (register Lisp_Object buffer)
8093 {
8094 #ifdef subprocesses
8095   register Lisp_Object buf, tail, proc;
8096 
8097   if (NILP (buffer)) return Qnil;
8098   buf = Fget_buffer (buffer);
8099   if (NILP (buf)) return Qnil;
8100 
8101   FOR_EACH_PROCESS (tail, proc)
8102     if (EQ (XPROCESS (proc)->buffer, buf))
8103       return proc;
8104 #endif	/* subprocesses */
8105   return Qnil;
8106 }
8107 
8108 DEFUN ("process-inherit-coding-system-flag",
8109        Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
8110        1, 1, 0,
8111        doc: /* Return the value of inherit-coding-system flag for PROCESS.
8112 If this flag is t, `buffer-file-coding-system' of the buffer
8113 associated with PROCESS will inherit the coding system used to decode
8114 the process output.  */)
8115   (register Lisp_Object process)
8116 {
8117 #ifdef subprocesses
8118   CHECK_PROCESS (process);
8119   return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
8120 #else
8121   /* Ignore the argument and return the value of
8122      inherit-process-coding-system.  */
8123   return inherit_process_coding_system ? Qt : Qnil;
8124 #endif
8125 }
8126 
8127 /* Kill all processes associated with `buffer'.
8128    If `buffer' is nil, kill all processes.  */
8129 
8130 void
kill_buffer_processes(Lisp_Object buffer)8131 kill_buffer_processes (Lisp_Object buffer)
8132 {
8133 #ifdef subprocesses
8134   Lisp_Object tail, proc;
8135 
8136   FOR_EACH_PROCESS (tail, proc)
8137     if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
8138       {
8139 	if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
8140 	  Fdelete_process (proc);
8141 	else if (XPROCESS (proc)->infd >= 0)
8142 	  process_send_signal (proc, SIGHUP, Qnil, 1);
8143       }
8144 #else  /* subprocesses */
8145   /* Since we have no subprocesses, this does nothing.  */
8146 #endif /* subprocesses */
8147 }
8148 
8149 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
8150        Swaiting_for_user_input_p, 0, 0, 0,
8151        doc: /* Return non-nil if Emacs is waiting for input from the user.
8152 This is intended for use by asynchronous process output filters and sentinels.  */)
8153   (void)
8154 {
8155 #ifdef subprocesses
8156   return (waiting_for_user_input_p ? Qt : Qnil);
8157 #else
8158   return Qnil;
8159 #endif
8160 }
8161 
8162 /* Stop reading input from keyboard sources.  */
8163 
8164 void
hold_keyboard_input(void)8165 hold_keyboard_input (void)
8166 {
8167   kbd_is_on_hold = 1;
8168 }
8169 
8170 /* Resume reading input from keyboard sources.  */
8171 
8172 void
unhold_keyboard_input(void)8173 unhold_keyboard_input (void)
8174 {
8175   kbd_is_on_hold = 0;
8176 }
8177 
8178 /* Return true if keyboard input is on hold, zero otherwise.  */
8179 
8180 bool
kbd_on_hold_p(void)8181 kbd_on_hold_p (void)
8182 {
8183   return kbd_is_on_hold;
8184 }
8185 
8186 
8187 /* Enumeration of and access to system processes a-la ps(1).  */
8188 
8189 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
8190        0, 0, 0,
8191        doc: /* Return a list of numerical process IDs of all running processes.
8192 If this functionality is unsupported, return nil.
8193 
8194 See `process-attributes' for getting attributes of a process given its ID.  */)
8195   (void)
8196 {
8197   return list_system_processes ();
8198 }
8199 
8200 DEFUN ("process-attributes", Fprocess_attributes,
8201        Sprocess_attributes, 1, 1, 0,
8202        doc: /* Return attributes of the process given by its PID, a number.
8203 
8204 Value is an alist where each element is a cons cell of the form
8205 
8206     (KEY . VALUE)
8207 
8208 If this functionality is unsupported, the value is nil.
8209 
8210 See `list-system-processes' for getting a list of all process IDs.
8211 
8212 The KEYs of the attributes that this function may return are listed
8213 below, together with the type of the associated VALUE (in parentheses).
8214 Not all platforms support all of these attributes; unsupported
8215 attributes will not appear in the returned alist.
8216 Unless explicitly indicated otherwise, numbers can have either
8217 integer or floating point values.
8218 
8219  euid    -- Effective user User ID of the process (number)
8220  user    -- User name corresponding to euid (string)
8221  egid    -- Effective user Group ID of the process (number)
8222  group   -- Group name corresponding to egid (string)
8223  comm    -- Command name (executable name only) (string)
8224  state   -- Process state code, such as "S", "R", or "T" (string)
8225  ppid    -- Parent process ID (number)
8226  pgrp    -- Process group ID (number)
8227  sess    -- Session ID, i.e. process ID of session leader (number)
8228  ttname  -- Controlling tty name (string)
8229  tpgid   -- ID of foreground process group on the process's tty (number)
8230  minflt  -- number of minor page faults (number)
8231  majflt  -- number of major page faults (number)
8232  cminflt -- cumulative number of minor page faults (number)
8233  cmajflt -- cumulative number of major page faults (number)
8234  utime   -- user time used by the process, in `current-time' format
8235  stime   -- system time used by the process (current-time)
8236  time    -- sum of utime and stime (current-time)
8237  cutime  -- user time used by the process and its children (current-time)
8238  cstime  -- system time used by the process and its children (current-time)
8239  ctime   -- sum of cutime and cstime (current-time)
8240  pri     -- priority of the process (number)
8241  nice    -- nice value of the process (number)
8242  thcount -- process thread count (number)
8243  start   -- time the process started (current-time)
8244  vsize   -- virtual memory size of the process in KB's (number)
8245  rss     -- resident set size of the process in KB's (number)
8246  etime   -- elapsed time the process is running (current-time)
8247  pcpu    -- percents of CPU time used by the process (floating-point number)
8248  pmem    -- percents of total physical memory used by process's resident set
8249               (floating-point number)
8250  args    -- command line which invoked the process (string).  */)
8251   ( Lisp_Object pid)
8252 {
8253   return system_process_attributes (pid);
8254 }
8255 
8256 DEFUN ("num-processors", Fnum_processors, Snum_processors, 0, 1, 0,
8257        doc: /* Return the number of processors, a positive integer.
8258 Each usable thread execution unit counts as a processor.
8259 By default, count the number of available processors,
8260 overridable via the OMP_NUM_THREADS environment variable.
8261 If optional argument QUERY is `current', ignore OMP_NUM_THREADS.
8262 If QUERY is `all', also count processors not available.  */)
8263   (Lisp_Object query)
8264 {
8265 #ifndef MSDOS
8266   return make_uint (num_processors (EQ (query, Qall) ? NPROC_ALL
8267 				    : EQ (query, Qcurrent) ? NPROC_CURRENT
8268 				    : NPROC_CURRENT_OVERRIDABLE));
8269 #else
8270   return make_fixnum (1);
8271 #endif
8272 }
8273 
8274 #ifdef subprocesses
8275 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
8276    Invoke this after init_process_emacs, and after glib and/or GNUstep
8277    futz with the SIGCHLD handler, but before Emacs forks any children.
8278    This function's caller should block SIGCHLD.  */
8279 
8280 void
catch_child_signal(void)8281 catch_child_signal (void)
8282 {
8283   struct sigaction action, old_action;
8284   sigset_t oldset;
8285   emacs_sigaction_init (&action, deliver_child_signal);
8286   block_child_signal (&oldset);
8287   sigaction (SIGCHLD, &action, &old_action);
8288   eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
8289 	   || ! (old_action.sa_flags & SA_SIGINFO));
8290 
8291   if (old_action.sa_handler != deliver_child_signal)
8292     lib_child_handler
8293       = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
8294 	 ? dummy_handler
8295 	 : old_action.sa_handler);
8296   unblock_child_signal (&oldset);
8297 }
8298 #endif	/* subprocesses */
8299 
8300 /* Limit the number of open files to the value it had at startup.  */
8301 
8302 void
restore_nofile_limit(void)8303 restore_nofile_limit (void)
8304 {
8305 #ifdef HAVE_SETRLIMIT
8306   if (FD_SETSIZE < nofile_limit.rlim_cur)
8307     setrlimit (RLIMIT_NOFILE, &nofile_limit);
8308 #endif
8309 }
8310 
8311 int
open_channel_for_module(Lisp_Object process)8312 open_channel_for_module (Lisp_Object process)
8313 {
8314   CHECK_PROCESS (process);
8315   CHECK_TYPE (PIPECONN_P (process), Qpipe_process_p, process);
8316 #ifndef MSDOS
8317   int fd = dup (XPROCESS (process)->open_fd[SUBPROCESS_STDOUT]);
8318   if (fd == -1)
8319     report_file_error ("Cannot duplicate file descriptor", Qnil);
8320   return fd;
8321 #else
8322   /* PIPECONN_P returning true shouldn't be possible on MSDOS.  */
8323   emacs_abort ();
8324 #endif
8325 }
8326 
8327 
8328 /* This is not called "init_process" because that is the name of a
8329    Mach system call, so it would cause problems on Darwin systems.  */
8330 void
init_process_emacs(int sockfd)8331 init_process_emacs (int sockfd)
8332 {
8333 #ifdef subprocesses
8334   int i;
8335 
8336   inhibit_sentinels = 0;
8337 
8338   if (!will_dump_with_unexec_p ())
8339     {
8340 #if defined HAVE_GLIB && !defined WINDOWSNT
8341       /* Tickle glib's child-handling code.  Ask glib to install a
8342 	 watch source for Emacs itself which will initialize glib's
8343 	 private SIGCHLD handler, allowing catch_child_signal to copy
8344 	 it into lib_child_handler.
8345 
8346          Unfortunately in glib commit 2e471acf, the behavior changed to
8347          always install a signal handler when g_child_watch_source_new
8348          is called and not just the first time it's called.  Glib also
8349          now resets signal handlers to SIG_DFL when it no longer has a
8350          watcher on that signal.  This is a hackey work around to get
8351          glib's g_unix_signal_handler into lib_child_handler.  */
8352       GSource *source = g_child_watch_source_new (getpid ());
8353       catch_child_signal ();
8354       g_source_unref (source);
8355 
8356       eassert (lib_child_handler != dummy_handler);
8357       signal_handler_t lib_child_handler_glib = lib_child_handler;
8358       catch_child_signal ();
8359       eassert (lib_child_handler == dummy_handler);
8360       lib_child_handler = lib_child_handler_glib;
8361 #else
8362       catch_child_signal ();
8363 #endif
8364     }
8365 
8366 #ifdef HAVE_SETRLIMIT
8367   /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself.  */
8368   if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
8369     nofile_limit.rlim_cur = 0;
8370   else if (FD_SETSIZE < nofile_limit.rlim_cur)
8371     {
8372       struct rlimit rlim = nofile_limit;
8373       rlim.rlim_cur = FD_SETSIZE;
8374       if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
8375 	nofile_limit.rlim_cur = 0;
8376     }
8377 #endif
8378 
8379   external_sock_fd = sockfd;
8380   Lisp_Object sockname = Qnil;
8381 # if HAVE_GETSOCKNAME
8382   if (0 <= sockfd)
8383     {
8384       union u_sockaddr sa;
8385       socklen_t salen = sizeof sa;
8386       if (getsockname (sockfd, &sa.sa, &salen) == 0)
8387 	sockname = conv_sockaddr_to_lisp (&sa.sa, salen);
8388     }
8389 # endif
8390   Vinternal__daemon_sockname = sockname;
8391 
8392   max_desc = -1;
8393   memset (fd_callback_info, 0, sizeof (fd_callback_info));
8394 
8395   num_pending_connects = 0;
8396 
8397   process_output_delay_count = 0;
8398   process_output_skip = 0;
8399 
8400   /* Don't do this, it caused infinite select loops.  The display
8401      method should call add_keyboard_wait_descriptor on stdin if it
8402      needs that.  */
8403 #if 0
8404   FD_SET (0, &input_wait_mask);
8405 #endif
8406 
8407   Vprocess_alist = Qnil;
8408   deleted_pid_list = Qnil;
8409   for (i = 0; i < FD_SETSIZE; i++)
8410     {
8411       chan_process[i] = Qnil;
8412       proc_buffered_char[i] = -1;
8413     }
8414   memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
8415   memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
8416 #ifdef DATAGRAM_SOCKETS
8417   memset (datagram_address, 0, sizeof datagram_address);
8418 #endif
8419 
8420 #endif	/* subprocesses */
8421   kbd_is_on_hold = 0;
8422 }
8423 
8424 void
syms_of_process(void)8425 syms_of_process (void)
8426 {
8427   DEFSYM (Qmake_process, "make-process");
8428 
8429 #ifdef subprocesses
8430 
8431   DEFSYM (Qprocessp, "processp");
8432   DEFSYM (Qrun, "run");
8433   DEFSYM (Qstop, "stop");
8434   DEFSYM (Qsignal, "signal");
8435 
8436   /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8437      here again.  */
8438 
8439   DEFSYM (Qopen, "open");
8440   DEFSYM (Qclosed, "closed");
8441   DEFSYM (Qconnect, "connect");
8442   DEFSYM (Qfailed, "failed");
8443   DEFSYM (Qlisten, "listen");
8444   DEFSYM (Qlocal, "local");
8445   DEFSYM (Qipv4, "ipv4");
8446 #ifdef AF_INET6
8447   DEFSYM (Qipv6, "ipv6");
8448 #endif
8449   DEFSYM (Qdatagram, "datagram");
8450   DEFSYM (Qseqpacket, "seqpacket");
8451 
8452   DEFSYM (QCport, ":port");
8453   DEFSYM (QCspeed, ":speed");
8454   DEFSYM (QCprocess, ":process");
8455 
8456   DEFSYM (QCbytesize, ":bytesize");
8457   DEFSYM (QCstopbits, ":stopbits");
8458   DEFSYM (QCparity, ":parity");
8459   DEFSYM (Qodd, "odd");
8460   DEFSYM (Qeven, "even");
8461   DEFSYM (QCflowcontrol, ":flowcontrol");
8462   DEFSYM (Qhw, "hw");
8463   DEFSYM (Qsw, "sw");
8464   DEFSYM (QCsummary, ":summary");
8465 
8466   DEFSYM (Qreal, "real");
8467   DEFSYM (Qnetwork, "network");
8468   DEFSYM (Qserial, "serial");
8469   DEFSYM (QCfile_handler, ":file-handler");
8470   DEFSYM (QCbuffer, ":buffer");
8471   DEFSYM (QChost, ":host");
8472   DEFSYM (QCservice, ":service");
8473   DEFSYM (QClocal, ":local");
8474   DEFSYM (QCremote, ":remote");
8475   DEFSYM (QCcoding, ":coding");
8476   DEFSYM (QCserver, ":server");
8477   DEFSYM (QCnowait, ":nowait");
8478   DEFSYM (QCsentinel, ":sentinel");
8479   DEFSYM (QCuse_external_socket, ":use-external-socket");
8480   DEFSYM (QCtls_parameters, ":tls-parameters");
8481   DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8482   DEFSYM (QClog, ":log");
8483   DEFSYM (QCnoquery, ":noquery");
8484   DEFSYM (QCstop, ":stop");
8485   DEFSYM (QCplist, ":plist");
8486   DEFSYM (QCcommand, ":command");
8487   DEFSYM (QCconnection_type, ":connection-type");
8488   DEFSYM (QCstderr, ":stderr");
8489   DEFSYM (Qpty, "pty");
8490   DEFSYM (Qpipe, "pipe");
8491 
8492   DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8493 
8494   staticpro (&Vprocess_alist);
8495   staticpro (&deleted_pid_list);
8496 
8497 #endif	/* subprocesses */
8498 
8499   DEFSYM (QCname, ":name");
8500   DEFSYM (QCtype, ":type");
8501 
8502   DEFSYM (Qeuid, "euid");
8503   DEFSYM (Qegid, "egid");
8504   DEFSYM (Quser, "user");
8505   DEFSYM (Qgroup, "group");
8506   DEFSYM (Qcomm, "comm");
8507   DEFSYM (Qstate, "state");
8508   DEFSYM (Qppid, "ppid");
8509   DEFSYM (Qpgrp, "pgrp");
8510   DEFSYM (Qsess, "sess");
8511   DEFSYM (Qttname, "ttname");
8512   DEFSYM (Qtpgid, "tpgid");
8513   DEFSYM (Qminflt, "minflt");
8514   DEFSYM (Qmajflt, "majflt");
8515   DEFSYM (Qcminflt, "cminflt");
8516   DEFSYM (Qcmajflt, "cmajflt");
8517   DEFSYM (Qutime, "utime");
8518   DEFSYM (Qstime, "stime");
8519   DEFSYM (Qtime, "time");
8520   DEFSYM (Qcutime, "cutime");
8521   DEFSYM (Qcstime, "cstime");
8522   DEFSYM (Qctime, "ctime");
8523 #ifdef subprocesses
8524   DEFSYM (Qinternal_default_process_sentinel,
8525 	  "internal-default-process-sentinel");
8526   DEFSYM (Qinternal_default_process_filter,
8527 	  "internal-default-process-filter");
8528 #endif
8529   DEFSYM (Qpri, "pri");
8530   DEFSYM (Qnice, "nice");
8531   DEFSYM (Qthcount, "thcount");
8532   DEFSYM (Qstart, "start");
8533   DEFSYM (Qvsize, "vsize");
8534   DEFSYM (Qrss, "rss");
8535   DEFSYM (Qetime, "etime");
8536   DEFSYM (Qpcpu, "pcpu");
8537   DEFSYM (Qpmem, "pmem");
8538   DEFSYM (Qargs, "args");
8539   DEFSYM (Qall, "all");
8540   DEFSYM (Qcurrent, "current");
8541 
8542   DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8543 	       doc: /* Non-nil means delete processes immediately when they exit.
8544 A value of nil means don't delete them until `list-processes' is run.  */);
8545 
8546   delete_exited_processes = 1;
8547 
8548 #ifdef subprocesses
8549   DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8550 	       doc: /* Control type of device used to communicate with subprocesses.
8551 Values are nil to use a pipe, or t or `pty' to use a pty.
8552 The value has no effect if the system has no ptys or if all ptys are busy:
8553 then a pipe is used in any case.
8554 The value takes effect when `start-process' is called.  */);
8555   Vprocess_connection_type = Qt;
8556 
8557   DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8558 	       doc: /* If non-nil, improve receive buffering by delaying after short reads.
8559 On some systems, when Emacs reads the output from a subprocess, the output data
8560 is read in very small blocks, potentially resulting in very poor performance.
8561 This behavior can be remedied to some extent by setting this variable to a
8562 non-nil value, as it will automatically delay reading from such processes, to
8563 allow them to produce more output before Emacs tries to read it.
8564 If the value is t, the delay is reset after each write to the process; any other
8565 non-nil value means that the delay is not reset on write.
8566 The variable takes effect when `start-process' is called.  */);
8567   Vprocess_adaptive_read_buffering = Qt;
8568 
8569   DEFVAR_BOOL ("process-prioritize-lower-fds", process_prioritize_lower_fds,
8570 	       doc: /* Whether to start checking for subprocess output from first file descriptor.
8571 Emacs loops through file descriptors to check for output from subprocesses.
8572 If this variable is nil, the default, then after accepting output from a
8573 subprocess, Emacs will continue checking the rest of descriptors, starting
8574 from the one following the descriptor it just read.  If this variable is
8575 non-nil, Emacs will always restart the loop from the first file descriptor,
8576 thus favoring processes with lower descriptors.  */);
8577   process_prioritize_lower_fds = 0;
8578 
8579   DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions,
8580 	       doc: /* List of functions to be called for `interrupt-process'.
8581 The arguments of the functions are the same as for `interrupt-process'.
8582 These functions are called in the order of the list, until one of them
8583 returns non-nil.  */);
8584   Vinterrupt_process_functions = list1 (Qinternal_default_interrupt_process);
8585 
8586   DEFVAR_LISP ("internal--daemon-sockname", Vinternal__daemon_sockname,
8587 	       doc: /* Name of external socket passed to Emacs, or nil if none.  */);
8588   Vinternal__daemon_sockname = Qnil;
8589 
8590   DEFVAR_INT ("read-process-output-max", read_process_output_max,
8591 	      doc: /* Maximum number of bytes to read from subprocess in a single chunk.
8592 Enlarge the value only if the subprocess generates very large (megabytes)
8593 amounts of data in one go.  */);
8594   read_process_output_max = 4096;
8595 
8596   DEFVAR_INT ("process-error-pause-time", process_error_pause_time,
8597 	      doc: /* The number of seconds to pause after handling process errors.
8598 This isn't used for all process-related errors, but is used when a
8599 sentinel or a process filter function has an error.  */);
8600   process_error_pause_time = 1;
8601 
8602   DEFSYM (Qinternal_default_interrupt_process,
8603 	  "internal-default-interrupt-process");
8604   DEFSYM (Qinterrupt_process_functions, "interrupt-process-functions");
8605 
8606   DEFSYM (Qnull, "null");
8607   DEFSYM (Qpipe_process_p, "pipe-process-p");
8608 
8609   defsubr (&Sprocessp);
8610   defsubr (&Sget_process);
8611   defsubr (&Sdelete_process);
8612   defsubr (&Sprocess_status);
8613   defsubr (&Sprocess_exit_status);
8614   defsubr (&Sprocess_id);
8615   defsubr (&Sprocess_name);
8616   defsubr (&Sprocess_tty_name);
8617   defsubr (&Sprocess_command);
8618   defsubr (&Sset_process_buffer);
8619   defsubr (&Sprocess_buffer);
8620   defsubr (&Sprocess_mark);
8621   defsubr (&Sset_process_filter);
8622   defsubr (&Sprocess_filter);
8623   defsubr (&Sset_process_sentinel);
8624   defsubr (&Sprocess_sentinel);
8625   defsubr (&Sset_process_thread);
8626   defsubr (&Sprocess_thread);
8627   defsubr (&Sset_process_window_size);
8628   defsubr (&Sset_process_inherit_coding_system_flag);
8629   defsubr (&Sset_process_query_on_exit_flag);
8630   defsubr (&Sprocess_query_on_exit_flag);
8631   defsubr (&Sprocess_contact);
8632   defsubr (&Sprocess_plist);
8633   defsubr (&Sset_process_plist);
8634   defsubr (&Sprocess_list);
8635   defsubr (&Smake_process);
8636   defsubr (&Smake_pipe_process);
8637   defsubr (&Sserial_process_configure);
8638   defsubr (&Smake_serial_process);
8639   defsubr (&Sset_network_process_option);
8640   defsubr (&Smake_network_process);
8641   defsubr (&Sformat_network_address);
8642   defsubr (&Snetwork_lookup_address_info);
8643   defsubr (&Snetwork_interface_list);
8644   defsubr (&Snetwork_interface_info);
8645 #ifdef DATAGRAM_SOCKETS
8646   defsubr (&Sprocess_datagram_address);
8647   defsubr (&Sset_process_datagram_address);
8648 #endif
8649   defsubr (&Saccept_process_output);
8650   defsubr (&Sprocess_send_region);
8651   defsubr (&Sprocess_send_string);
8652   defsubr (&Sinternal_default_interrupt_process);
8653   defsubr (&Sinterrupt_process);
8654   defsubr (&Skill_process);
8655   defsubr (&Squit_process);
8656   defsubr (&Sstop_process);
8657   defsubr (&Scontinue_process);
8658   defsubr (&Sprocess_running_child_p);
8659   defsubr (&Sprocess_send_eof);
8660   defsubr (&Ssignal_process);
8661   defsubr (&Swaiting_for_user_input_p);
8662   defsubr (&Sprocess_type);
8663   defsubr (&Sinternal_default_process_sentinel);
8664   defsubr (&Sinternal_default_process_filter);
8665   defsubr (&Sset_process_coding_system);
8666   defsubr (&Sprocess_coding_system);
8667   defsubr (&Sset_process_filter_multibyte);
8668   defsubr (&Sprocess_filter_multibyte_p);
8669 
8670  {
8671    Lisp_Object subfeatures = Qnil;
8672    const struct socket_options *sopt;
8673 
8674 #define ADD_SUBFEATURE(key, val) \
8675   subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8676 
8677    ADD_SUBFEATURE (QCnowait, Qt);
8678 #ifdef DATAGRAM_SOCKETS
8679    ADD_SUBFEATURE (QCtype, Qdatagram);
8680 #endif
8681 #ifdef HAVE_SEQPACKET
8682    ADD_SUBFEATURE (QCtype, Qseqpacket);
8683 #endif
8684 #ifdef HAVE_LOCAL_SOCKETS
8685    ADD_SUBFEATURE (QCfamily, Qlocal);
8686 #endif
8687    ADD_SUBFEATURE (QCfamily, Qipv4);
8688 #ifdef AF_INET6
8689    ADD_SUBFEATURE (QCfamily, Qipv6);
8690 #endif
8691 #ifdef HAVE_GETSOCKNAME
8692    ADD_SUBFEATURE (QCservice, Qt);
8693 #endif
8694    ADD_SUBFEATURE (QCserver, Qt);
8695 
8696    for (sopt = socket_options; sopt->name; sopt++)
8697      subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8698 
8699    Fprovide (intern_c_string ("make-network-process"), subfeatures);
8700  }
8701 
8702 #endif	/* subprocesses */
8703 
8704   defsubr (&Sget_buffer_process);
8705   defsubr (&Sprocess_inherit_coding_system_flag);
8706   defsubr (&Slist_system_processes);
8707   defsubr (&Sprocess_attributes);
8708   defsubr (&Snum_processors);
8709 }
8710