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