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