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