; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / src / process.c
blob6dba218c90726559a71cc04ec0d38749ad9fd19d
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2018 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <fcntl.h>
33 #include "lisp.h"
35 /* Only MS-DOS does not define `subprocesses'. */
36 #ifdef subprocesses
38 #include <sys/socket.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
43 #endif /* subprocesses */
45 #ifdef HAVE_SETRLIMIT
46 # include <sys/resource.h>
48 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
49 NOFILE_LIMIT is the initial limit on the number of open files,
50 which should be restored in child processes. */
51 static struct rlimit nofile_limit;
52 #endif
54 #ifdef subprocesses
56 /* Are local (unix) sockets supported? */
57 #if defined (HAVE_SYS_UN_H)
58 #if !defined (AF_LOCAL) && defined (AF_UNIX)
59 #define AF_LOCAL AF_UNIX
60 #endif
61 #ifdef AF_LOCAL
62 #define HAVE_LOCAL_SOCKETS
63 #include <sys/un.h>
64 #endif
65 #endif
67 #include <sys/ioctl.h>
68 #if defined (HAVE_NET_IF_H)
69 #include <net/if.h>
70 #endif /* HAVE_NET_IF_H */
72 #if defined (HAVE_IFADDRS_H)
73 /* Must be after net/if.h */
74 #include <ifaddrs.h>
76 /* We only use structs from this header when we use getifaddrs. */
77 #if defined (HAVE_NET_IF_DL_H)
78 #include <net/if_dl.h>
79 #endif
81 #endif
83 #ifdef NEED_BSDTTY
84 #include <bsdtty.h>
85 #endif
87 #ifdef USG5_4
88 # include <sys/stream.h>
89 # include <sys/stropts.h>
90 #endif
92 #ifdef HAVE_UTIL_H
93 #include <util.h>
94 #endif
96 #ifdef HAVE_PTY_H
97 #include <pty.h>
98 #endif
100 #include <c-ctype.h>
101 #include <flexmember.h>
102 #include <sig2str.h>
103 #include <verify.h>
105 #endif /* subprocesses */
107 #include "systime.h"
108 #include "systty.h"
110 #include "window.h"
111 #include "character.h"
112 #include "buffer.h"
113 #include "coding.h"
114 #include "process.h"
115 #include "frame.h"
116 #include "termopts.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "atimer.h"
120 #include "sysselect.h"
121 #include "syssignal.h"
122 #include "syswait.h"
123 #ifdef HAVE_GNUTLS
124 #include "gnutls.h"
125 #endif
127 #ifdef HAVE_WINDOW_SYSTEM
128 #include TERM_HEADER
129 #endif /* HAVE_WINDOW_SYSTEM */
131 #ifdef HAVE_GLIB
132 #include "xgselect.h"
133 #ifndef WINDOWSNT
134 #include <glib.h>
135 #endif
136 #endif
138 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
139 /* This is 0.1s in nanoseconds. */
140 #define ASYNC_RETRY_NSEC 100000000
141 #endif
143 #ifdef WINDOWSNT
144 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
145 const struct timespec *, const sigset_t *);
146 #endif
148 /* Work around GCC 4.3.0 bug with strict overflow checking; see
149 <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
150 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
151 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
152 # pragma GCC diagnostic ignored "-Wstrict-overflow"
153 #endif
155 /* True if keyboard input is on hold, zero otherwise. */
157 static bool kbd_is_on_hold;
159 /* Nonzero means don't run process sentinels. This is used
160 when exiting. */
161 bool inhibit_sentinels;
163 union u_sockaddr
165 struct sockaddr sa;
166 struct sockaddr_in in;
167 #ifdef AF_INET6
168 struct sockaddr_in6 in6;
169 #endif
170 #ifdef HAVE_LOCAL_SOCKETS
171 struct sockaddr_un un;
172 #endif
175 #ifdef subprocesses
177 #ifndef SOCK_CLOEXEC
178 # define SOCK_CLOEXEC 0
179 #endif
180 #ifndef SOCK_NONBLOCK
181 # define SOCK_NONBLOCK 0
182 #endif
184 /* True if ERRNUM represents an error where the system call would
185 block if a blocking variant were used. */
186 static bool
187 would_block (int errnum)
189 #ifdef EWOULDBLOCK
190 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
191 return true;
192 #endif
193 return errnum == EAGAIN;
196 #ifndef HAVE_ACCEPT4
198 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
200 static int
201 close_on_exec (int fd)
203 if (0 <= fd)
204 fcntl (fd, F_SETFD, FD_CLOEXEC);
205 return fd;
208 # undef accept4
209 # define accept4(sockfd, addr, addrlen, flags) \
210 process_accept4 (sockfd, addr, addrlen, flags)
211 static int
212 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
214 return close_on_exec (accept (sockfd, addr, addrlen));
217 static int
218 process_socket (int domain, int type, int protocol)
220 return close_on_exec (socket (domain, type, protocol));
222 # undef socket
223 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
224 #endif
226 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
227 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
228 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
229 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
230 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
231 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
233 /* Number of events of change of status of a process. */
234 static EMACS_INT process_tick;
235 /* Number of events for which the user or sentinel has been notified. */
236 static EMACS_INT update_tick;
238 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
239 this system. We need to read full packets, so we need a
240 "non-destructive" select. So we require either native select,
241 or emulation of select using FIONREAD. */
243 #ifndef BROKEN_DATAGRAM_SOCKETS
244 # if defined HAVE_SELECT || defined USABLE_FIONREAD
245 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
246 # define DATAGRAM_SOCKETS
247 # endif
248 # endif
249 #endif
251 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
252 # define HAVE_SEQPACKET
253 #endif
255 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
256 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
257 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
259 /* Number of processes which have a non-zero read_output_delay,
260 and therefore might be delayed for adaptive read buffering. */
262 static int process_output_delay_count;
264 /* True if any process has non-nil read_output_skip. */
266 static bool process_output_skip;
268 static void start_process_unwind (Lisp_Object);
269 static void create_process (Lisp_Object, char **, Lisp_Object);
270 #ifdef USABLE_SIGIO
271 static bool keyboard_bit_set (fd_set *);
272 #endif
273 static void deactivate_process (Lisp_Object);
274 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
275 static int read_process_output (Lisp_Object, int);
276 static void create_pty (Lisp_Object);
277 static void exec_sentinel (Lisp_Object, Lisp_Object);
279 /* Number of bits set in connect_wait_mask. */
280 static int num_pending_connects;
282 /* The largest descriptor currently in use; -1 if none. */
283 static int max_desc;
285 /* Set the external socket descriptor for Emacs to use when
286 `make-network-process' is called with a non-nil
287 `:use-external-socket' option. The value should be either -1, or
288 the file descriptor of a socket that is already bound. */
289 static int external_sock_fd;
291 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
292 static Lisp_Object chan_process[FD_SETSIZE];
293 static void wait_for_socket_fds (Lisp_Object, char const *);
295 /* Alist of elements (NAME . PROCESS). */
296 static Lisp_Object Vprocess_alist;
298 /* Buffered-ahead input char from process, indexed by channel.
299 -1 means empty (no char is buffered).
300 Used on sys V where the only way to tell if there is any
301 output from the process is to read at least one char.
302 Always -1 on systems that support FIONREAD. */
304 static int proc_buffered_char[FD_SETSIZE];
306 /* Table of `struct coding-system' for each process. */
307 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
308 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
310 #ifdef DATAGRAM_SOCKETS
311 /* Table of `partner address' for datagram sockets. */
312 static struct sockaddr_and_len {
313 struct sockaddr *sa;
314 ptrdiff_t len;
315 } datagram_address[FD_SETSIZE];
316 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
317 #define DATAGRAM_CONN_P(proc) \
318 (PROCESSP (proc) && \
319 XPROCESS (proc)->infd >= 0 && \
320 datagram_address[XPROCESS (proc)->infd].sa != 0)
321 #else
322 #define DATAGRAM_CONN_P(proc) (0)
323 #endif
325 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
326 a `for' loop which iterates over processes from Vprocess_alist. */
328 #define FOR_EACH_PROCESS(list_var, proc_var) \
329 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
331 /* These setters are used only in this file, so they can be private. */
332 static void
333 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
335 p->buffer = val;
337 static void
338 pset_command (struct Lisp_Process *p, Lisp_Object val)
340 p->command = val;
342 static void
343 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
345 p->decode_coding_system = val;
347 static void
348 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
350 p->decoding_buf = val;
352 static void
353 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
355 p->encode_coding_system = val;
357 static void
358 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
360 p->encoding_buf = val;
362 static void
363 pset_filter (struct Lisp_Process *p, Lisp_Object val)
365 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
367 static void
368 pset_log (struct Lisp_Process *p, Lisp_Object val)
370 p->log = val;
372 static void
373 pset_mark (struct Lisp_Process *p, Lisp_Object val)
375 p->mark = val;
377 static void
378 pset_thread (struct Lisp_Process *p, Lisp_Object val)
380 p->thread = val;
382 static void
383 pset_name (struct Lisp_Process *p, Lisp_Object val)
385 p->name = val;
387 static void
388 pset_plist (struct Lisp_Process *p, Lisp_Object val)
390 p->plist = val;
392 static void
393 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
395 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
397 static void
398 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
400 p->tty_name = val;
402 static void
403 pset_type (struct Lisp_Process *p, Lisp_Object val)
405 p->type = val;
407 static void
408 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
410 p->write_queue = val;
412 static void
413 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
415 p->stderrproc = val;
419 static Lisp_Object
420 make_lisp_proc (struct Lisp_Process *p)
422 return make_lisp_ptr (p, Lisp_Vectorlike);
425 enum fd_bits
427 /* Read from file descriptor. */
428 FOR_READ = 1,
429 /* Write to file descriptor. */
430 FOR_WRITE = 2,
431 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
432 set. */
433 KEYBOARD_FD = 4,
434 /* This descriptor refers to a process. */
435 PROCESS_FD = 8,
436 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
437 NON_BLOCKING_CONNECT_FD = 16
440 static struct fd_callback_data
442 fd_callback func;
443 void *data;
444 /* Flags from enum fd_bits. */
445 int flags;
446 /* If this fd is locked to a certain thread, this points to it.
447 Otherwise, this is NULL. If an fd is locked to a thread, then
448 only that thread is permitted to wait on it. */
449 struct thread_state *thread;
450 /* If this fd is currently being selected on by a thread, this
451 points to the thread. Otherwise it is NULL. */
452 struct thread_state *waiting_thread;
453 } fd_callback_info[FD_SETSIZE];
456 /* Add a file descriptor FD to be monitored for when read is possible.
457 When read is possible, call FUNC with argument DATA. */
459 void
460 add_read_fd (int fd, fd_callback func, void *data)
462 add_keyboard_wait_descriptor (fd);
464 fd_callback_info[fd].func = func;
465 fd_callback_info[fd].data = data;
468 static void
469 add_non_keyboard_read_fd (int fd)
471 eassert (fd >= 0 && fd < FD_SETSIZE);
472 eassert (fd_callback_info[fd].func == NULL);
474 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
475 fd_callback_info[fd].flags |= FOR_READ;
476 if (fd > max_desc)
477 max_desc = fd;
480 static void
481 add_process_read_fd (int fd)
483 add_non_keyboard_read_fd (fd);
484 fd_callback_info[fd].flags |= PROCESS_FD;
487 /* Stop monitoring file descriptor FD for when read is possible. */
489 void
490 delete_read_fd (int fd)
492 delete_keyboard_wait_descriptor (fd);
494 if (fd_callback_info[fd].flags == 0)
496 fd_callback_info[fd].func = 0;
497 fd_callback_info[fd].data = 0;
501 /* Add a file descriptor FD to be monitored for when write is possible.
502 When write is possible, call FUNC with argument DATA. */
504 void
505 add_write_fd (int fd, fd_callback func, void *data)
507 eassert (fd >= 0 && fd < FD_SETSIZE);
509 fd_callback_info[fd].func = func;
510 fd_callback_info[fd].data = data;
511 fd_callback_info[fd].flags |= FOR_WRITE;
512 if (fd > max_desc)
513 max_desc = fd;
516 static void
517 add_non_blocking_write_fd (int fd)
519 eassert (fd >= 0 && fd < FD_SETSIZE);
520 eassert (fd_callback_info[fd].func == NULL);
522 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
523 if (fd > max_desc)
524 max_desc = fd;
525 ++num_pending_connects;
528 static void
529 recompute_max_desc (void)
531 int fd;
533 for (fd = max_desc; fd >= 0; --fd)
535 if (fd_callback_info[fd].flags != 0)
537 max_desc = fd;
538 break;
543 /* Stop monitoring file descriptor FD for when write is possible. */
545 void
546 delete_write_fd (int fd)
548 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
550 if (--num_pending_connects < 0)
551 emacs_abort ();
553 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
554 if (fd_callback_info[fd].flags == 0)
556 fd_callback_info[fd].func = 0;
557 fd_callback_info[fd].data = 0;
559 if (fd == max_desc)
560 recompute_max_desc ();
564 static void
565 compute_input_wait_mask (fd_set *mask)
567 int fd;
569 FD_ZERO (mask);
570 for (fd = 0; fd <= max_desc; ++fd)
572 if (fd_callback_info[fd].thread != NULL
573 && fd_callback_info[fd].thread != current_thread)
574 continue;
575 if (fd_callback_info[fd].waiting_thread != NULL
576 && fd_callback_info[fd].waiting_thread != current_thread)
577 continue;
578 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
580 FD_SET (fd, mask);
581 fd_callback_info[fd].waiting_thread = current_thread;
586 static void
587 compute_non_process_wait_mask (fd_set *mask)
589 int fd;
591 FD_ZERO (mask);
592 for (fd = 0; fd <= max_desc; ++fd)
594 if (fd_callback_info[fd].thread != NULL
595 && fd_callback_info[fd].thread != current_thread)
596 continue;
597 if (fd_callback_info[fd].waiting_thread != NULL
598 && fd_callback_info[fd].waiting_thread != current_thread)
599 continue;
600 if ((fd_callback_info[fd].flags & FOR_READ) != 0
601 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
603 FD_SET (fd, mask);
604 fd_callback_info[fd].waiting_thread = current_thread;
609 static void
610 compute_non_keyboard_wait_mask (fd_set *mask)
612 int fd;
614 FD_ZERO (mask);
615 for (fd = 0; fd <= max_desc; ++fd)
617 if (fd_callback_info[fd].thread != NULL
618 && fd_callback_info[fd].thread != current_thread)
619 continue;
620 if (fd_callback_info[fd].waiting_thread != NULL
621 && fd_callback_info[fd].waiting_thread != current_thread)
622 continue;
623 if ((fd_callback_info[fd].flags & FOR_READ) != 0
624 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
626 FD_SET (fd, mask);
627 fd_callback_info[fd].waiting_thread = current_thread;
632 static void
633 compute_write_mask (fd_set *mask)
635 int fd;
637 FD_ZERO (mask);
638 for (fd = 0; fd <= max_desc; ++fd)
640 if (fd_callback_info[fd].thread != NULL
641 && fd_callback_info[fd].thread != current_thread)
642 continue;
643 if (fd_callback_info[fd].waiting_thread != NULL
644 && fd_callback_info[fd].waiting_thread != current_thread)
645 continue;
646 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
648 FD_SET (fd, mask);
649 fd_callback_info[fd].waiting_thread = current_thread;
654 static void
655 clear_waiting_thread_info (void)
657 int fd;
659 for (fd = 0; fd <= max_desc; ++fd)
661 if (fd_callback_info[fd].waiting_thread == current_thread)
662 fd_callback_info[fd].waiting_thread = NULL;
667 /* Compute the Lisp form of the process status, p->status, from
668 the numeric status that was returned by `wait'. */
670 static Lisp_Object status_convert (int);
672 static void
673 update_status (struct Lisp_Process *p)
675 eassert (p->raw_status_new);
676 pset_status (p, status_convert (p->raw_status));
677 p->raw_status_new = 0;
680 /* Convert a process status word in Unix format to
681 the list that we use internally. */
683 static Lisp_Object
684 status_convert (int w)
686 if (WIFSTOPPED (w))
687 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
688 else if (WIFEXITED (w))
689 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
690 WCOREDUMP (w) ? Qt : Qnil));
691 else if (WIFSIGNALED (w))
692 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
693 WCOREDUMP (w) ? Qt : Qnil));
694 else
695 return Qrun;
698 /* True if STATUS is that of a process attempting connection. */
700 static bool
701 connecting_status (Lisp_Object status)
703 return CONSP (status) && EQ (XCAR (status), Qconnect);
706 /* Given a status-list, extract the three pieces of information
707 and store them individually through the three pointers. */
709 static void
710 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
711 bool *coredump)
713 Lisp_Object tem;
715 if (connecting_status (l))
716 l = XCAR (l);
718 if (SYMBOLP (l))
720 *symbol = l;
721 *code = make_number (0);
722 *coredump = 0;
724 else
726 *symbol = XCAR (l);
727 tem = XCDR (l);
728 *code = XCAR (tem);
729 tem = XCDR (tem);
730 *coredump = !NILP (tem);
734 /* Return a string describing a process status list. */
736 static Lisp_Object
737 status_message (struct Lisp_Process *p)
739 Lisp_Object status = p->status;
740 Lisp_Object symbol, code;
741 bool coredump;
742 Lisp_Object string;
744 decode_status (status, &symbol, &code, &coredump);
746 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
748 char const *signame;
749 synchronize_system_messages_locale ();
750 signame = strsignal (XFASTINT (code));
751 if (signame == 0)
752 string = build_string ("unknown");
753 else
755 int c1, c2;
757 string = build_unibyte_string (signame);
758 if (! NILP (Vlocale_coding_system))
759 string = (code_convert_string_norecord
760 (string, Vlocale_coding_system, 0));
761 c1 = STRING_CHAR (SDATA (string));
762 c2 = downcase (c1);
763 if (c1 != c2)
764 Faset (string, make_number (0), make_number (c2));
766 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
767 return concat2 (string, suffix);
769 else if (EQ (symbol, Qexit))
771 if (NETCONN1_P (p))
772 return build_string (XFASTINT (code) == 0
773 ? "deleted\n"
774 : "connection broken by remote peer\n");
775 if (XFASTINT (code) == 0)
776 return build_string ("finished\n");
777 AUTO_STRING (prefix, "exited abnormally with code ");
778 string = Fnumber_to_string (code);
779 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
780 return concat3 (prefix, string, suffix);
782 else if (EQ (symbol, Qfailed))
784 AUTO_STRING (format, "failed with code %s\n");
785 return CALLN (Fformat, format, code);
787 else
788 return Fcopy_sequence (Fsymbol_name (symbol));
791 enum { PTY_NAME_SIZE = 24 };
793 /* Open an available pty, returning a file descriptor.
794 Store into PTY_NAME the file name of the terminal corresponding to the pty.
795 Return -1 on failure. */
797 static int
798 allocate_pty (char pty_name[PTY_NAME_SIZE])
800 #ifdef HAVE_PTYS
801 int fd;
803 #ifdef PTY_ITERATION
804 PTY_ITERATION
805 #else
806 register int c, i;
807 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
808 for (i = 0; i < 16; i++)
809 #endif
811 #ifdef PTY_NAME_SPRINTF
812 PTY_NAME_SPRINTF
813 #else
814 sprintf (pty_name, "/dev/pty%c%x", c, i);
815 #endif /* no PTY_NAME_SPRINTF */
817 #ifdef PTY_OPEN
818 PTY_OPEN;
819 #else /* no PTY_OPEN */
820 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
821 #endif /* no PTY_OPEN */
823 if (fd >= 0)
825 #ifdef PTY_TTY_NAME_SPRINTF
826 PTY_TTY_NAME_SPRINTF
827 #else
828 sprintf (pty_name, "/dev/tty%c%x", c, i);
829 #endif /* no PTY_TTY_NAME_SPRINTF */
831 /* Set FD's close-on-exec flag. This is needed even if
832 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
833 doesn't require support for that combination.
834 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
835 doesn't work if the close-on-exec flag is set (Bug#20555).
836 Multithreaded platforms where posix_openpt ignores
837 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
838 have a race condition between the PTY_OPEN and here. */
839 fcntl (fd, F_SETFD, FD_CLOEXEC);
841 /* Check to make certain that both sides are available.
842 This avoids a nasty yet stupid bug in rlogins. */
843 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
845 emacs_close (fd);
846 continue;
848 setup_pty (fd);
849 return fd;
852 #endif /* HAVE_PTYS */
853 return -1;
856 /* Allocate basically initialized process. */
858 static struct Lisp_Process *
859 allocate_process (void)
861 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
864 static Lisp_Object
865 make_process (Lisp_Object name)
867 struct Lisp_Process *p = allocate_process ();
868 /* Initialize Lisp data. Note that allocate_process initializes all
869 Lisp data to nil, so do it only for slots which should not be nil. */
870 pset_status (p, Qrun);
871 pset_mark (p, Fmake_marker ());
872 pset_thread (p, Fcurrent_thread ());
874 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
875 non-Lisp data, so do it only for slots which should not be zero. */
876 p->infd = -1;
877 p->outfd = -1;
878 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
879 p->open_fd[i] = -1;
881 #ifdef HAVE_GNUTLS
882 verify (GNUTLS_STAGE_EMPTY == 0);
883 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
884 eassert (NILP (p->gnutls_boot_parameters));
885 #endif
887 /* If name is already in use, modify it until it is unused. */
889 Lisp_Object name1 = name;
890 for (printmax_t i = 1; ; i++)
892 Lisp_Object tem = Fget_process (name1);
893 if (NILP (tem))
894 break;
895 char const suffix_fmt[] = "<%"pMd">";
896 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
897 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
898 name1 = concat2 (name, lsuffix);
900 name = name1;
901 pset_name (p, name);
902 pset_sentinel (p, Qinternal_default_process_sentinel);
903 pset_filter (p, Qinternal_default_process_filter);
904 Lisp_Object val;
905 XSETPROCESS (val, p);
906 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
907 return val;
910 static void
911 remove_process (register Lisp_Object proc)
913 register Lisp_Object pair;
915 pair = Frassq (proc, Vprocess_alist);
916 Vprocess_alist = Fdelq (pair, Vprocess_alist);
918 deactivate_process (proc);
921 void
922 update_processes_for_thread_death (Lisp_Object dying_thread)
924 Lisp_Object pair;
926 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
928 Lisp_Object process = XCDR (XCAR (pair));
929 if (EQ (XPROCESS (process)->thread, dying_thread))
931 struct Lisp_Process *proc = XPROCESS (process);
933 pset_thread (proc, Qnil);
934 if (proc->infd >= 0)
935 fd_callback_info[proc->infd].thread = NULL;
936 if (proc->outfd >= 0)
937 fd_callback_info[proc->outfd].thread = NULL;
942 #ifdef HAVE_GETADDRINFO_A
943 static void
944 free_dns_request (Lisp_Object proc)
946 struct Lisp_Process *p = XPROCESS (proc);
948 if (p->dns_request->ar_result)
949 freeaddrinfo (p->dns_request->ar_result);
950 xfree (p->dns_request);
951 p->dns_request = NULL;
953 #endif
956 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
957 doc: /* Return t if OBJECT is a process. */)
958 (Lisp_Object object)
960 return PROCESSP (object) ? Qt : Qnil;
963 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
964 doc: /* Return the process named NAME, or nil if there is none. */)
965 (register Lisp_Object name)
967 if (PROCESSP (name))
968 return name;
969 CHECK_STRING (name);
970 return Fcdr (Fassoc (name, Vprocess_alist, Qnil));
973 /* This is how commands for the user decode process arguments. It
974 accepts a process, a process name, a buffer, a buffer name, or nil.
975 Buffers denote the first process in the buffer, and nil denotes the
976 current buffer. */
978 static Lisp_Object
979 get_process (register Lisp_Object name)
981 register Lisp_Object proc, obj;
982 if (STRINGP (name))
984 obj = Fget_process (name);
985 if (NILP (obj))
986 obj = Fget_buffer (name);
987 if (NILP (obj))
988 error ("Process %s does not exist", SDATA (name));
990 else if (NILP (name))
991 obj = Fcurrent_buffer ();
992 else
993 obj = name;
995 /* Now obj should be either a buffer object or a process object. */
996 if (BUFFERP (obj))
998 if (NILP (BVAR (XBUFFER (obj), name)))
999 error ("Attempt to get process for a dead buffer");
1000 proc = Fget_buffer_process (obj);
1001 if (NILP (proc))
1002 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
1004 else
1006 CHECK_PROCESS (obj);
1007 proc = obj;
1009 return proc;
1013 /* Fdelete_process promises to immediately forget about the process, but in
1014 reality, Emacs needs to remember those processes until they have been
1015 treated by the SIGCHLD handler and waitpid has been invoked on them;
1016 otherwise they might fill up the kernel's process table.
1018 Some processes created by call-process are also put onto this list.
1020 Members of this list are (process-ID . filename) pairs. The
1021 process-ID is a number; the filename, if a string, is a file that
1022 needs to be removed after the process exits. */
1023 static Lisp_Object deleted_pid_list;
1025 void
1026 record_deleted_pid (pid_t pid, Lisp_Object filename)
1028 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1029 /* GC treated elements set to nil. */
1030 Fdelq (Qnil, deleted_pid_list));
1034 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1035 doc: /* Delete PROCESS: kill it and forget about it immediately.
1036 PROCESS may be a process, a buffer, the name of a process or buffer, or
1037 nil, indicating the current buffer's process. */)
1038 (register Lisp_Object process)
1040 register struct Lisp_Process *p;
1042 process = get_process (process);
1043 p = XPROCESS (process);
1045 #ifdef HAVE_GETADDRINFO_A
1046 if (p->dns_request)
1048 /* Cancel the request. Unless shutting down, wait until
1049 completion. Free the request if completely canceled. */
1051 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
1052 if (!canceled && !inhibit_sentinels)
1054 struct gaicb const *req = p->dns_request;
1055 while (gai_suspend (&req, 1, NULL) != 0)
1056 continue;
1057 canceled = true;
1059 if (canceled)
1060 free_dns_request (process);
1062 #endif
1064 p->raw_status_new = 0;
1065 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1067 pset_status (p, list2 (Qexit, make_number (0)));
1068 p->tick = ++process_tick;
1069 status_notify (p, NULL);
1070 redisplay_preserve_echo_area (13);
1072 else
1074 if (p->alive)
1075 record_kill_process (p, Qnil);
1077 if (p->infd >= 0)
1079 /* Update P's status, since record_kill_process will make the
1080 SIGCHLD handler update deleted_pid_list, not *P. */
1081 Lisp_Object symbol;
1082 if (p->raw_status_new)
1083 update_status (p);
1084 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1085 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1086 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1088 p->tick = ++process_tick;
1089 status_notify (p, NULL);
1090 redisplay_preserve_echo_area (13);
1093 remove_process (process);
1094 return Qnil;
1097 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1098 doc: /* Return the status of PROCESS.
1099 The returned value is one of the following symbols:
1100 run -- for a process that is running.
1101 stop -- for a process stopped but continuable.
1102 exit -- for a process that has exited.
1103 signal -- for a process that has got a fatal signal.
1104 open -- for a network stream connection that is open.
1105 listen -- for a network stream server that is listening.
1106 closed -- for a network stream connection that is closed.
1107 connect -- when waiting for a non-blocking connection to complete.
1108 failed -- when a non-blocking connection has failed.
1109 nil -- if arg is a process name and no such process exists.
1110 PROCESS may be a process, a buffer, the name of a process, or
1111 nil, indicating the current buffer's process. */)
1112 (register Lisp_Object process)
1114 register struct Lisp_Process *p;
1115 register Lisp_Object status;
1117 if (STRINGP (process))
1118 process = Fget_process (process);
1119 else
1120 process = get_process (process);
1122 if (NILP (process))
1123 return process;
1125 p = XPROCESS (process);
1126 if (p->raw_status_new)
1127 update_status (p);
1128 status = p->status;
1129 if (CONSP (status))
1130 status = XCAR (status);
1131 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1133 if (EQ (status, Qexit))
1134 status = Qclosed;
1135 else if (EQ (p->command, Qt))
1136 status = Qstop;
1137 else if (EQ (status, Qrun))
1138 status = Qopen;
1140 return status;
1143 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1144 1, 1, 0,
1145 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1146 If PROCESS has not yet exited or died, return 0. */)
1147 (register Lisp_Object process)
1149 CHECK_PROCESS (process);
1150 if (XPROCESS (process)->raw_status_new)
1151 update_status (XPROCESS (process));
1152 if (CONSP (XPROCESS (process)->status))
1153 return XCAR (XCDR (XPROCESS (process)->status));
1154 return make_number (0);
1157 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1158 doc: /* Return the process id of PROCESS.
1159 This is the pid of the external process which PROCESS uses or talks to.
1160 For a network, serial, and pipe connections, this value is nil. */)
1161 (register Lisp_Object process)
1163 pid_t pid;
1165 CHECK_PROCESS (process);
1166 pid = XPROCESS (process)->pid;
1167 return (pid ? make_fixnum_or_float (pid) : Qnil);
1170 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1171 doc: /* Return the name of PROCESS, as a string.
1172 This is the name of the program invoked in PROCESS,
1173 possibly modified to make it unique among process names. */)
1174 (register Lisp_Object process)
1176 CHECK_PROCESS (process);
1177 return XPROCESS (process)->name;
1180 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1181 doc: /* Return the command that was executed to start PROCESS.
1182 This is a list of strings, the first string being the program executed
1183 and the rest of the strings being the arguments given to it.
1184 For a network or serial or pipe connection, this is nil (process is running)
1185 or t (process is stopped). */)
1186 (register Lisp_Object process)
1188 CHECK_PROCESS (process);
1189 return XPROCESS (process)->command;
1192 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1193 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1194 This is the terminal that the process itself reads and writes on,
1195 not the name of the pty that Emacs uses to talk with that terminal. */)
1196 (register Lisp_Object process)
1198 CHECK_PROCESS (process);
1199 return XPROCESS (process)->tty_name;
1202 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1203 2, 2, 0,
1204 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1205 Return BUFFER. */)
1206 (register Lisp_Object process, Lisp_Object buffer)
1208 struct Lisp_Process *p;
1210 CHECK_PROCESS (process);
1211 if (!NILP (buffer))
1212 CHECK_BUFFER (buffer);
1213 p = XPROCESS (process);
1214 pset_buffer (p, buffer);
1215 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1216 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1217 setup_process_coding_systems (process);
1218 return buffer;
1221 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1222 1, 1, 0,
1223 doc: /* Return the buffer PROCESS is associated with.
1224 The default process filter inserts output from PROCESS into this buffer. */)
1225 (register Lisp_Object process)
1227 CHECK_PROCESS (process);
1228 return XPROCESS (process)->buffer;
1231 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1232 1, 1, 0,
1233 doc: /* Return the marker for the end of the last output from PROCESS. */)
1234 (register Lisp_Object process)
1236 CHECK_PROCESS (process);
1237 return XPROCESS (process)->mark;
1240 static void
1241 set_process_filter_masks (struct Lisp_Process *p)
1243 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1244 delete_read_fd (p->infd);
1245 else if (EQ (p->filter, Qt)
1246 /* Network or serial process not stopped: */
1247 && !EQ (p->command, Qt))
1248 add_process_read_fd (p->infd);
1251 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1252 2, 2, 0,
1253 doc: /* Give PROCESS the filter function FILTER; nil means default.
1254 A value of t means stop accepting output from the process.
1256 When a process has a non-default filter, its buffer is not used for output.
1257 Instead, each time it does output, the entire string of output is
1258 passed to the filter.
1260 The filter gets two arguments: the process and the string of output.
1261 The string argument is normally a multibyte string, except:
1262 - if the process's input coding system is no-conversion or raw-text,
1263 it is a unibyte string (the non-converted input). */)
1264 (Lisp_Object process, Lisp_Object filter)
1266 CHECK_PROCESS (process);
1267 struct Lisp_Process *p = XPROCESS (process);
1269 /* Don't signal an error if the process's input file descriptor
1270 is closed. This could make debugging Lisp more difficult,
1271 for example when doing something like
1273 (setq process (start-process ...))
1274 (debug)
1275 (set-process-filter process ...) */
1277 if (NILP (filter))
1278 filter = Qinternal_default_process_filter;
1280 pset_filter (p, filter);
1282 if (p->infd >= 0)
1283 set_process_filter_masks (p);
1285 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1286 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1287 setup_process_coding_systems (process);
1288 return filter;
1291 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1292 1, 1, 0,
1293 doc: /* Return the filter function of PROCESS.
1294 See `set-process-filter' for more info on filter functions. */)
1295 (register Lisp_Object process)
1297 CHECK_PROCESS (process);
1298 return XPROCESS (process)->filter;
1301 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1302 2, 2, 0,
1303 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1304 The sentinel is called as a function when the process changes state.
1305 It gets two arguments: the process, and a string describing the change. */)
1306 (register Lisp_Object process, Lisp_Object sentinel)
1308 struct Lisp_Process *p;
1310 CHECK_PROCESS (process);
1311 p = XPROCESS (process);
1313 if (NILP (sentinel))
1314 sentinel = Qinternal_default_process_sentinel;
1316 pset_sentinel (p, sentinel);
1317 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1318 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1319 return sentinel;
1322 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1323 1, 1, 0,
1324 doc: /* Return the sentinel of PROCESS.
1325 See `set-process-sentinel' for more info on sentinels. */)
1326 (register Lisp_Object process)
1328 CHECK_PROCESS (process);
1329 return XPROCESS (process)->sentinel;
1332 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1333 2, 2, 0,
1334 doc: /* Set the locking thread of PROCESS to be THREAD.
1335 If THREAD is nil, the process is unlocked. */)
1336 (Lisp_Object process, Lisp_Object thread)
1338 struct Lisp_Process *proc;
1339 struct thread_state *tstate;
1341 CHECK_PROCESS (process);
1342 if (NILP (thread))
1343 tstate = NULL;
1344 else
1346 CHECK_THREAD (thread);
1347 tstate = XTHREAD (thread);
1350 proc = XPROCESS (process);
1351 pset_thread (proc, thread);
1352 if (proc->infd >= 0)
1353 fd_callback_info[proc->infd].thread = tstate;
1354 if (proc->outfd >= 0)
1355 fd_callback_info[proc->outfd].thread = tstate;
1357 return thread;
1360 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1361 1, 1, 0,
1362 doc: /* Ret the locking thread of PROCESS.
1363 If PROCESS is unlocked, this function returns nil. */)
1364 (Lisp_Object process)
1366 CHECK_PROCESS (process);
1367 return XPROCESS (process)->thread;
1370 DEFUN ("set-process-window-size", Fset_process_window_size,
1371 Sset_process_window_size, 3, 3, 0,
1372 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1373 Value is t if PROCESS was successfully told about the window size,
1374 nil otherwise. */)
1375 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1377 CHECK_PROCESS (process);
1379 /* All known platforms store window sizes as 'unsigned short'. */
1380 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1381 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1383 if (NETCONN_P (process)
1384 || XPROCESS (process)->infd < 0
1385 || (set_window_size (XPROCESS (process)->infd,
1386 XINT (height), XINT (width))
1387 < 0))
1388 return Qnil;
1389 else
1390 return Qt;
1393 DEFUN ("set-process-inherit-coding-system-flag",
1394 Fset_process_inherit_coding_system_flag,
1395 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1396 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1397 If the second argument FLAG is non-nil, then the variable
1398 `buffer-file-coding-system' of the buffer associated with PROCESS
1399 will be bound to the value of the coding system used to decode
1400 the process output.
1402 This is useful when the coding system specified for the process buffer
1403 leaves either the character code conversion or the end-of-line conversion
1404 unspecified, or if the coding system used to decode the process output
1405 is more appropriate for saving the process buffer.
1407 Binding the variable `inherit-process-coding-system' to non-nil before
1408 starting the process is an alternative way of setting the inherit flag
1409 for the process which will run.
1411 This function returns FLAG. */)
1412 (register Lisp_Object process, Lisp_Object flag)
1414 CHECK_PROCESS (process);
1415 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1416 return flag;
1419 DEFUN ("set-process-query-on-exit-flag",
1420 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1421 2, 2, 0,
1422 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1423 If the second argument FLAG is non-nil, Emacs will query the user before
1424 exiting or killing a buffer if PROCESS is running. This function
1425 returns FLAG. */)
1426 (register Lisp_Object process, Lisp_Object flag)
1428 CHECK_PROCESS (process);
1429 XPROCESS (process)->kill_without_query = NILP (flag);
1430 return flag;
1433 DEFUN ("process-query-on-exit-flag",
1434 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1435 1, 1, 0,
1436 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1437 (register Lisp_Object process)
1439 CHECK_PROCESS (process);
1440 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1443 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1444 1, 2, 0,
1445 doc: /* Return the contact info of PROCESS; t for a real child.
1446 For a network or serial or pipe connection, the value depends on the
1447 optional KEY arg. If KEY is nil, value is a cons cell of the form
1448 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1449 connection; it is t for a pipe connection. If KEY is t, the complete
1450 contact information for the connection is returned, else the specific
1451 value for the keyword KEY is returned. See `make-network-process',
1452 `make-serial-process', or `make-pipe-process' for the list of keywords.
1453 If PROCESS is a non-blocking network process that hasn't been fully
1454 set up yet, this function will block until socket setup has completed. */)
1455 (Lisp_Object process, Lisp_Object key)
1457 Lisp_Object contact;
1459 CHECK_PROCESS (process);
1460 contact = XPROCESS (process)->childp;
1462 #ifdef DATAGRAM_SOCKETS
1464 if (NETCONN_P (process))
1465 wait_for_socket_fds (process, "process-contact");
1467 if (DATAGRAM_CONN_P (process)
1468 && (EQ (key, Qt) || EQ (key, QCremote)))
1469 contact = Fplist_put (contact, QCremote,
1470 Fprocess_datagram_address (process));
1471 #endif
1473 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1474 || EQ (key, Qt))
1475 return contact;
1476 if (NILP (key) && NETCONN_P (process))
1477 return list2 (Fplist_get (contact, QChost),
1478 Fplist_get (contact, QCservice));
1479 if (NILP (key) && SERIALCONN_P (process))
1480 return list2 (Fplist_get (contact, QCport),
1481 Fplist_get (contact, QCspeed));
1482 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1483 if the pipe process is useful for purposes other than receiving
1484 stderr. */
1485 if (NILP (key) && PIPECONN_P (process))
1486 return Qt;
1487 return Fplist_get (contact, key);
1490 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1491 1, 1, 0,
1492 doc: /* Return the plist of PROCESS. */)
1493 (register Lisp_Object process)
1495 CHECK_PROCESS (process);
1496 return XPROCESS (process)->plist;
1499 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1500 2, 2, 0,
1501 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1502 (Lisp_Object process, Lisp_Object plist)
1504 CHECK_PROCESS (process);
1505 CHECK_LIST (plist);
1507 pset_plist (XPROCESS (process), plist);
1508 return plist;
1511 #if 0 /* Turned off because we don't currently record this info
1512 in the process. Perhaps add it. */
1513 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1514 doc: /* Return the connection type of PROCESS.
1515 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1516 a socket connection. */)
1517 (Lisp_Object process)
1519 return XPROCESS (process)->type;
1521 #endif
1523 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1524 doc: /* Return the connection type of PROCESS.
1525 The value is either the symbol `real', `network', `serial', or `pipe'.
1526 PROCESS may be a process, a buffer, the name of a process or buffer, or
1527 nil, indicating the current buffer's process. */)
1528 (Lisp_Object process)
1530 Lisp_Object proc;
1531 proc = get_process (process);
1532 return XPROCESS (proc)->type;
1535 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1536 1, 2, 0,
1537 doc: /* Convert network ADDRESS from internal format to a string.
1538 A 4 or 5 element vector represents an IPv4 address (with port number).
1539 An 8 or 9 element vector represents an IPv6 address (with port number).
1540 If optional second argument OMIT-PORT is non-nil, don't include a port
1541 number in the string, even when present in ADDRESS.
1542 Return nil if format of ADDRESS is invalid. */)
1543 (Lisp_Object address, Lisp_Object omit_port)
1545 if (NILP (address))
1546 return Qnil;
1548 if (STRINGP (address)) /* AF_LOCAL */
1549 return address;
1551 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1553 register struct Lisp_Vector *p = XVECTOR (address);
1554 ptrdiff_t size = p->header.size;
1555 Lisp_Object args[10];
1556 int nargs, i;
1557 char const *format;
1559 if (size == 4 || (size == 5 && !NILP (omit_port)))
1561 format = "%d.%d.%d.%d";
1562 nargs = 4;
1564 else if (size == 5)
1566 format = "%d.%d.%d.%d:%d";
1567 nargs = 5;
1569 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1571 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1572 nargs = 8;
1574 else if (size == 9)
1576 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1577 nargs = 9;
1579 else
1580 return Qnil;
1582 AUTO_STRING (format_obj, format);
1583 args[0] = format_obj;
1585 for (i = 0; i < nargs; i++)
1587 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1588 return Qnil;
1590 if (nargs <= 5 /* IPv4 */
1591 && i < 4 /* host, not port */
1592 && XINT (p->contents[i]) > 255)
1593 return Qnil;
1595 args[i + 1] = p->contents[i];
1598 return Fformat (nargs + 1, args);
1601 if (CONSP (address))
1603 AUTO_STRING (format, "<Family %d>");
1604 return CALLN (Fformat, format, Fcar (address));
1607 return Qnil;
1610 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1611 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1612 (void)
1614 return Fmapcar (Qcdr, Vprocess_alist);
1617 /* Starting asynchronous inferior processes. */
1619 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1620 doc: /* Start a program in a subprocess. Return the process object for it.
1622 This is similar to `start-process', but arguments are specified as
1623 keyword/argument pairs. The following arguments are defined:
1625 :name NAME -- NAME is name for process. It is modified if necessary
1626 to make it unique.
1628 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1629 with the process. Process output goes at end of that buffer, unless
1630 you specify a filter function to handle the output. BUFFER may be
1631 also nil, meaning that this process is not associated with any buffer.
1633 :command COMMAND -- COMMAND is a list starting with the program file
1634 name, followed by strings to give to the program as arguments.
1636 :coding CODING -- If CODING is a symbol, it specifies the coding
1637 system used for both reading and writing for this process. If CODING
1638 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1639 ENCODING is used for writing.
1641 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1642 the process is running. If BOOL is not given, query before exiting.
1644 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1645 In the stopped state, a process does not accept incoming data, but you
1646 can send outgoing data. The stopped state is cleared by
1647 `continue-process' and set by `stop-process'.
1649 :connection-type TYPE -- TYPE is control type of device used to
1650 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1651 to use a pty, or nil to use the default specified through
1652 `process-connection-type'.
1654 :filter FILTER -- Install FILTER as the process filter.
1656 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1658 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1659 to the standard error of subprocess. Specifying this implies
1660 `:connection-type' is set to `pipe'. If STDERR is nil, standard error
1661 is mixed with standard output and sent to BUFFER or FILTER.
1663 usage: (make-process &rest ARGS) */)
1664 (ptrdiff_t nargs, Lisp_Object *args)
1666 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1667 Lisp_Object xstderr, stderrproc;
1668 ptrdiff_t count = SPECPDL_INDEX ();
1670 if (nargs == 0)
1671 return Qnil;
1673 /* Save arguments for process-contact and clone-process. */
1674 contact = Flist (nargs, args);
1676 buffer = Fplist_get (contact, QCbuffer);
1677 if (!NILP (buffer))
1678 buffer = Fget_buffer_create (buffer);
1680 /* Make sure that the child will be able to chdir to the current
1681 buffer's current directory, or its unhandled equivalent. We
1682 can't just have the child check for an error when it does the
1683 chdir, since it's in a vfork. */
1684 current_dir = encode_current_directory ();
1686 name = Fplist_get (contact, QCname);
1687 CHECK_STRING (name);
1689 command = Fplist_get (contact, QCcommand);
1690 if (CONSP (command))
1691 program = XCAR (command);
1692 else
1693 program = Qnil;
1695 if (!NILP (program))
1696 CHECK_STRING (program);
1698 bool query_on_exit = NILP (Fplist_get (contact, QCnoquery));
1700 stderrproc = Qnil;
1701 xstderr = Fplist_get (contact, QCstderr);
1702 if (PROCESSP (xstderr))
1704 if (!PIPECONN_P (xstderr))
1705 error ("Process is not a pipe process");
1706 stderrproc = xstderr;
1708 else if (!NILP (xstderr))
1710 CHECK_STRING (program);
1711 stderrproc = CALLN (Fmake_pipe_process,
1712 QCname,
1713 concat2 (name, build_string (" stderr")),
1714 QCbuffer,
1715 Fget_buffer_create (xstderr),
1716 QCnoquery,
1717 query_on_exit ? Qnil : Qt);
1720 proc = make_process (name);
1721 record_unwind_protect (start_process_unwind, proc);
1723 pset_childp (XPROCESS (proc), Qt);
1724 eassert (NILP (XPROCESS (proc)->plist));
1725 pset_type (XPROCESS (proc), Qreal);
1726 pset_buffer (XPROCESS (proc), buffer);
1727 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1728 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1729 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1731 if (!query_on_exit)
1732 XPROCESS (proc)->kill_without_query = 1;
1733 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1734 pset_command (XPROCESS (proc), Qt);
1736 tem = Fplist_get (contact, QCconnection_type);
1737 if (EQ (tem, Qpty))
1738 XPROCESS (proc)->pty_flag = true;
1739 else if (EQ (tem, Qpipe))
1740 XPROCESS (proc)->pty_flag = false;
1741 else if (NILP (tem))
1742 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1743 else
1744 report_file_error ("Unknown connection type", tem);
1746 if (!NILP (stderrproc))
1748 pset_stderrproc (XPROCESS (proc), stderrproc);
1750 XPROCESS (proc)->pty_flag = false;
1753 #ifdef HAVE_GNUTLS
1754 /* AKA GNUTLS_INITSTAGE(proc). */
1755 verify (GNUTLS_STAGE_EMPTY == 0);
1756 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1757 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1758 #endif
1760 XPROCESS (proc)->adaptive_read_buffering
1761 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1762 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1764 /* Make the process marker point into the process buffer (if any). */
1765 if (BUFFERP (buffer))
1766 set_marker_both (XPROCESS (proc)->mark, buffer,
1767 BUF_ZV (XBUFFER (buffer)),
1768 BUF_ZV_BYTE (XBUFFER (buffer)));
1770 USE_SAFE_ALLOCA;
1773 /* Decide coding systems for communicating with the process. Here
1774 we don't setup the structure coding_system nor pay attention to
1775 unibyte mode. They are done in create_process. */
1777 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1778 Lisp_Object coding_systems = Qt;
1779 Lisp_Object val, *args2;
1781 tem = Fplist_get (contact, QCcoding);
1782 if (!NILP (tem))
1784 val = tem;
1785 if (CONSP (val))
1786 val = XCAR (val);
1788 else
1789 val = Vcoding_system_for_read;
1790 if (NILP (val))
1792 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1793 Lisp_Object tem2;
1794 SAFE_ALLOCA_LISP (args2, nargs2);
1795 ptrdiff_t i = 0;
1796 args2[i++] = Qstart_process;
1797 args2[i++] = name;
1798 args2[i++] = buffer;
1799 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1800 args2[i++] = XCAR (tem2);
1801 if (!NILP (program))
1802 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1803 if (CONSP (coding_systems))
1804 val = XCAR (coding_systems);
1805 else if (CONSP (Vdefault_process_coding_system))
1806 val = XCAR (Vdefault_process_coding_system);
1808 pset_decode_coding_system (XPROCESS (proc), val);
1810 if (!NILP (tem))
1812 val = tem;
1813 if (CONSP (val))
1814 val = XCDR (val);
1816 else
1817 val = Vcoding_system_for_write;
1818 if (NILP (val))
1820 if (EQ (coding_systems, Qt))
1822 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1823 Lisp_Object tem2;
1824 SAFE_ALLOCA_LISP (args2, nargs2);
1825 ptrdiff_t i = 0;
1826 args2[i++] = Qstart_process;
1827 args2[i++] = name;
1828 args2[i++] = buffer;
1829 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1830 args2[i++] = XCAR (tem2);
1831 if (!NILP (program))
1832 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1834 if (CONSP (coding_systems))
1835 val = XCDR (coding_systems);
1836 else if (CONSP (Vdefault_process_coding_system))
1837 val = XCDR (Vdefault_process_coding_system);
1839 pset_encode_coding_system (XPROCESS (proc), val);
1840 /* Note: At this moment, the above coding system may leave
1841 text-conversion or eol-conversion unspecified. They will be
1842 decided after we read output from the process and decode it by
1843 some coding system, or just before we actually send a text to
1844 the process. */
1848 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1849 eassert (XPROCESS (proc)->decoding_carryover == 0);
1850 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1852 XPROCESS (proc)->inherit_coding_system_flag
1853 = !(NILP (buffer) || !inherit_process_coding_system);
1855 if (!NILP (program))
1857 Lisp_Object program_args = XCDR (command);
1859 /* If program file name is not absolute, search our path for it.
1860 Put the name we will really use in TEM. */
1861 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1862 && !(SCHARS (program) > 1
1863 && IS_DEVICE_SEP (SREF (program, 1))))
1865 tem = Qnil;
1866 openp (Vexec_path, program, Vexec_suffixes, &tem,
1867 make_number (X_OK), false);
1868 if (NILP (tem))
1869 report_file_error ("Searching for program", program);
1870 tem = Fexpand_file_name (tem, Qnil);
1872 else
1874 if (!NILP (Ffile_directory_p (program)))
1875 error ("Specified program for new process is a directory");
1876 tem = program;
1879 /* Remove "/:" from TEM. */
1880 tem = remove_slash_colon (tem);
1882 Lisp_Object arg_encoding = Qnil;
1884 /* Encode the file name and put it in NEW_ARGV.
1885 That's where the child will use it to execute the program. */
1886 tem = list1 (ENCODE_FILE (tem));
1887 ptrdiff_t new_argc = 1;
1889 /* Here we encode arguments by the coding system used for sending
1890 data to the process. We don't support using different coding
1891 systems for encoding arguments and for encoding data sent to the
1892 process. */
1894 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1896 Lisp_Object arg = XCAR (tem2);
1897 CHECK_STRING (arg);
1898 if (STRING_MULTIBYTE (arg))
1900 if (NILP (arg_encoding))
1901 arg_encoding = (complement_process_encoding_system
1902 (XPROCESS (proc)->encode_coding_system));
1903 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1905 tem = Fcons (arg, tem);
1906 new_argc++;
1909 /* Now that everything is encoded we can collect the strings into
1910 NEW_ARGV. */
1911 char **new_argv;
1912 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1913 new_argv[new_argc] = 0;
1915 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1917 new_argv[i] = SSDATA (XCAR (tem));
1918 tem = XCDR (tem);
1921 create_process (proc, new_argv, current_dir);
1923 else
1924 create_pty (proc);
1926 SAFE_FREE ();
1927 return unbind_to (count, proc);
1930 /* If PROC doesn't have its pid set, then an error was signaled and
1931 the process wasn't started successfully, so remove it. */
1932 static void
1933 start_process_unwind (Lisp_Object proc)
1935 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1936 remove_process (proc);
1939 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1941 static void
1942 close_process_fd (int *fd_addr)
1944 int fd = *fd_addr;
1945 if (0 <= fd)
1947 *fd_addr = -1;
1948 emacs_close (fd);
1952 /* Indexes of file descriptors in open_fds. */
1953 enum
1955 /* The pipe from Emacs to its subprocess. */
1956 SUBPROCESS_STDIN,
1957 WRITE_TO_SUBPROCESS,
1959 /* The main pipe from the subprocess to Emacs. */
1960 READ_FROM_SUBPROCESS,
1961 SUBPROCESS_STDOUT,
1963 /* The pipe from the subprocess to Emacs that is closed when the
1964 subprocess execs. */
1965 READ_FROM_EXEC_MONITOR,
1966 EXEC_MONITOR_OUTPUT
1969 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1971 static void
1972 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1974 struct Lisp_Process *p = XPROCESS (process);
1975 int inchannel, outchannel;
1976 pid_t pid;
1977 int vfork_errno;
1978 int forkin, forkout, forkerr = -1;
1979 bool pty_flag = 0;
1980 char pty_name[PTY_NAME_SIZE];
1981 Lisp_Object lisp_pty_name = Qnil;
1982 sigset_t oldset;
1984 inchannel = outchannel = -1;
1986 if (p->pty_flag)
1987 outchannel = inchannel = allocate_pty (pty_name);
1989 if (inchannel >= 0)
1991 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1992 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1993 /* On most USG systems it does not work to open the pty's tty here,
1994 then close it and reopen it in the child. */
1995 /* Don't let this terminal become our controlling terminal
1996 (in case we don't have one). */
1997 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1998 if (forkin < 0)
1999 report_file_error ("Opening pty", Qnil);
2000 p->open_fd[SUBPROCESS_STDIN] = forkin;
2001 #else
2002 forkin = forkout = -1;
2003 #endif /* not USG, or USG_SUBTTY_WORKS */
2004 pty_flag = 1;
2005 lisp_pty_name = build_string (pty_name);
2007 else
2009 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2010 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2011 report_file_error ("Creating pipe", Qnil);
2012 forkin = p->open_fd[SUBPROCESS_STDIN];
2013 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2014 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2015 forkout = p->open_fd[SUBPROCESS_STDOUT];
2017 if (!NILP (p->stderrproc))
2019 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2021 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
2023 /* Close unnecessary file descriptors. */
2024 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
2025 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
2029 #ifndef WINDOWSNT
2030 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
2031 report_file_error ("Creating pipe", Qnil);
2032 #endif
2034 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2035 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2037 /* Record this as an active process, with its channels. */
2038 chan_process[inchannel] = process;
2039 p->infd = inchannel;
2040 p->outfd = outchannel;
2042 /* Previously we recorded the tty descriptor used in the subprocess.
2043 It was only used for getting the foreground tty process, so now
2044 we just reopen the device (see emacs_get_tty_pgrp) as this is
2045 more portable (see USG_SUBTTY_WORKS above). */
2047 p->pty_flag = pty_flag;
2048 pset_status (p, Qrun);
2050 if (!EQ (p->command, Qt))
2051 add_process_read_fd (inchannel);
2053 /* This may signal an error. */
2054 setup_process_coding_systems (process);
2056 block_input ();
2057 block_child_signal (&oldset);
2059 #ifndef WINDOWSNT
2060 /* vfork, and prevent local vars from being clobbered by the vfork. */
2061 Lisp_Object volatile current_dir_volatile = current_dir;
2062 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
2063 char **volatile new_argv_volatile = new_argv;
2064 int volatile forkin_volatile = forkin;
2065 int volatile forkout_volatile = forkout;
2066 int volatile forkerr_volatile = forkerr;
2067 struct Lisp_Process *p_volatile = p;
2069 #ifdef DARWIN_OS
2070 /* Darwin doesn't let us run setsid after a vfork, so use fork when
2071 necessary. Also, reset SIGCHLD handling after a vfork, as
2072 apparently macOS can mistakenly deliver SIGCHLD to the child. */
2073 if (pty_flag)
2074 pid = fork ();
2075 else
2077 pid = vfork ();
2078 if (pid == 0)
2079 signal (SIGCHLD, SIG_DFL);
2081 #else
2082 pid = vfork ();
2083 #endif
2085 current_dir = current_dir_volatile;
2086 lisp_pty_name = lisp_pty_name_volatile;
2087 new_argv = new_argv_volatile;
2088 forkin = forkin_volatile;
2089 forkout = forkout_volatile;
2090 forkerr = forkerr_volatile;
2091 p = p_volatile;
2093 pty_flag = p->pty_flag;
2095 if (pid == 0)
2096 #endif /* not WINDOWSNT */
2098 /* Make the pty be the controlling terminal of the process. */
2099 #ifdef HAVE_PTYS
2100 /* First, disconnect its current controlling terminal.
2101 Do this even if !PTY_FLAG; see Bug#30762. */
2102 setsid ();
2103 /* Make the pty's terminal the controlling terminal. */
2104 if (pty_flag && forkin >= 0)
2106 #ifdef TIOCSCTTY
2107 /* We ignore the return value
2108 because faith@cs.unc.edu says that is necessary on Linux. */
2109 ioctl (forkin, TIOCSCTTY, 0);
2110 #endif
2112 #if defined (LDISC1)
2113 if (pty_flag && forkin >= 0)
2115 struct termios t;
2116 tcgetattr (forkin, &t);
2117 t.c_lflag = LDISC1;
2118 if (tcsetattr (forkin, TCSANOW, &t) < 0)
2119 emacs_perror ("create_process/tcsetattr LDISC1");
2121 #else
2122 #if defined (NTTYDISC) && defined (TIOCSETD)
2123 if (pty_flag && forkin >= 0)
2125 /* Use new line discipline. */
2126 int ldisc = NTTYDISC;
2127 ioctl (forkin, TIOCSETD, &ldisc);
2129 #endif
2130 #endif
2131 #ifdef TIOCNOTTY
2132 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2133 can do TIOCSPGRP only to the process's controlling tty. */
2134 if (pty_flag)
2136 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2137 I can't test it since I don't have 4.3. */
2138 int j = emacs_open (DEV_TTY, O_RDWR, 0);
2139 if (j >= 0)
2141 ioctl (j, TIOCNOTTY, 0);
2142 emacs_close (j);
2145 #endif /* TIOCNOTTY */
2147 #if !defined (DONT_REOPEN_PTY)
2148 /*** There is a suggestion that this ought to be a
2149 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2150 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2151 that system does seem to need this code, even though
2152 both TIOCSCTTY is defined. */
2153 /* Now close the pty (if we had it open) and reopen it.
2154 This makes the pty the controlling terminal of the subprocess. */
2155 if (pty_flag)
2158 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2159 would work? */
2160 if (forkin >= 0)
2161 emacs_close (forkin);
2162 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2164 if (forkin < 0)
2166 emacs_perror (SSDATA (lisp_pty_name));
2167 _exit (EXIT_CANCELED);
2171 #endif /* not DONT_REOPEN_PTY */
2173 #ifdef SETUP_SLAVE_PTY
2174 if (pty_flag)
2176 SETUP_SLAVE_PTY;
2178 #endif /* SETUP_SLAVE_PTY */
2179 #endif /* HAVE_PTYS */
2181 signal (SIGINT, SIG_DFL);
2182 signal (SIGQUIT, SIG_DFL);
2183 #ifdef SIGPROF
2184 signal (SIGPROF, SIG_DFL);
2185 #endif
2187 /* Emacs ignores SIGPIPE, but the child should not. */
2188 signal (SIGPIPE, SIG_DFL);
2190 /* Stop blocking SIGCHLD in the child. */
2191 unblock_child_signal (&oldset);
2193 if (pty_flag)
2194 child_setup_tty (forkout);
2196 if (forkerr < 0)
2197 forkerr = forkout;
2198 #ifdef WINDOWSNT
2199 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2200 #else /* not WINDOWSNT */
2201 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2202 #endif /* not WINDOWSNT */
2205 /* Back in the parent process. */
2207 vfork_errno = errno;
2208 p->pid = pid;
2209 if (pid >= 0)
2210 p->alive = 1;
2212 /* Stop blocking in the parent. */
2213 unblock_child_signal (&oldset);
2214 unblock_input ();
2216 if (pid < 0)
2217 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2218 else
2220 /* vfork succeeded. */
2222 /* Close the pipe ends that the child uses, or the child's pty. */
2223 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2224 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2226 #ifdef WINDOWSNT
2227 register_child (pid, inchannel);
2228 #endif /* WINDOWSNT */
2230 pset_tty_name (p, lisp_pty_name);
2232 #ifndef WINDOWSNT
2233 /* Wait for child_setup to complete in case that vfork is
2234 actually defined as fork. The descriptor
2235 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2236 of a pipe is closed at the child side either by close-on-exec
2237 on successful execve or the _exit call in child_setup. */
2239 char dummy;
2241 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2242 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2243 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2245 #endif
2246 if (!NILP (p->stderrproc))
2248 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2249 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2254 static void
2255 create_pty (Lisp_Object process)
2257 struct Lisp_Process *p = XPROCESS (process);
2258 char pty_name[PTY_NAME_SIZE];
2259 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2261 if (pty_fd >= 0)
2263 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2264 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2265 /* On most USG systems it does not work to open the pty's tty here,
2266 then close it and reopen it in the child. */
2267 /* Don't let this terminal become our controlling terminal
2268 (in case we don't have one). */
2269 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2270 if (forkout < 0)
2271 report_file_error ("Opening pty", Qnil);
2272 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2273 #if defined (DONT_REOPEN_PTY)
2274 /* In the case that vfork is defined as fork, the parent process
2275 (Emacs) may send some data before the child process completes
2276 tty options setup. So we setup tty before forking. */
2277 child_setup_tty (forkout);
2278 #endif /* DONT_REOPEN_PTY */
2279 #endif /* not USG, or USG_SUBTTY_WORKS */
2281 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2283 /* Record this as an active process, with its channels.
2284 As a result, child_setup will close Emacs's side of the pipes. */
2285 chan_process[pty_fd] = process;
2286 p->infd = pty_fd;
2287 p->outfd = pty_fd;
2289 /* Previously we recorded the tty descriptor used in the subprocess.
2290 It was only used for getting the foreground tty process, so now
2291 we just reopen the device (see emacs_get_tty_pgrp) as this is
2292 more portable (see USG_SUBTTY_WORKS above). */
2294 p->pty_flag = 1;
2295 pset_status (p, Qrun);
2296 setup_process_coding_systems (process);
2298 add_process_read_fd (pty_fd);
2300 pset_tty_name (p, build_string (pty_name));
2303 p->pid = -2;
2306 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2307 0, MANY, 0,
2308 doc: /* Create and return a bidirectional pipe process.
2310 In Emacs, pipes are represented by process objects, so input and
2311 output work as for subprocesses, and `delete-process' closes a pipe.
2312 However, a pipe process has no process id, it cannot be signaled,
2313 and the status codes are different from normal processes.
2315 Arguments are specified as keyword/argument pairs. The following
2316 arguments are defined:
2318 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2320 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2321 with the process. Process output goes at the end of that buffer,
2322 unless you specify a filter function to handle the output. If BUFFER
2323 is not given, the value of NAME is used.
2325 :coding CODING -- If CODING is a symbol, it specifies the coding
2326 system used for both reading and writing for this process. If CODING
2327 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2328 ENCODING is used for writing.
2330 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2331 the process is running. If BOOL is not given, query before exiting.
2333 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2334 In the stopped state, a pipe process does not accept incoming data,
2335 but you can send outgoing data. The stopped state is cleared by
2336 `continue-process' and set by `stop-process'.
2338 :filter FILTER -- Install FILTER as the process filter.
2340 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2342 usage: (make-pipe-process &rest ARGS) */)
2343 (ptrdiff_t nargs, Lisp_Object *args)
2345 Lisp_Object proc, contact;
2346 struct Lisp_Process *p;
2347 Lisp_Object name, buffer;
2348 Lisp_Object tem;
2349 ptrdiff_t specpdl_count;
2350 int inchannel, outchannel;
2352 if (nargs == 0)
2353 return Qnil;
2355 contact = Flist (nargs, args);
2357 name = Fplist_get (contact, QCname);
2358 CHECK_STRING (name);
2359 proc = make_process (name);
2360 specpdl_count = SPECPDL_INDEX ();
2361 record_unwind_protect (remove_process, proc);
2362 p = XPROCESS (proc);
2364 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2365 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2366 report_file_error ("Creating pipe", Qnil);
2367 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2368 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2370 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2371 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2373 #ifdef WINDOWSNT
2374 register_aux_fd (inchannel);
2375 #endif
2377 /* Record this as an active process, with its channels. */
2378 chan_process[inchannel] = proc;
2379 p->infd = inchannel;
2380 p->outfd = outchannel;
2382 if (inchannel > max_desc)
2383 max_desc = inchannel;
2385 buffer = Fplist_get (contact, QCbuffer);
2386 if (NILP (buffer))
2387 buffer = name;
2388 buffer = Fget_buffer_create (buffer);
2389 pset_buffer (p, buffer);
2391 pset_childp (p, contact);
2392 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2393 pset_type (p, Qpipe);
2394 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2395 pset_filter (p, Fplist_get (contact, QCfilter));
2396 eassert (NILP (p->log));
2397 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2398 p->kill_without_query = 1;
2399 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2400 pset_command (p, Qt);
2401 eassert (! p->pty_flag);
2403 if (!EQ (p->command, Qt))
2404 add_process_read_fd (inchannel);
2405 p->adaptive_read_buffering
2406 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2407 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2409 /* Make the process marker point into the process buffer (if any). */
2410 if (BUFFERP (buffer))
2411 set_marker_both (p->mark, buffer,
2412 BUF_ZV (XBUFFER (buffer)),
2413 BUF_ZV_BYTE (XBUFFER (buffer)));
2416 /* Setup coding systems for communicating with the network stream. */
2418 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2419 Lisp_Object coding_systems = Qt;
2420 Lisp_Object val;
2422 tem = Fplist_get (contact, QCcoding);
2423 val = Qnil;
2424 if (!NILP (tem))
2426 val = tem;
2427 if (CONSP (val))
2428 val = XCAR (val);
2430 else if (!NILP (Vcoding_system_for_read))
2431 val = Vcoding_system_for_read;
2432 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2433 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2434 /* We dare not decode end-of-line format by setting VAL to
2435 Qraw_text, because the existing Emacs Lisp libraries
2436 assume that they receive bare code including a sequence of
2437 CR LF. */
2438 val = Qnil;
2439 else
2441 if (CONSP (coding_systems))
2442 val = XCAR (coding_systems);
2443 else if (CONSP (Vdefault_process_coding_system))
2444 val = XCAR (Vdefault_process_coding_system);
2445 else
2446 val = Qnil;
2448 pset_decode_coding_system (p, val);
2450 if (!NILP (tem))
2452 val = tem;
2453 if (CONSP (val))
2454 val = XCDR (val);
2456 else if (!NILP (Vcoding_system_for_write))
2457 val = Vcoding_system_for_write;
2458 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2459 val = Qnil;
2460 else
2462 if (CONSP (coding_systems))
2463 val = XCDR (coding_systems);
2464 else if (CONSP (Vdefault_process_coding_system))
2465 val = XCDR (Vdefault_process_coding_system);
2466 else
2467 val = Qnil;
2469 pset_encode_coding_system (p, val);
2471 /* This may signal an error. */
2472 setup_process_coding_systems (proc);
2474 pset_decoding_buf (p, empty_unibyte_string);
2475 eassert (p->decoding_carryover == 0);
2476 pset_encoding_buf (p, empty_unibyte_string);
2478 specpdl_ptr = specpdl + specpdl_count;
2480 return proc;
2484 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2485 The address family of sa is not included in the result. */
2487 Lisp_Object
2488 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2490 Lisp_Object address;
2491 ptrdiff_t i;
2492 unsigned char *cp;
2493 struct Lisp_Vector *p;
2495 /* Workaround for a bug in getsockname on BSD: Names bound to
2496 sockets in the UNIX domain are inaccessible; getsockname returns
2497 a zero length name. */
2498 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2499 return empty_unibyte_string;
2501 switch (sa->sa_family)
2503 case AF_INET:
2505 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2506 len = sizeof (sin->sin_addr) + 1;
2507 address = Fmake_vector (make_number (len), Qnil);
2508 p = XVECTOR (address);
2509 p->contents[--len] = make_number (ntohs (sin->sin_port));
2510 cp = (unsigned char *) &sin->sin_addr;
2511 break;
2513 #ifdef AF_INET6
2514 case AF_INET6:
2516 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2517 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2518 len = sizeof (sin6->sin6_addr) / 2 + 1;
2519 address = Fmake_vector (make_number (len), Qnil);
2520 p = XVECTOR (address);
2521 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2522 for (i = 0; i < len; i++)
2523 p->contents[i] = make_number (ntohs (ip6[i]));
2524 return address;
2526 #endif
2527 #ifdef HAVE_LOCAL_SOCKETS
2528 case AF_LOCAL:
2530 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2531 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2532 /* If the first byte is NUL, the name is a Linux abstract
2533 socket name, and the name can contain embedded NULs. If
2534 it's not, we have a NUL-terminated string. Be careful not
2535 to walk past the end of the object looking for the name
2536 terminator, however. */
2537 if (name_length > 0 && sockun->sun_path[0] != '\0')
2539 const char *terminator
2540 = memchr (sockun->sun_path, '\0', name_length);
2542 if (terminator)
2543 name_length = terminator - (const char *) sockun->sun_path;
2546 return make_unibyte_string (sockun->sun_path, name_length);
2548 #endif
2549 default:
2550 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2551 address = Fcons (make_number (sa->sa_family),
2552 Fmake_vector (make_number (len), Qnil));
2553 p = XVECTOR (XCDR (address));
2554 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2555 break;
2558 i = 0;
2559 while (i < len)
2560 p->contents[i++] = make_number (*cp++);
2562 return address;
2565 /* Convert an internal struct addrinfo to a Lisp object. */
2567 static Lisp_Object
2568 conv_addrinfo_to_lisp (struct addrinfo *res)
2570 Lisp_Object protocol = make_number (res->ai_protocol);
2571 eassert (XINT (protocol) == res->ai_protocol);
2572 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2576 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2578 static ptrdiff_t
2579 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2581 struct Lisp_Vector *p;
2583 if (VECTORP (address))
2585 p = XVECTOR (address);
2586 if (p->header.size == 5)
2588 *familyp = AF_INET;
2589 return sizeof (struct sockaddr_in);
2591 #ifdef AF_INET6
2592 else if (p->header.size == 9)
2594 *familyp = AF_INET6;
2595 return sizeof (struct sockaddr_in6);
2597 #endif
2599 #ifdef HAVE_LOCAL_SOCKETS
2600 else if (STRINGP (address))
2602 *familyp = AF_LOCAL;
2603 return sizeof (struct sockaddr_un);
2605 #endif
2606 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2607 && VECTORP (XCDR (address)))
2609 struct sockaddr *sa;
2610 p = XVECTOR (XCDR (address));
2611 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2612 return 0;
2613 *familyp = XINT (XCAR (address));
2614 return p->header.size + sizeof (sa->sa_family);
2616 return 0;
2619 /* Convert an address object (vector or string) to an internal sockaddr.
2621 The address format has been basically validated by
2622 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2623 it could have come from user data. So if FAMILY is not valid,
2624 we return after zeroing *SA. */
2626 static void
2627 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2629 register struct Lisp_Vector *p;
2630 register unsigned char *cp = NULL;
2631 register int i;
2632 EMACS_INT hostport;
2634 memset (sa, 0, len);
2636 if (VECTORP (address))
2638 p = XVECTOR (address);
2639 if (family == AF_INET)
2641 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2642 len = sizeof (sin->sin_addr) + 1;
2643 hostport = XINT (p->contents[--len]);
2644 sin->sin_port = htons (hostport);
2645 cp = (unsigned char *)&sin->sin_addr;
2646 sa->sa_family = family;
2648 #ifdef AF_INET6
2649 else if (family == AF_INET6)
2651 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2652 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2653 len = sizeof (sin6->sin6_addr) / 2 + 1;
2654 hostport = XINT (p->contents[--len]);
2655 sin6->sin6_port = htons (hostport);
2656 for (i = 0; i < len; i++)
2657 if (INTEGERP (p->contents[i]))
2659 int j = XFASTINT (p->contents[i]) & 0xffff;
2660 ip6[i] = ntohs (j);
2662 sa->sa_family = family;
2663 return;
2665 #endif
2666 else
2667 return;
2669 else if (STRINGP (address))
2671 #ifdef HAVE_LOCAL_SOCKETS
2672 if (family == AF_LOCAL)
2674 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2675 cp = SDATA (address);
2676 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2677 sockun->sun_path[i] = *cp++;
2678 sa->sa_family = family;
2680 #endif
2681 return;
2683 else
2685 p = XVECTOR (XCDR (address));
2686 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2689 for (i = 0; i < len; i++)
2690 if (INTEGERP (p->contents[i]))
2691 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2694 #ifdef DATAGRAM_SOCKETS
2695 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2696 1, 1, 0,
2697 doc: /* Get the current datagram address associated with PROCESS.
2698 If PROCESS is a non-blocking network process that hasn't been fully
2699 set up yet, this function will block until socket setup has completed. */)
2700 (Lisp_Object process)
2702 int channel;
2704 CHECK_PROCESS (process);
2706 if (NETCONN_P (process))
2707 wait_for_socket_fds (process, "process-datagram-address");
2709 if (!DATAGRAM_CONN_P (process))
2710 return Qnil;
2712 channel = XPROCESS (process)->infd;
2713 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2714 datagram_address[channel].len);
2717 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2718 2, 2, 0,
2719 doc: /* Set the datagram address for PROCESS to ADDRESS.
2720 Return nil upon error setting address, ADDRESS otherwise.
2722 If PROCESS is a non-blocking network process that hasn't been fully
2723 set up yet, this function will block until socket setup has completed. */)
2724 (Lisp_Object process, Lisp_Object address)
2726 int channel;
2727 int family;
2728 ptrdiff_t len;
2730 CHECK_PROCESS (process);
2732 if (NETCONN_P (process))
2733 wait_for_socket_fds (process, "set-process-datagram-address");
2735 if (!DATAGRAM_CONN_P (process))
2736 return Qnil;
2738 channel = XPROCESS (process)->infd;
2740 len = get_lisp_to_sockaddr_size (address, &family);
2741 if (len == 0 || datagram_address[channel].len != len)
2742 return Qnil;
2743 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2744 return address;
2746 #endif
2749 static const struct socket_options {
2750 /* The name of this option. Should be lowercase version of option
2751 name without SO_ prefix. */
2752 const char *name;
2753 /* Option level SOL_... */
2754 int optlevel;
2755 /* Option number SO_... */
2756 int optnum;
2757 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2758 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2759 } socket_options[] =
2761 #ifdef SO_BINDTODEVICE
2762 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2763 #endif
2764 #ifdef SO_BROADCAST
2765 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2766 #endif
2767 #ifdef SO_DONTROUTE
2768 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2769 #endif
2770 #ifdef SO_KEEPALIVE
2771 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2772 #endif
2773 #ifdef SO_LINGER
2774 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2775 #endif
2776 #ifdef SO_OOBINLINE
2777 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2778 #endif
2779 #ifdef SO_PRIORITY
2780 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2781 #endif
2782 #ifdef SO_REUSEADDR
2783 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2784 #endif
2785 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2788 /* Set option OPT to value VAL on socket S.
2790 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2791 Signals an error if setting a known option fails.
2794 static int
2795 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2797 char *name;
2798 const struct socket_options *sopt;
2799 int ret = 0;
2801 CHECK_SYMBOL (opt);
2803 name = SSDATA (SYMBOL_NAME (opt));
2804 for (sopt = socket_options; sopt->name; sopt++)
2805 if (strcmp (name, sopt->name) == 0)
2806 break;
2808 switch (sopt->opttype)
2810 case SOPT_BOOL:
2812 int optval;
2813 optval = NILP (val) ? 0 : 1;
2814 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2815 &optval, sizeof (optval));
2816 break;
2819 case SOPT_INT:
2821 int optval;
2822 if (TYPE_RANGED_INTEGERP (int, val))
2823 optval = XINT (val);
2824 else
2825 error ("Bad option value for %s", name);
2826 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2827 &optval, sizeof (optval));
2828 break;
2831 #ifdef SO_BINDTODEVICE
2832 case SOPT_IFNAME:
2834 char devname[IFNAMSIZ + 1];
2836 /* This is broken, at least in the Linux 2.4 kernel.
2837 To unbind, the arg must be a zero integer, not the empty string.
2838 This should work on all systems. KFS. 2003-09-23. */
2839 memset (devname, 0, sizeof devname);
2840 if (STRINGP (val))
2842 char *arg = SSDATA (val);
2843 int len = min (strlen (arg), IFNAMSIZ);
2844 memcpy (devname, arg, len);
2846 else if (!NILP (val))
2847 error ("Bad option value for %s", name);
2848 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2849 devname, IFNAMSIZ);
2850 break;
2852 #endif
2854 #ifdef SO_LINGER
2855 case SOPT_LINGER:
2857 struct linger linger;
2859 linger.l_onoff = 1;
2860 linger.l_linger = 0;
2861 if (TYPE_RANGED_INTEGERP (int, val))
2862 linger.l_linger = XINT (val);
2863 else
2864 linger.l_onoff = NILP (val) ? 0 : 1;
2865 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2866 &linger, sizeof (linger));
2867 break;
2869 #endif
2871 default:
2872 return 0;
2875 if (ret < 0)
2877 int setsockopt_errno = errno;
2878 report_file_errno ("Cannot set network option", list2 (opt, val),
2879 setsockopt_errno);
2882 return (1 << sopt->optbit);
2886 DEFUN ("set-network-process-option",
2887 Fset_network_process_option, Sset_network_process_option,
2888 3, 4, 0,
2889 doc: /* For network process PROCESS set option OPTION to value VALUE.
2890 See `make-network-process' for a list of options and values.
2891 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2892 OPTION is not a supported option, return nil instead; otherwise return t.
2894 If PROCESS is a non-blocking network process that hasn't been fully
2895 set up yet, this function will block until socket setup has completed. */)
2896 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2898 int s;
2899 struct Lisp_Process *p;
2901 CHECK_PROCESS (process);
2902 p = XPROCESS (process);
2903 if (!NETCONN1_P (p))
2904 error ("Process is not a network process");
2906 wait_for_socket_fds (process, "set-network-process-option");
2908 s = p->infd;
2909 if (s < 0)
2910 error ("Process is not running");
2912 if (set_socket_option (s, option, value))
2914 pset_childp (p, Fplist_put (p->childp, option, value));
2915 return Qt;
2918 if (NILP (no_error))
2919 error ("Unknown or unsupported option");
2921 return Qnil;
2925 DEFUN ("serial-process-configure",
2926 Fserial_process_configure,
2927 Sserial_process_configure,
2928 0, MANY, 0,
2929 doc: /* Configure speed, bytesize, etc. of a serial process.
2931 Arguments are specified as keyword/argument pairs. Attributes that
2932 are not given are re-initialized from the process's current
2933 configuration (available via the function `process-contact') or set to
2934 reasonable default values. The following arguments are defined:
2936 :process PROCESS
2937 :name NAME
2938 :buffer BUFFER
2939 :port PORT
2940 -- Any of these arguments can be given to identify the process that is
2941 to be configured. If none of these arguments is given, the current
2942 buffer's process is used.
2944 :speed SPEED -- SPEED is the speed of the serial port in bits per
2945 second, also called baud rate. Any value can be given for SPEED, but
2946 most serial ports work only at a few defined values between 1200 and
2947 115200, with 9600 being the most common value. If SPEED is nil, the
2948 serial port is not configured any further, i.e., all other arguments
2949 are ignored. This may be useful for special serial ports such as
2950 Bluetooth-to-serial converters which can only be configured through AT
2951 commands. A value of nil for SPEED can be used only when passed
2952 through `make-serial-process' or `serial-term'.
2954 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2955 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2957 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2958 `odd' (use odd parity), or the symbol `even' (use even parity). If
2959 PARITY is not given, no parity is used.
2961 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2962 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2963 is not given or nil, 1 stopbit is used.
2965 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2966 flowcontrol to be used, which is either nil (don't use flowcontrol),
2967 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2968 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2969 flowcontrol is used.
2971 `serial-process-configure' is called by `make-serial-process' for the
2972 initial configuration of the serial port.
2974 Examples:
2976 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2978 \(serial-process-configure
2979 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2981 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2983 usage: (serial-process-configure &rest ARGS) */)
2984 (ptrdiff_t nargs, Lisp_Object *args)
2986 struct Lisp_Process *p;
2987 Lisp_Object contact = Qnil;
2988 Lisp_Object proc = Qnil;
2990 contact = Flist (nargs, args);
2992 proc = Fplist_get (contact, QCprocess);
2993 if (NILP (proc))
2994 proc = Fplist_get (contact, QCname);
2995 if (NILP (proc))
2996 proc = Fplist_get (contact, QCbuffer);
2997 if (NILP (proc))
2998 proc = Fplist_get (contact, QCport);
2999 proc = get_process (proc);
3000 p = XPROCESS (proc);
3001 if (!EQ (p->type, Qserial))
3002 error ("Not a serial process");
3004 if (NILP (Fplist_get (p->childp, QCspeed)))
3005 return Qnil;
3007 serial_configure (p, contact);
3008 return Qnil;
3011 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
3012 0, MANY, 0,
3013 doc: /* Create and return a serial port process.
3015 In Emacs, serial port connections are represented by process objects,
3016 so input and output work as for subprocesses, and `delete-process'
3017 closes a serial port connection. However, a serial process has no
3018 process id, it cannot be signaled, and the status codes are different
3019 from normal processes.
3021 `make-serial-process' creates a process and a buffer, on which you
3022 probably want to use `process-send-string'. Try \\[serial-term] for
3023 an interactive terminal. See below for examples.
3025 Arguments are specified as keyword/argument pairs. The following
3026 arguments are defined:
3028 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3029 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
3030 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3031 the backslashes in strings).
3033 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3034 which this function calls.
3036 :name NAME -- NAME is the name of the process. If NAME is not given,
3037 the value of PORT is used.
3039 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3040 with the process. Process output goes at the end of that buffer,
3041 unless you specify a filter function to handle the output. If BUFFER
3042 is not given, the value of NAME is used.
3044 :coding CODING -- If CODING is a symbol, it specifies the coding
3045 system used for both reading and writing for this process. If CODING
3046 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3047 ENCODING is used for writing.
3049 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3050 the process is running. If BOOL is not given, query before exiting.
3052 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3053 In the stopped state, a serial process does not accept incoming data,
3054 but you can send outgoing data. The stopped state is cleared by
3055 `continue-process' and set by `stop-process'.
3057 :filter FILTER -- Install FILTER as the process filter.
3059 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3061 :plist PLIST -- Install PLIST as the initial plist of the process.
3063 :bytesize
3064 :parity
3065 :stopbits
3066 :flowcontrol
3067 -- This function calls `serial-process-configure' to handle these
3068 arguments.
3070 The original argument list, possibly modified by later configuration,
3071 is available via the function `process-contact'.
3073 Examples:
3075 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3077 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3079 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3081 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3083 usage: (make-serial-process &rest ARGS) */)
3084 (ptrdiff_t nargs, Lisp_Object *args)
3086 int fd = -1;
3087 Lisp_Object proc, contact, port;
3088 struct Lisp_Process *p;
3089 Lisp_Object name, buffer;
3090 Lisp_Object tem, val;
3091 ptrdiff_t specpdl_count;
3093 if (nargs == 0)
3094 return Qnil;
3096 contact = Flist (nargs, args);
3098 port = Fplist_get (contact, QCport);
3099 if (NILP (port))
3100 error ("No port specified");
3101 CHECK_STRING (port);
3103 if (NILP (Fplist_member (contact, QCspeed)))
3104 error (":speed not specified");
3105 if (!NILP (Fplist_get (contact, QCspeed)))
3106 CHECK_NUMBER (Fplist_get (contact, QCspeed));
3108 name = Fplist_get (contact, QCname);
3109 if (NILP (name))
3110 name = port;
3111 CHECK_STRING (name);
3112 proc = make_process (name);
3113 specpdl_count = SPECPDL_INDEX ();
3114 record_unwind_protect (remove_process, proc);
3115 p = XPROCESS (proc);
3117 fd = serial_open (port);
3118 p->open_fd[SUBPROCESS_STDIN] = fd;
3119 p->infd = fd;
3120 p->outfd = fd;
3121 if (fd > max_desc)
3122 max_desc = fd;
3123 chan_process[fd] = proc;
3125 buffer = Fplist_get (contact, QCbuffer);
3126 if (NILP (buffer))
3127 buffer = name;
3128 buffer = Fget_buffer_create (buffer);
3129 pset_buffer (p, buffer);
3131 pset_childp (p, contact);
3132 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3133 pset_type (p, Qserial);
3134 pset_sentinel (p, Fplist_get (contact, QCsentinel));
3135 pset_filter (p, Fplist_get (contact, QCfilter));
3136 eassert (NILP (p->log));
3137 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3138 p->kill_without_query = 1;
3139 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3140 pset_command (p, Qt);
3141 eassert (! p->pty_flag);
3143 if (!EQ (p->command, Qt))
3144 add_process_read_fd (fd);
3146 if (BUFFERP (buffer))
3148 set_marker_both (p->mark, buffer,
3149 BUF_ZV (XBUFFER (buffer)),
3150 BUF_ZV_BYTE (XBUFFER (buffer)));
3153 tem = Fplist_member (contact, QCcoding);
3154 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3155 tem = Qnil;
3157 val = Qnil;
3158 if (!NILP (tem))
3160 val = XCAR (XCDR (tem));
3161 if (CONSP (val))
3162 val = XCAR (val);
3164 else if (!NILP (Vcoding_system_for_read))
3165 val = Vcoding_system_for_read;
3166 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3167 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3168 val = Qnil;
3169 pset_decode_coding_system (p, val);
3171 val = Qnil;
3172 if (!NILP (tem))
3174 val = XCAR (XCDR (tem));
3175 if (CONSP (val))
3176 val = XCDR (val);
3178 else if (!NILP (Vcoding_system_for_write))
3179 val = Vcoding_system_for_write;
3180 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3181 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3182 val = Qnil;
3183 pset_encode_coding_system (p, val);
3185 setup_process_coding_systems (proc);
3186 pset_decoding_buf (p, empty_unibyte_string);
3187 eassert (p->decoding_carryover == 0);
3188 pset_encoding_buf (p, empty_unibyte_string);
3189 p->inherit_coding_system_flag
3190 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3192 Fserial_process_configure (nargs, args);
3194 specpdl_ptr = specpdl + specpdl_count;
3196 return proc;
3199 static void
3200 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
3201 Lisp_Object service, Lisp_Object name)
3203 Lisp_Object tem;
3204 struct Lisp_Process *p = XPROCESS (proc);
3205 Lisp_Object contact = p->childp;
3206 Lisp_Object coding_systems = Qt;
3207 Lisp_Object val;
3209 tem = Fplist_member (contact, QCcoding);
3210 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3211 tem = Qnil; /* No error message (too late!). */
3213 /* Setup coding systems for communicating with the network stream. */
3214 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3216 if (!NILP (tem))
3218 val = XCAR (XCDR (tem));
3219 if (CONSP (val))
3220 val = XCAR (val);
3222 else if (!NILP (Vcoding_system_for_read))
3223 val = Vcoding_system_for_read;
3224 else if ((!NILP (p->buffer)
3225 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3226 || (NILP (p->buffer)
3227 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3228 /* We dare not decode end-of-line format by setting VAL to
3229 Qraw_text, because the existing Emacs Lisp libraries
3230 assume that they receive bare code including a sequence of
3231 CR LF. */
3232 val = Qnil;
3233 else
3235 if (NILP (host) || NILP (service))
3236 coding_systems = Qnil;
3237 else
3238 coding_systems = CALLN (Ffind_operation_coding_system,
3239 Qopen_network_stream, name, p->buffer,
3240 host, service);
3241 if (CONSP (coding_systems))
3242 val = XCAR (coding_systems);
3243 else if (CONSP (Vdefault_process_coding_system))
3244 val = XCAR (Vdefault_process_coding_system);
3245 else
3246 val = Qnil;
3248 pset_decode_coding_system (p, val);
3250 if (!NILP (tem))
3252 val = XCAR (XCDR (tem));
3253 if (CONSP (val))
3254 val = XCDR (val);
3256 else if (!NILP (Vcoding_system_for_write))
3257 val = Vcoding_system_for_write;
3258 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3259 val = Qnil;
3260 else
3262 if (EQ (coding_systems, Qt))
3264 if (NILP (host) || NILP (service))
3265 coding_systems = Qnil;
3266 else
3267 coding_systems = CALLN (Ffind_operation_coding_system,
3268 Qopen_network_stream, name, p->buffer,
3269 host, service);
3271 if (CONSP (coding_systems))
3272 val = XCDR (coding_systems);
3273 else if (CONSP (Vdefault_process_coding_system))
3274 val = XCDR (Vdefault_process_coding_system);
3275 else
3276 val = Qnil;
3278 pset_encode_coding_system (p, val);
3280 pset_decoding_buf (p, empty_unibyte_string);
3281 p->decoding_carryover = 0;
3282 pset_encoding_buf (p, empty_unibyte_string);
3284 p->inherit_coding_system_flag
3285 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3288 #ifdef HAVE_GNUTLS
3289 static void
3290 finish_after_tls_connection (Lisp_Object proc)
3292 struct Lisp_Process *p = XPROCESS (proc);
3293 Lisp_Object contact = p->childp;
3294 Lisp_Object result = Qt;
3296 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3297 result = call3 (Qnsm_verify_connection,
3298 proc,
3299 Fplist_get (contact, QChost),
3300 Fplist_get (contact, QCservice));
3302 if (NILP (result))
3304 pset_status (p, list2 (Qfailed,
3305 build_string ("The Network Security Manager stopped the connections")));
3306 deactivate_process (proc);
3308 else if (p->outfd < 0)
3310 /* The counterparty may have closed the connection (especially
3311 if the NSM prompt above take a long time), so recheck the file
3312 descriptor here. */
3313 pset_status (p, Qfailed);
3314 deactivate_process (proc);
3316 else if ((fd_callback_info[p->outfd].flags & NON_BLOCKING_CONNECT_FD) == 0)
3318 /* If we cleared the connection wait mask before we did the TLS
3319 setup, then we have to say that the process is finally "open"
3320 here. */
3321 pset_status (p, Qrun);
3322 /* Execute the sentinel here. If we had relied on status_notify
3323 to do it later, it will read input from the process before
3324 calling the sentinel. */
3325 exec_sentinel (proc, build_string ("open\n"));
3328 #endif
3330 static void
3331 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3332 Lisp_Object use_external_socket_p)
3334 ptrdiff_t count = SPECPDL_INDEX ();
3335 int s = -1, outch, inch;
3336 int xerrno = 0;
3337 int family;
3338 struct sockaddr *sa = NULL;
3339 int ret;
3340 ptrdiff_t addrlen;
3341 struct Lisp_Process *p = XPROCESS (proc);
3342 Lisp_Object contact = p->childp;
3343 int optbits = 0;
3344 int socket_to_use = -1;
3346 if (!NILP (use_external_socket_p))
3348 socket_to_use = external_sock_fd;
3350 /* Ensure we don't consume the external socket twice. */
3351 external_sock_fd = -1;
3354 /* Do this in case we never enter the while-loop below. */
3355 s = -1;
3357 while (!NILP (addrinfos))
3359 Lisp_Object addrinfo = XCAR (addrinfos);
3360 addrinfos = XCDR (addrinfos);
3361 int protocol = XINT (XCAR (addrinfo));
3362 Lisp_Object ip_address = XCDR (addrinfo);
3364 #ifdef WINDOWSNT
3365 retry_connect:
3366 #endif
3368 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3369 if (sa)
3370 free (sa);
3371 sa = xmalloc (addrlen);
3372 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3374 s = socket_to_use;
3375 if (s < 0)
3377 int socktype = p->socktype | SOCK_CLOEXEC;
3378 if (p->is_non_blocking_client)
3379 socktype |= SOCK_NONBLOCK;
3380 s = socket (family, socktype, protocol);
3381 if (s < 0)
3383 xerrno = errno;
3384 continue;
3388 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3390 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3391 if (ret < 0)
3393 xerrno = errno;
3394 emacs_close (s);
3395 s = -1;
3396 if (0 <= socket_to_use)
3397 break;
3398 continue;
3402 #ifdef DATAGRAM_SOCKETS
3403 if (!p->is_server && p->socktype == SOCK_DGRAM)
3404 break;
3405 #endif /* DATAGRAM_SOCKETS */
3407 /* Make us close S if quit. */
3408 record_unwind_protect_int (close_file_unwind, s);
3410 /* Parse network options in the arg list. We simply ignore anything
3411 which isn't a known option (including other keywords). An error
3412 is signaled if setting a known option fails. */
3414 Lisp_Object params = contact, key, val;
3416 while (!NILP (params))
3418 key = XCAR (params);
3419 params = XCDR (params);
3420 val = XCAR (params);
3421 params = XCDR (params);
3422 optbits |= set_socket_option (s, key, val);
3426 if (p->is_server)
3428 /* Configure as a server socket. */
3430 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3431 explicit :reuseaddr key to override this. */
3432 #ifdef HAVE_LOCAL_SOCKETS
3433 if (family != AF_LOCAL)
3434 #endif
3435 if (!(optbits & (1 << OPIX_REUSEADDR)))
3437 int optval = 1;
3438 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3439 report_file_error ("Cannot set reuse option on server socket", Qnil);
3442 /* If passed a socket descriptor, it should be already bound. */
3443 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3444 report_file_error ("Cannot bind server socket", Qnil);
3446 #ifdef HAVE_GETSOCKNAME
3447 if (p->port == 0
3448 #ifdef HAVE_LOCAL_SOCKETS
3449 && family != AF_LOCAL
3450 #endif
3453 struct sockaddr_in sa1;
3454 socklen_t len1 = sizeof (sa1);
3455 #ifdef AF_INET6
3456 /* The code below assumes the port is at the same offset
3457 and of the same width in both IPv4 and IPv6
3458 structures, but the standards don't guarantee that,
3459 so verify it here. */
3460 struct sockaddr_in6 sa6;
3461 verify ((offsetof (struct sockaddr_in, sin_port)
3462 == offsetof (struct sockaddr_in6, sin6_port))
3463 && sizeof (sa1.sin_port) == sizeof (sa6.sin6_port));
3464 #endif
3465 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3466 if (getsockname (s, psa1, &len1) == 0)
3468 Lisp_Object service = make_number (ntohs (sa1.sin_port));
3469 contact = Fplist_put (contact, QCservice, service);
3470 /* Save the port number so that we can stash it in
3471 the process object later. */
3472 DECLARE_POINTER_ALIAS (psa, struct sockaddr_in, sa);
3473 psa->sin_port = sa1.sin_port;
3476 #endif
3478 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3479 report_file_error ("Cannot listen on server socket", Qnil);
3481 break;
3484 maybe_quit ();
3486 ret = connect (s, sa, addrlen);
3487 xerrno = errno;
3489 if (ret == 0 || xerrno == EISCONN)
3491 /* The unwind-protect will be discarded afterwards. */
3492 break;
3495 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3496 break;
3498 #ifndef WINDOWSNT
3499 if (xerrno == EINTR)
3501 /* Unlike most other syscalls connect() cannot be called
3502 again. (That would return EALREADY.) The proper way to
3503 wait for completion is pselect(). */
3504 int sc;
3505 socklen_t len;
3506 fd_set fdset;
3507 retry_select:
3508 FD_ZERO (&fdset);
3509 FD_SET (s, &fdset);
3510 maybe_quit ();
3511 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3512 if (sc == -1)
3514 if (errno == EINTR)
3515 goto retry_select;
3516 else
3517 report_file_error ("Failed select", Qnil);
3519 eassert (sc > 0);
3521 len = sizeof xerrno;
3522 eassert (FD_ISSET (s, &fdset));
3523 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3524 report_file_error ("Failed getsockopt", Qnil);
3525 if (xerrno == 0)
3526 break;
3527 if (NILP (addrinfos))
3528 report_file_errno ("Failed connect", Qnil, xerrno);
3530 #endif /* !WINDOWSNT */
3532 /* Discard the unwind protect closing S. */
3533 specpdl_ptr = specpdl + count;
3534 emacs_close (s);
3535 s = -1;
3536 if (0 <= socket_to_use)
3537 break;
3539 #ifdef WINDOWSNT
3540 if (xerrno == EINTR)
3541 goto retry_connect;
3542 #endif
3545 if (s >= 0)
3547 #ifdef DATAGRAM_SOCKETS
3548 if (p->socktype == SOCK_DGRAM)
3550 if (datagram_address[s].sa)
3551 emacs_abort ();
3553 datagram_address[s].sa = xmalloc (addrlen);
3554 datagram_address[s].len = addrlen;
3555 if (p->is_server)
3557 Lisp_Object remote;
3558 memset (datagram_address[s].sa, 0, addrlen);
3559 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3561 int rfamily;
3562 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3563 if (rlen != 0 && rfamily == family
3564 && rlen == addrlen)
3565 conv_lisp_to_sockaddr (rfamily, remote,
3566 datagram_address[s].sa, rlen);
3569 else
3570 memcpy (datagram_address[s].sa, sa, addrlen);
3572 #endif
3574 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3575 conv_sockaddr_to_lisp (sa, addrlen));
3576 #ifdef HAVE_GETSOCKNAME
3577 if (!p->is_server)
3579 struct sockaddr_storage sa1;
3580 socklen_t len1 = sizeof (sa1);
3581 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3582 if (getsockname (s, psa1, &len1) == 0)
3583 contact = Fplist_put (contact, QClocal,
3584 conv_sockaddr_to_lisp (psa1, len1));
3586 #endif
3589 if (s < 0)
3591 /* If non-blocking got this far - and failed - assume non-blocking is
3592 not supported after all. This is probably a wrong assumption, but
3593 the normal blocking calls to open-network-stream handles this error
3594 better. */
3595 if (p->is_non_blocking_client)
3596 return;
3598 report_file_errno ((p->is_server
3599 ? "make server process failed"
3600 : "make client process failed"),
3601 contact, xerrno);
3604 inch = s;
3605 outch = s;
3607 chan_process[inch] = proc;
3609 fcntl (inch, F_SETFL, O_NONBLOCK);
3611 p = XPROCESS (proc);
3612 p->open_fd[SUBPROCESS_STDIN] = inch;
3613 p->infd = inch;
3614 p->outfd = outch;
3616 /* Discard the unwind protect for closing S, if any. */
3617 specpdl_ptr = specpdl + count;
3619 if (p->is_server && p->socktype != SOCK_DGRAM)
3620 pset_status (p, Qlisten);
3622 /* Make the process marker point into the process buffer (if any). */
3623 if (BUFFERP (p->buffer))
3624 set_marker_both (p->mark, p->buffer,
3625 BUF_ZV (XBUFFER (p->buffer)),
3626 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3628 if (p->is_non_blocking_client)
3630 /* We may get here if connect did succeed immediately. However,
3631 in that case, we still need to signal this like a non-blocking
3632 connection. */
3633 if (! (connecting_status (p->status)
3634 && EQ (XCDR (p->status), addrinfos)))
3635 pset_status (p, Fcons (Qconnect, addrinfos));
3636 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3637 add_non_blocking_write_fd (inch);
3639 else
3640 /* A server may have a client filter setting of Qt, but it must
3641 still listen for incoming connects unless it is stopped. */
3642 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3643 || (EQ (p->status, Qlisten) && NILP (p->command)))
3644 add_process_read_fd (inch);
3646 if (inch > max_desc)
3647 max_desc = inch;
3649 /* Set up the masks based on the process filter. */
3650 set_process_filter_masks (p);
3652 setup_process_coding_systems (proc);
3654 #ifdef HAVE_GNUTLS
3655 /* Continue the asynchronous connection. */
3656 if (!NILP (p->gnutls_boot_parameters))
3658 Lisp_Object boot, params = p->gnutls_boot_parameters;
3660 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3661 p->gnutls_boot_parameters = Qnil;
3663 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3664 /* Run sentinels, etc. */
3665 finish_after_tls_connection (proc);
3666 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3668 deactivate_process (proc);
3669 if (NILP (boot))
3670 pset_status (p, list2 (Qfailed,
3671 build_string ("TLS negotiation failed")));
3672 else
3673 pset_status (p, list2 (Qfailed, boot));
3676 #endif
3680 /* Create a network stream/datagram client/server process. Treated
3681 exactly like a normal process when reading and writing. Primary
3682 differences are in status display and process deletion. A network
3683 connection has no PID; you cannot signal it. All you can do is
3684 stop/continue it and deactivate/close it via delete-process. */
3686 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3687 0, MANY, 0,
3688 doc: /* Create and return a network server or client process.
3690 In Emacs, network connections are represented by process objects, so
3691 input and output work as for subprocesses and `delete-process' closes
3692 a network connection. However, a network process has no process id,
3693 it cannot be signaled, and the status codes are different from normal
3694 processes.
3696 Arguments are specified as keyword/argument pairs. The following
3697 arguments are defined:
3699 :name NAME -- NAME is name for process. It is modified if necessary
3700 to make it unique.
3702 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3703 with the process. Process output goes at end of that buffer, unless
3704 you specify a filter function to handle the output. BUFFER may be
3705 also nil, meaning that this process is not associated with any buffer.
3707 :host HOST -- HOST is name of the host to connect to, or its IP
3708 address. The symbol `local' specifies the local host. If specified
3709 for a server process, it must be a valid name or address for the local
3710 host, and only clients connecting to that address will be accepted.
3712 :service SERVICE -- SERVICE is name of the service desired, or an
3713 integer specifying a port number to connect to. If SERVICE is t,
3714 a random port number is selected for the server. A port number can
3715 be specified as an integer string, e.g., "80", as well as an integer.
3717 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3718 stream type connection, `datagram' creates a datagram type connection,
3719 `seqpacket' creates a reliable datagram connection.
3721 :family FAMILY -- FAMILY is the address (and protocol) family for the
3722 service specified by HOST and SERVICE. The default (nil) is to use
3723 whatever address family (IPv4 or IPv6) that is defined for the host
3724 and port number specified by HOST and SERVICE. Other address families
3725 supported are:
3726 local -- for a local (i.e. UNIX) address specified by SERVICE.
3727 ipv4 -- use IPv4 address family only.
3728 ipv6 -- use IPv6 address family only.
3730 :local ADDRESS -- ADDRESS is the local address used for the connection.
3731 This parameter is ignored when opening a client process. When specified
3732 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3734 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3735 connection. This parameter is ignored when opening a stream server
3736 process. For a datagram server process, it specifies the initial
3737 setting of the remote datagram address. When specified for a client
3738 process, the FAMILY, HOST, and SERVICE args are ignored.
3740 The format of ADDRESS depends on the address family:
3741 - An IPv4 address is represented as a vector of integers [A B C D P]
3742 corresponding to numeric IP address A.B.C.D and port number P.
3743 - A local address is represented as a string with the address in the
3744 local address space.
3745 - An "unsupported family" address is represented by a cons (F . AV)
3746 where F is the family number and AV is a vector containing the socket
3747 address data with one element per address data byte. Do not rely on
3748 this format in portable code, as it may depend on implementation
3749 defined constants, data sizes, and data structure alignment.
3751 :coding CODING -- If CODING is a symbol, it specifies the coding
3752 system used for both reading and writing for this process. If CODING
3753 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3754 ENCODING is used for writing.
3756 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3757 process, return without waiting for the connection to complete;
3758 instead, the sentinel function will be called with second arg matching
3759 "open" (if successful) or "failed" when the connect completes.
3760 Default is to use a blocking connect (i.e. wait) for stream type
3761 connections.
3763 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3764 running when Emacs is exited.
3766 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3767 In the stopped state, a server process does not accept new
3768 connections, and a client process does not handle incoming traffic.
3769 The stopped state is cleared by `continue-process' and set by
3770 `stop-process'.
3772 :filter FILTER -- Install FILTER as the process filter.
3774 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3775 process filter are multibyte, otherwise they are unibyte.
3776 If this keyword is not specified, the strings are multibyte.
3778 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3780 :log LOG -- Install LOG as the server process log function. This
3781 function is called when the server accepts a network connection from a
3782 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3783 is the server process, CLIENT is the new process for the connection,
3784 and MESSAGE is a string.
3786 :plist PLIST -- Install PLIST as the new process's initial plist.
3788 :tls-parameters LIST -- is a list that should be supplied if you're
3789 opening a TLS connection. The first element is the TLS type (either
3790 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3791 be a keyword list accepted by gnutls-boot (as returned by
3792 `gnutls-boot-parameters').
3794 :server QLEN -- if QLEN is non-nil, create a server process for the
3795 specified FAMILY, SERVICE, and connection type (stream or datagram).
3796 If QLEN is an integer, it is used as the max. length of the server's
3797 pending connection queue (also known as the backlog); the default
3798 queue length is 5. Default is to create a client process.
3800 The following network options can be specified for this connection:
3802 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3803 :dontroute BOOL -- Only send to directly connected hosts.
3804 :keepalive BOOL -- Send keep-alive messages on network stream.
3805 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3806 :oobinline BOOL -- Place out-of-band data in receive data stream.
3807 :priority INT -- Set protocol defined priority for sent packets.
3808 :reuseaddr BOOL -- Allow reusing a recently used local address
3809 (this is allowed by default for a server process).
3810 :bindtodevice NAME -- bind to interface NAME. Using this may require
3811 special privileges on some systems.
3812 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3813 been passed to Emacs. If Emacs wasn't
3814 passed a socket, this option is silently
3815 ignored.
3818 Consult the relevant system programmer's manual pages for more
3819 information on using these options.
3822 A server process will listen for and accept connections from clients.
3823 When a client connection is accepted, a new network process is created
3824 for the connection with the following parameters:
3826 - The client's process name is constructed by concatenating the server
3827 process's NAME and a client identification string.
3828 - If the FILTER argument is non-nil, the client process will not get a
3829 separate process buffer; otherwise, the client's process buffer is a newly
3830 created buffer named after the server process's BUFFER name or process
3831 NAME concatenated with the client identification string.
3832 - The connection type and the process filter and sentinel parameters are
3833 inherited from the server process's TYPE, FILTER and SENTINEL.
3834 - The client process's contact info is set according to the client's
3835 addressing information (typically an IP address and a port number).
3836 - The client process's plist is initialized from the server's plist.
3838 Notice that the FILTER and SENTINEL args are never used directly by
3839 the server process. Also, the BUFFER argument is not used directly by
3840 the server process, but via the optional :log function, accepted (and
3841 failed) connections may be logged in the server process's buffer.
3843 The original argument list, modified with the actual connection
3844 information, is available via the `process-contact' function.
3846 usage: (make-network-process &rest ARGS) */)
3847 (ptrdiff_t nargs, Lisp_Object *args)
3849 Lisp_Object proc;
3850 Lisp_Object contact;
3851 struct Lisp_Process *p;
3852 const char *portstring UNINIT;
3853 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3854 #ifdef HAVE_LOCAL_SOCKETS
3855 struct sockaddr_un address_un;
3856 #endif
3857 EMACS_INT port = 0;
3858 Lisp_Object tem;
3859 Lisp_Object name, buffer, host, service, address;
3860 Lisp_Object filter, sentinel, use_external_socket_p;
3861 Lisp_Object addrinfos = Qnil;
3862 int socktype;
3863 int family = -1;
3864 enum { any_protocol = 0 };
3865 #ifdef HAVE_GETADDRINFO_A
3866 struct gaicb *dns_request = NULL;
3867 #endif
3868 ptrdiff_t count = SPECPDL_INDEX ();
3870 if (nargs == 0)
3871 return Qnil;
3873 /* Save arguments for process-contact and clone-process. */
3874 contact = Flist (nargs, args);
3876 #ifdef WINDOWSNT
3877 /* Ensure socket support is loaded if available. */
3878 init_winsock (TRUE);
3879 #endif
3881 /* :type TYPE (nil: stream, datagram */
3882 tem = Fplist_get (contact, QCtype);
3883 if (NILP (tem))
3884 socktype = SOCK_STREAM;
3885 #ifdef DATAGRAM_SOCKETS
3886 else if (EQ (tem, Qdatagram))
3887 socktype = SOCK_DGRAM;
3888 #endif
3889 #ifdef HAVE_SEQPACKET
3890 else if (EQ (tem, Qseqpacket))
3891 socktype = SOCK_SEQPACKET;
3892 #endif
3893 else
3894 error ("Unsupported connection type");
3896 name = Fplist_get (contact, QCname);
3897 buffer = Fplist_get (contact, QCbuffer);
3898 filter = Fplist_get (contact, QCfilter);
3899 sentinel = Fplist_get (contact, QCsentinel);
3900 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3902 CHECK_STRING (name);
3904 /* :local ADDRESS or :remote ADDRESS */
3905 tem = Fplist_get (contact, QCserver);
3906 if (NILP (tem))
3907 address = Fplist_get (contact, QCremote);
3908 else
3909 address = Fplist_get (contact, QClocal);
3910 if (!NILP (address))
3912 host = service = Qnil;
3914 if (!get_lisp_to_sockaddr_size (address, &family))
3915 error ("Malformed :address");
3917 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3918 goto open_socket;
3921 /* :family FAMILY -- nil (for Inet), local, or integer. */
3922 tem = Fplist_get (contact, QCfamily);
3923 if (NILP (tem))
3925 #ifdef AF_INET6
3926 family = AF_UNSPEC;
3927 #else
3928 family = AF_INET;
3929 #endif
3931 #ifdef HAVE_LOCAL_SOCKETS
3932 else if (EQ (tem, Qlocal))
3933 family = AF_LOCAL;
3934 #endif
3935 #ifdef AF_INET6
3936 else if (EQ (tem, Qipv6))
3937 family = AF_INET6;
3938 #endif
3939 else if (EQ (tem, Qipv4))
3940 family = AF_INET;
3941 else if (TYPE_RANGED_INTEGERP (int, tem))
3942 family = XINT (tem);
3943 else
3944 error ("Unknown address family");
3946 /* :service SERVICE -- string, integer (port number), or t (random port). */
3947 service = Fplist_get (contact, QCservice);
3949 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3950 host = Fplist_get (contact, QChost);
3951 if (NILP (host))
3953 /* The "connection" function gets it bind info from the address we're
3954 given, so use this dummy address if nothing is specified. */
3955 #ifdef HAVE_LOCAL_SOCKETS
3956 if (family != AF_LOCAL)
3957 #endif
3958 host = build_string ("127.0.0.1");
3960 else
3962 if (EQ (host, Qlocal))
3963 /* Depending on setup, "localhost" may map to different IPv4 and/or
3964 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3965 host = build_string ("127.0.0.1");
3966 CHECK_STRING (host);
3969 #ifdef HAVE_LOCAL_SOCKETS
3970 if (family == AF_LOCAL)
3972 if (!NILP (host))
3974 message (":family local ignores the :host property");
3975 contact = Fplist_put (contact, QChost, Qnil);
3976 host = Qnil;
3978 CHECK_STRING (service);
3979 if (sizeof address_un.sun_path <= SBYTES (service))
3980 error ("Service name too long");
3981 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3982 goto open_socket;
3984 #endif
3986 /* Slow down polling to every ten seconds.
3987 Some kernels have a bug which causes retrying connect to fail
3988 after a connect. Polling can interfere with gethostbyname too. */
3989 #ifdef POLL_FOR_INPUT
3990 if (socktype != SOCK_DGRAM)
3992 record_unwind_protect_void (run_all_atimers);
3993 bind_polling_period (10);
3995 #endif
3997 if (!NILP (host))
3999 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
4001 /* SERVICE can either be a string or int.
4002 Convert to a C string for later use by getaddrinfo. */
4003 if (EQ (service, Qt))
4005 portstring = "0";
4006 portstringlen = 1;
4008 else if (INTEGERP (service))
4010 portstring = portbuf;
4011 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
4013 else
4015 CHECK_STRING (service);
4016 portstring = SSDATA (service);
4017 portstringlen = SBYTES (service);
4020 #ifdef HAVE_GETADDRINFO_A
4021 if (!NILP (Fplist_get (contact, QCnowait)))
4023 ptrdiff_t hostlen = SBYTES (host);
4024 struct req
4026 struct gaicb gaicb;
4027 struct addrinfo hints;
4028 char str[FLEXIBLE_ARRAY_MEMBER];
4029 } *req = xmalloc (FLEXSIZEOF (struct req, str,
4030 hostlen + 1 + portstringlen + 1));
4031 dns_request = &req->gaicb;
4032 dns_request->ar_name = req->str;
4033 dns_request->ar_service = req->str + hostlen + 1;
4034 dns_request->ar_request = &req->hints;
4035 dns_request->ar_result = NULL;
4036 memset (&req->hints, 0, sizeof req->hints);
4037 req->hints.ai_family = family;
4038 req->hints.ai_socktype = socktype;
4039 strcpy (req->str, SSDATA (host));
4040 strcpy (req->str + hostlen + 1, portstring);
4042 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4043 if (ret)
4044 error ("%s/%s getaddrinfo_a error %d",
4045 SSDATA (host), portstring, ret);
4047 goto open_socket;
4049 #endif /* HAVE_GETADDRINFO_A */
4052 /* If we have a host, use getaddrinfo to resolve both host and service.
4053 Otherwise, use getservbyname to lookup the service. */
4055 if (!NILP (host))
4057 struct addrinfo *res, *lres;
4058 int ret;
4060 maybe_quit ();
4062 struct addrinfo hints;
4063 memset (&hints, 0, sizeof hints);
4064 hints.ai_family = family;
4065 hints.ai_socktype = socktype;
4067 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4068 if (ret)
4069 #ifdef HAVE_GAI_STRERROR
4071 synchronize_system_messages_locale ();
4072 char const *str = gai_strerror (ret);
4073 if (! NILP (Vlocale_coding_system))
4074 str = SSDATA (code_convert_string_norecord
4075 (build_string (str), Vlocale_coding_system, 0));
4076 error ("%s/%s %s", SSDATA (host), portstring, str);
4078 #else
4079 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4080 #endif
4082 for (lres = res; lres; lres = lres->ai_next)
4083 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4085 addrinfos = Fnreverse (addrinfos);
4087 freeaddrinfo (res);
4089 goto open_socket;
4092 /* No hostname has been specified (e.g., a local server process). */
4094 if (EQ (service, Qt))
4095 port = 0;
4096 else if (INTEGERP (service))
4097 port = XINT (service);
4098 else
4100 CHECK_STRING (service);
4102 port = -1;
4103 if (SBYTES (service) != 0)
4105 /* Allow the service to be a string containing the port number,
4106 because that's allowed if you have getaddrbyname. */
4107 char *service_end;
4108 long int lport = strtol (SSDATA (service), &service_end, 10);
4109 if (service_end == SSDATA (service) + SBYTES (service))
4110 port = lport;
4111 else
4113 struct servent *svc_info
4114 = getservbyname (SSDATA (service),
4115 socktype == SOCK_DGRAM ? "udp" : "tcp");
4116 if (svc_info)
4117 port = ntohs (svc_info->s_port);
4122 if (! (0 <= port && port < 1 << 16))
4124 AUTO_STRING (unknown_service, "Unknown service: %s");
4125 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4128 open_socket:
4130 if (!NILP (buffer))
4131 buffer = Fget_buffer_create (buffer);
4133 /* Unwind bind_polling_period. */
4134 unbind_to (count, Qnil);
4136 proc = make_process (name);
4137 record_unwind_protect (remove_process, proc);
4138 p = XPROCESS (proc);
4139 pset_childp (p, contact);
4140 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4141 pset_type (p, Qnetwork);
4143 pset_buffer (p, buffer);
4144 pset_sentinel (p, sentinel);
4145 pset_filter (p, filter);
4146 pset_log (p, Fplist_get (contact, QClog));
4147 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4148 p->kill_without_query = 1;
4149 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4150 pset_command (p, Qt);
4151 eassert (p->pid == 0);
4152 p->backlog = 5;
4153 eassert (! p->is_non_blocking_client);
4154 eassert (! p->is_server);
4155 p->port = port;
4156 p->socktype = socktype;
4157 #ifdef HAVE_GETADDRINFO_A
4158 eassert (! p->dns_request);
4159 #endif
4160 #ifdef HAVE_GNUTLS
4161 tem = Fplist_get (contact, QCtls_parameters);
4162 CHECK_LIST (tem);
4163 p->gnutls_boot_parameters = tem;
4164 #endif
4166 set_network_socket_coding_system (proc, host, service, name);
4168 /* :server BOOL */
4169 tem = Fplist_get (contact, QCserver);
4170 if (!NILP (tem))
4172 /* Don't support network sockets when non-blocking mode is
4173 not available, since a blocked Emacs is not useful. */
4174 p->is_server = true;
4175 if (TYPE_RANGED_INTEGERP (int, tem))
4176 p->backlog = XINT (tem);
4179 /* :nowait BOOL */
4180 if (!p->is_server && socktype != SOCK_DGRAM
4181 && !NILP (Fplist_get (contact, QCnowait)))
4182 p->is_non_blocking_client = true;
4184 bool postpone_connection = false;
4185 #ifdef HAVE_GETADDRINFO_A
4186 /* With async address resolution, the list of addresses is empty, so
4187 postpone connecting to the server. */
4188 if (!p->is_server && NILP (addrinfos))
4190 p->dns_request = dns_request;
4191 p->status = list1 (Qconnect);
4192 postpone_connection = true;
4194 #endif
4195 if (! postpone_connection)
4196 connect_network_socket (proc, addrinfos, use_external_socket_p);
4198 specpdl_ptr = specpdl + count;
4199 return proc;
4203 #ifdef HAVE_NET_IF_H
4205 #ifdef SIOCGIFCONF
4206 static Lisp_Object
4207 network_interface_list (void)
4209 struct ifconf ifconf;
4210 struct ifreq *ifreq;
4211 void *buf = NULL;
4212 ptrdiff_t buf_size = 512;
4213 int s;
4214 Lisp_Object res;
4215 ptrdiff_t count;
4217 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4218 if (s < 0)
4219 return Qnil;
4220 count = SPECPDL_INDEX ();
4221 record_unwind_protect_int (close_file_unwind, s);
4225 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4226 ifconf.ifc_buf = buf;
4227 ifconf.ifc_len = buf_size;
4228 if (ioctl (s, SIOCGIFCONF, &ifconf))
4230 emacs_close (s);
4231 xfree (buf);
4232 return Qnil;
4235 while (ifconf.ifc_len == buf_size);
4237 res = unbind_to (count, Qnil);
4238 ifreq = ifconf.ifc_req;
4239 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4241 struct ifreq *ifq = ifreq;
4242 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4243 #define SIZEOF_IFREQ(sif) \
4244 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4245 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4247 int len = SIZEOF_IFREQ (ifq);
4248 #else
4249 int len = sizeof (*ifreq);
4250 #endif
4251 char namebuf[sizeof (ifq->ifr_name) + 1];
4252 ifreq = (struct ifreq *) ((char *) ifreq + len);
4254 if (ifq->ifr_addr.sa_family != AF_INET)
4255 continue;
4257 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4258 namebuf[sizeof (ifq->ifr_name)] = 0;
4259 res = Fcons (Fcons (build_string (namebuf),
4260 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4261 sizeof (struct sockaddr))),
4262 res);
4265 xfree (buf);
4266 return res;
4268 #endif /* SIOCGIFCONF */
4270 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4272 struct ifflag_def {
4273 int flag_bit;
4274 const char *flag_sym;
4277 static const struct ifflag_def ifflag_table[] = {
4278 #ifdef IFF_UP
4279 { IFF_UP, "up" },
4280 #endif
4281 #ifdef IFF_BROADCAST
4282 { IFF_BROADCAST, "broadcast" },
4283 #endif
4284 #ifdef IFF_DEBUG
4285 { IFF_DEBUG, "debug" },
4286 #endif
4287 #ifdef IFF_LOOPBACK
4288 { IFF_LOOPBACK, "loopback" },
4289 #endif
4290 #ifdef IFF_POINTOPOINT
4291 { IFF_POINTOPOINT, "pointopoint" },
4292 #endif
4293 #ifdef IFF_RUNNING
4294 { IFF_RUNNING, "running" },
4295 #endif
4296 #ifdef IFF_NOARP
4297 { IFF_NOARP, "noarp" },
4298 #endif
4299 #ifdef IFF_PROMISC
4300 { IFF_PROMISC, "promisc" },
4301 #endif
4302 #ifdef IFF_NOTRAILERS
4303 #ifdef NS_IMPL_COCOA
4304 /* Really means smart, notrailers is obsolete. */
4305 { IFF_NOTRAILERS, "smart" },
4306 #else
4307 { IFF_NOTRAILERS, "notrailers" },
4308 #endif
4309 #endif
4310 #ifdef IFF_ALLMULTI
4311 { IFF_ALLMULTI, "allmulti" },
4312 #endif
4313 #ifdef IFF_MASTER
4314 { IFF_MASTER, "master" },
4315 #endif
4316 #ifdef IFF_SLAVE
4317 { IFF_SLAVE, "slave" },
4318 #endif
4319 #ifdef IFF_MULTICAST
4320 { IFF_MULTICAST, "multicast" },
4321 #endif
4322 #ifdef IFF_PORTSEL
4323 { IFF_PORTSEL, "portsel" },
4324 #endif
4325 #ifdef IFF_AUTOMEDIA
4326 { IFF_AUTOMEDIA, "automedia" },
4327 #endif
4328 #ifdef IFF_DYNAMIC
4329 { IFF_DYNAMIC, "dynamic" },
4330 #endif
4331 #ifdef IFF_OACTIVE
4332 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4333 #endif
4334 #ifdef IFF_SIMPLEX
4335 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4336 #endif
4337 #ifdef IFF_LINK0
4338 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4339 #endif
4340 #ifdef IFF_LINK1
4341 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4342 #endif
4343 #ifdef IFF_LINK2
4344 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4345 #endif
4346 { 0, 0 }
4349 static Lisp_Object
4350 network_interface_info (Lisp_Object ifname)
4352 struct ifreq rq;
4353 Lisp_Object res = Qnil;
4354 Lisp_Object elt;
4355 int s;
4356 bool any = 0;
4357 ptrdiff_t count;
4358 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4359 && defined HAVE_GETIFADDRS && defined LLADDR)
4360 struct ifaddrs *ifap;
4361 #endif
4363 CHECK_STRING (ifname);
4365 if (sizeof rq.ifr_name <= SBYTES (ifname))
4366 error ("interface name too long");
4367 lispstpcpy (rq.ifr_name, ifname);
4369 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4370 if (s < 0)
4371 return Qnil;
4372 count = SPECPDL_INDEX ();
4373 record_unwind_protect_int (close_file_unwind, s);
4375 elt = Qnil;
4376 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4377 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4379 int flags = rq.ifr_flags;
4380 const struct ifflag_def *fp;
4381 int fnum;
4383 /* If flags is smaller than int (i.e. short) it may have the high bit set
4384 due to IFF_MULTICAST. In that case, sign extending it into
4385 an int is wrong. */
4386 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4387 flags = (unsigned short) rq.ifr_flags;
4389 any = 1;
4390 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4392 if (flags & fp->flag_bit)
4394 elt = Fcons (intern (fp->flag_sym), elt);
4395 flags -= fp->flag_bit;
4398 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4400 if (flags & 1)
4402 elt = Fcons (make_number (fnum), elt);
4406 #endif
4407 res = Fcons (elt, res);
4409 elt = Qnil;
4410 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4411 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4413 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4414 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4415 int n;
4417 any = 1;
4418 for (n = 0; n < 6; n++)
4419 p->contents[n] = make_number (((unsigned char *)
4420 &rq.ifr_hwaddr.sa_data[0])
4421 [n]);
4422 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4424 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4425 if (getifaddrs (&ifap) != -1)
4427 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4428 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4429 struct ifaddrs *it;
4431 for (it = ifap; it != NULL; it = it->ifa_next)
4433 DECLARE_POINTER_ALIAS (sdl, struct sockaddr_dl, it->ifa_addr);
4434 unsigned char linkaddr[6];
4435 int n;
4437 if (it->ifa_addr->sa_family != AF_LINK
4438 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4439 || sdl->sdl_alen != 6)
4440 continue;
4442 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4443 for (n = 0; n < 6; n++)
4444 p->contents[n] = make_number (linkaddr[n]);
4446 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4447 break;
4450 #ifdef HAVE_FREEIFADDRS
4451 freeifaddrs (ifap);
4452 #endif
4454 #endif /* HAVE_GETIFADDRS && LLADDR */
4456 res = Fcons (elt, res);
4458 elt = Qnil;
4459 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4460 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4462 any = 1;
4463 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4464 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4465 #else
4466 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4467 #endif
4469 #endif
4470 res = Fcons (elt, res);
4472 elt = Qnil;
4473 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4474 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4476 any = 1;
4477 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4479 #endif
4480 res = Fcons (elt, res);
4482 elt = Qnil;
4483 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4484 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4486 any = 1;
4487 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4489 #endif
4490 res = Fcons (elt, res);
4492 return unbind_to (count, any ? res : Qnil);
4494 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4495 #endif /* defined (HAVE_NET_IF_H) */
4497 DEFUN ("network-interface-list", Fnetwork_interface_list,
4498 Snetwork_interface_list, 0, 0, 0,
4499 doc: /* Return an alist of all network interfaces and their network address.
4500 Each element is a cons, the car of which is a string containing the
4501 interface name, and the cdr is the network address in internal
4502 format; see the description of ADDRESS in `make-network-process'.
4504 If the information is not available, return nil. */)
4505 (void)
4507 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4508 return network_interface_list ();
4509 #else
4510 return Qnil;
4511 #endif
4514 DEFUN ("network-interface-info", Fnetwork_interface_info,
4515 Snetwork_interface_info, 1, 1, 0,
4516 doc: /* Return information about network interface named IFNAME.
4517 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4518 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4519 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4520 FLAGS is the current flags of the interface.
4522 Data that is unavailable is returned as nil. */)
4523 (Lisp_Object ifname)
4525 #if ((defined HAVE_NET_IF_H \
4526 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4527 || defined SIOCGIFFLAGS)) \
4528 || defined WINDOWSNT)
4529 return network_interface_info (ifname);
4530 #else
4531 return Qnil;
4532 #endif
4535 /* Turn off input and output for process PROC. */
4537 static void
4538 deactivate_process (Lisp_Object proc)
4540 int inchannel;
4541 struct Lisp_Process *p = XPROCESS (proc);
4542 int i;
4544 #ifdef HAVE_GNUTLS
4545 /* Delete GnuTLS structures in PROC, if any. */
4546 emacs_gnutls_deinit (proc);
4547 #endif /* HAVE_GNUTLS */
4549 if (p->read_output_delay > 0)
4551 if (--process_output_delay_count < 0)
4552 process_output_delay_count = 0;
4553 p->read_output_delay = 0;
4554 p->read_output_skip = 0;
4557 /* Beware SIGCHLD hereabouts. */
4559 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4560 close_process_fd (&p->open_fd[i]);
4562 inchannel = p->infd;
4563 if (inchannel >= 0)
4565 p->infd = -1;
4566 p->outfd = -1;
4567 #ifdef DATAGRAM_SOCKETS
4568 if (DATAGRAM_CHAN_P (inchannel))
4570 xfree (datagram_address[inchannel].sa);
4571 datagram_address[inchannel].sa = 0;
4572 datagram_address[inchannel].len = 0;
4574 #endif
4575 chan_process[inchannel] = Qnil;
4576 delete_read_fd (inchannel);
4577 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4578 delete_write_fd (inchannel);
4579 if (inchannel == max_desc)
4580 recompute_max_desc ();
4585 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4586 0, 4, 0,
4587 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4588 It is given to their filter functions.
4589 Optional argument PROCESS means do not return until output has been
4590 received from PROCESS.
4592 Optional second argument SECONDS and third argument MILLISEC
4593 specify a timeout; return after that much time even if there is
4594 no subprocess output. If SECONDS is a floating point number,
4595 it specifies a fractional number of seconds to wait.
4596 The MILLISEC argument is obsolete and should be avoided.
4598 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4599 from PROCESS only, suspending reading output from other processes.
4600 If JUST-THIS-ONE is an integer, don't run any timers either.
4601 Return non-nil if we received any output from PROCESS (or, if PROCESS
4602 is nil, from any process) before the timeout expired. */)
4603 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4604 Lisp_Object just_this_one)
4606 intmax_t secs;
4607 int nsecs;
4609 if (! NILP (process))
4611 CHECK_PROCESS (process);
4612 struct Lisp_Process *proc = XPROCESS (process);
4614 /* Can't wait for a process that is dedicated to a different
4615 thread. */
4616 if (!EQ (proc->thread, Qnil) && !EQ (proc->thread, Fcurrent_thread ()))
4618 Lisp_Object proc_thread_name = XTHREAD (proc->thread)->name;
4620 if (STRINGP (proc_thread_name))
4621 error ("Attempt to accept output from process %s locked to thread %s",
4622 SDATA (proc->name), SDATA (proc_thread_name));
4623 else
4624 error ("Attempt to accept output from process %s locked to thread %p",
4625 SDATA (proc->name), XTHREAD (proc->thread));
4628 else
4629 just_this_one = Qnil;
4631 if (!NILP (millisec))
4632 { /* Obsolete calling convention using integers rather than floats. */
4633 CHECK_NUMBER (millisec);
4634 if (NILP (seconds))
4635 seconds = make_float (XINT (millisec) / 1000.0);
4636 else
4638 CHECK_NUMBER (seconds);
4639 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4643 secs = 0;
4644 nsecs = -1;
4646 if (!NILP (seconds))
4648 if (INTEGERP (seconds))
4650 if (XINT (seconds) > 0)
4652 secs = XINT (seconds);
4653 nsecs = 0;
4656 else if (FLOATP (seconds))
4658 if (XFLOAT_DATA (seconds) > 0)
4660 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4661 secs = min (t.tv_sec, WAIT_READING_MAX);
4662 nsecs = t.tv_nsec;
4665 else
4666 wrong_type_argument (Qnumberp, seconds);
4668 else if (! NILP (process))
4669 nsecs = 0;
4671 return
4672 ((wait_reading_process_output (secs, nsecs, 0, 0,
4673 Qnil,
4674 !NILP (process) ? XPROCESS (process) : NULL,
4675 (NILP (just_this_one) ? 0
4676 : !INTEGERP (just_this_one) ? 1 : -1))
4677 <= 0)
4678 ? Qnil : Qt);
4681 /* Accept a connection for server process SERVER on CHANNEL. */
4683 static EMACS_INT connect_counter = 0;
4685 static void
4686 server_accept_connection (Lisp_Object server, int channel)
4688 Lisp_Object buffer;
4689 Lisp_Object contact, host, service;
4690 struct Lisp_Process *ps = XPROCESS (server);
4691 struct Lisp_Process *p;
4692 int s;
4693 union u_sockaddr saddr;
4694 socklen_t len = sizeof saddr;
4695 ptrdiff_t count;
4697 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4699 if (s < 0)
4701 int code = errno;
4702 if (!would_block (code) && !NILP (ps->log))
4703 call3 (ps->log, server, Qnil,
4704 concat3 (build_string ("accept failed with code"),
4705 Fnumber_to_string (make_number (code)),
4706 build_string ("\n")));
4707 return;
4710 count = SPECPDL_INDEX ();
4711 record_unwind_protect_int (close_file_unwind, s);
4713 connect_counter++;
4715 /* Setup a new process to handle the connection. */
4717 /* Generate a unique identification of the caller, and build contact
4718 information for this process. */
4719 host = Qt;
4720 service = Qnil;
4721 Lisp_Object args[11];
4722 int nargs = 0;
4723 AUTO_STRING (procname_format_in, "%s <%d.%d.%d.%d:%d>");
4724 AUTO_STRING (procname_format_in6, "%s <[%x:%x:%x:%x:%x:%x:%x:%x]:%d>");
4725 AUTO_STRING (procname_format_default, "%s <%d>");
4726 switch (saddr.sa.sa_family)
4728 case AF_INET:
4730 args[nargs++] = procname_format_in;
4731 nargs++;
4732 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4733 service = make_number (ntohs (saddr.in.sin_port));
4734 for (int i = 0; i < 4; i++)
4735 args[nargs++] = make_number (ip[i]);
4736 args[nargs++] = service;
4738 break;
4740 #ifdef AF_INET6
4741 case AF_INET6:
4743 args[nargs++] = procname_format_in6;
4744 nargs++;
4745 DECLARE_POINTER_ALIAS (ip6, uint16_t, &saddr.in6.sin6_addr);
4746 service = make_number (ntohs (saddr.in.sin_port));
4747 for (int i = 0; i < 8; i++)
4748 args[nargs++] = make_number (ip6[i]);
4749 args[nargs++] = service;
4751 break;
4752 #endif
4754 default:
4755 args[nargs++] = procname_format_default;
4756 nargs++;
4757 args[nargs++] = make_number (connect_counter);
4758 break;
4761 /* Create a new buffer name for this process if it doesn't have a
4762 filter. The new buffer name is based on the buffer name or
4763 process name of the server process concatenated with the caller
4764 identification. */
4766 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4767 || EQ (ps->filter, Qt)))
4768 buffer = Qnil;
4769 else
4771 buffer = ps->buffer;
4772 if (!NILP (buffer))
4773 buffer = Fbuffer_name (buffer);
4774 else
4775 buffer = ps->name;
4776 if (!NILP (buffer))
4778 args[1] = buffer;
4779 buffer = Fget_buffer_create (Fformat (nargs, args));
4783 /* Generate a unique name for the new server process. Combine the
4784 server process name with the caller identification. */
4786 args[1] = ps->name;
4787 Lisp_Object name = Fformat (nargs, args);
4788 Lisp_Object proc = make_process (name);
4790 chan_process[s] = proc;
4792 fcntl (s, F_SETFL, O_NONBLOCK);
4794 p = XPROCESS (proc);
4796 /* Build new contact information for this setup. */
4797 contact = Fcopy_sequence (ps->childp);
4798 contact = Fplist_put (contact, QCserver, Qnil);
4799 contact = Fplist_put (contact, QChost, host);
4800 if (!NILP (service))
4801 contact = Fplist_put (contact, QCservice, service);
4802 contact = Fplist_put (contact, QCremote,
4803 conv_sockaddr_to_lisp (&saddr.sa, len));
4804 #ifdef HAVE_GETSOCKNAME
4805 len = sizeof saddr;
4806 if (getsockname (s, &saddr.sa, &len) == 0)
4807 contact = Fplist_put (contact, QClocal,
4808 conv_sockaddr_to_lisp (&saddr.sa, len));
4809 #endif
4811 pset_childp (p, contact);
4812 pset_plist (p, Fcopy_sequence (ps->plist));
4813 pset_type (p, Qnetwork);
4815 pset_buffer (p, buffer);
4816 pset_sentinel (p, ps->sentinel);
4817 pset_filter (p, ps->filter);
4818 eassert (NILP (p->command));
4819 eassert (p->pid == 0);
4821 /* Discard the unwind protect for closing S. */
4822 specpdl_ptr = specpdl + count;
4824 p->open_fd[SUBPROCESS_STDIN] = s;
4825 p->infd = s;
4826 p->outfd = s;
4827 pset_status (p, Qrun);
4829 /* Client processes for accepted connections are not stopped initially. */
4830 if (!EQ (p->filter, Qt))
4831 add_process_read_fd (s);
4832 if (s > max_desc)
4833 max_desc = s;
4835 /* Setup coding system for new process based on server process.
4836 This seems to be the proper thing to do, as the coding system
4837 of the new process should reflect the settings at the time the
4838 server socket was opened; not the current settings. */
4840 pset_decode_coding_system (p, ps->decode_coding_system);
4841 pset_encode_coding_system (p, ps->encode_coding_system);
4842 setup_process_coding_systems (proc);
4844 pset_decoding_buf (p, empty_unibyte_string);
4845 eassert (p->decoding_carryover == 0);
4846 pset_encoding_buf (p, empty_unibyte_string);
4848 p->inherit_coding_system_flag
4849 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4851 AUTO_STRING (dash, "-");
4852 AUTO_STRING (nl, "\n");
4853 Lisp_Object host_string = STRINGP (host) ? host : dash;
4855 if (!NILP (ps->log))
4857 AUTO_STRING (accept_from, "accept from ");
4858 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4861 AUTO_STRING (open_from, "open from ");
4862 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4865 #ifdef HAVE_GETADDRINFO_A
4866 static Lisp_Object
4867 check_for_dns (Lisp_Object proc)
4869 struct Lisp_Process *p = XPROCESS (proc);
4870 Lisp_Object addrinfos = Qnil;
4872 /* Sanity check. */
4873 if (! p->dns_request)
4874 return Qnil;
4876 int ret = gai_error (p->dns_request);
4877 if (ret == EAI_INPROGRESS)
4878 return Qt;
4880 /* We got a response. */
4881 if (ret == 0)
4883 struct addrinfo *res;
4885 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4886 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4888 addrinfos = Fnreverse (addrinfos);
4890 /* The DNS lookup failed. */
4891 else if (connecting_status (p->status))
4893 deactivate_process (proc);
4894 pset_status (p, (list2
4895 (Qfailed,
4896 concat3 (build_string ("Name lookup of "),
4897 build_string (p->dns_request->ar_name),
4898 build_string (" failed")))));
4901 free_dns_request (proc);
4903 /* This process should not already be connected (or killed). */
4904 if (! connecting_status (p->status))
4905 return Qnil;
4907 return addrinfos;
4910 #endif /* HAVE_GETADDRINFO_A */
4912 static void
4913 wait_for_socket_fds (Lisp_Object process, char const *name)
4915 while (XPROCESS (process)->infd < 0
4916 && connecting_status (XPROCESS (process)->status))
4918 add_to_log ("Waiting for socket from %s...", build_string (name));
4919 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4923 static void
4924 wait_while_connecting (Lisp_Object process)
4926 while (connecting_status (XPROCESS (process)->status))
4928 add_to_log ("Waiting for connection...");
4929 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4933 static void
4934 wait_for_tls_negotiation (Lisp_Object process)
4936 #ifdef HAVE_GNUTLS
4937 while (XPROCESS (process)->gnutls_p
4938 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4940 add_to_log ("Waiting for TLS...");
4941 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4943 #endif
4946 static void
4947 wait_reading_process_output_unwind (int data)
4949 clear_waiting_thread_info ();
4950 waiting_for_user_input_p = data;
4953 /* This is here so breakpoints can be put on it. */
4954 static void
4955 wait_reading_process_output_1 (void)
4959 /* Read and dispose of subprocess output while waiting for timeout to
4960 elapse and/or keyboard input to be available.
4962 TIME_LIMIT is:
4963 timeout in seconds
4964 If negative, gobble data immediately available but don't wait for any.
4966 NSECS is:
4967 an additional duration to wait, measured in nanoseconds
4968 If TIME_LIMIT is zero, then:
4969 If NSECS == 0, there is no limit.
4970 If NSECS > 0, the timeout consists of NSECS only.
4971 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4973 READ_KBD is:
4974 0 to ignore keyboard input, or
4975 1 to return when input is available, or
4976 -1 meaning caller will actually read the input, so don't throw to
4977 the quit handler
4979 DO_DISPLAY means redisplay should be done to show subprocess
4980 output that arrives.
4982 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4983 (and gobble terminal input into the buffer if any arrives).
4985 If WAIT_PROC is specified, wait until something arrives from that
4986 process.
4988 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4989 (suspending output from other processes). A negative value
4990 means don't run any timers either.
4992 Return positive if we received input from WAIT_PROC (or from any
4993 process if WAIT_PROC is null), zero if we attempted to receive
4994 input but got none, and negative if we didn't even try. */
4997 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4998 bool do_display,
4999 Lisp_Object wait_for_cell,
5000 struct Lisp_Process *wait_proc, int just_wait_proc)
5002 int channel, nfds;
5003 fd_set Available;
5004 fd_set Writeok;
5005 bool check_write;
5006 int check_delay;
5007 bool no_avail;
5008 int xerrno;
5009 Lisp_Object proc;
5010 struct timespec timeout, end_time, timer_delay;
5011 struct timespec got_output_end_time = invalid_timespec ();
5012 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
5013 int got_some_output = -1;
5014 uintmax_t prev_wait_proc_nbytes_read = wait_proc ? wait_proc->nbytes_read : 0;
5015 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5016 bool retry_for_async;
5017 #endif
5018 ptrdiff_t count = SPECPDL_INDEX ();
5020 /* Close to the current time if known, an invalid timespec otherwise. */
5021 struct timespec now = invalid_timespec ();
5023 eassert (wait_proc == NULL
5024 || EQ (wait_proc->thread, Qnil)
5025 || XTHREAD (wait_proc->thread) == current_thread);
5027 FD_ZERO (&Available);
5028 FD_ZERO (&Writeok);
5030 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
5031 && !(CONSP (wait_proc->status)
5032 && EQ (XCAR (wait_proc->status), Qexit)))
5033 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5035 record_unwind_protect_int (wait_reading_process_output_unwind,
5036 waiting_for_user_input_p);
5037 waiting_for_user_input_p = read_kbd;
5039 if (TYPE_MAXIMUM (time_t) < time_limit)
5040 time_limit = TYPE_MAXIMUM (time_t);
5042 if (time_limit < 0 || nsecs < 0)
5043 wait = MINIMUM;
5044 else if (time_limit > 0 || nsecs > 0)
5046 wait = TIMEOUT;
5047 now = current_timespec ();
5048 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5050 else
5051 wait = INFINITY;
5053 while (1)
5055 bool process_skipped = false;
5057 /* If calling from keyboard input, do not quit
5058 since we want to return C-g as an input character.
5059 Otherwise, do pending quit if requested. */
5060 if (read_kbd >= 0)
5061 maybe_quit ();
5062 else if (pending_signals)
5063 process_pending_signals ();
5065 /* Exit now if the cell we're waiting for became non-nil. */
5066 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5067 break;
5069 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5071 Lisp_Object process_list_head, aproc;
5072 struct Lisp_Process *p;
5074 retry_for_async = false;
5075 FOR_EACH_PROCESS(process_list_head, aproc)
5077 p = XPROCESS (aproc);
5079 if (! wait_proc || p == wait_proc)
5081 #ifdef HAVE_GETADDRINFO_A
5082 /* Check for pending DNS requests. */
5083 if (p->dns_request)
5085 Lisp_Object addrinfos = check_for_dns (aproc);
5086 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5087 connect_network_socket (aproc, addrinfos, Qnil);
5088 else
5089 retry_for_async = true;
5091 #endif
5092 #ifdef HAVE_GNUTLS
5093 /* Continue TLS negotiation. */
5094 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5095 && p->is_non_blocking_client)
5097 gnutls_try_handshake (p);
5098 p->gnutls_handshakes_tried++;
5100 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5102 gnutls_verify_boot (aproc, Qnil);
5103 finish_after_tls_connection (aproc);
5105 else
5107 retry_for_async = true;
5108 if (p->gnutls_handshakes_tried
5109 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5111 deactivate_process (aproc);
5112 pset_status (p, list2 (Qfailed,
5113 build_string ("TLS negotiation failed")));
5117 #endif
5121 #endif /* GETADDRINFO_A or GNUTLS */
5123 /* Compute time from now till when time limit is up. */
5124 /* Exit if already run out. */
5125 if (wait == TIMEOUT)
5127 if (!timespec_valid_p (now))
5128 now = current_timespec ();
5129 if (timespec_cmp (end_time, now) <= 0)
5130 break;
5131 timeout = timespec_sub (end_time, now);
5133 else
5134 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5136 /* Normally we run timers here.
5137 But not if wait_for_cell; in those cases,
5138 the wait is supposed to be short,
5139 and those callers cannot handle running arbitrary Lisp code here. */
5140 if (NILP (wait_for_cell)
5141 && just_wait_proc >= 0)
5145 unsigned old_timers_run = timers_run;
5146 struct buffer *old_buffer = current_buffer;
5147 Lisp_Object old_window = selected_window;
5149 timer_delay = timer_check ();
5151 /* If a timer has run, this might have changed buffers
5152 an alike. Make read_key_sequence aware of that. */
5153 if (timers_run != old_timers_run
5154 && (old_buffer != current_buffer
5155 || !EQ (old_window, selected_window))
5156 && waiting_for_user_input_p == -1)
5157 record_asynch_buffer_change ();
5159 if (timers_run != old_timers_run && do_display)
5160 /* We must retry, since a timer may have requeued itself
5161 and that could alter the time_delay. */
5162 redisplay_preserve_echo_area (9);
5163 else
5164 break;
5166 while (!detect_input_pending ());
5168 /* If there is unread keyboard input, also return. */
5169 if (read_kbd != 0
5170 && requeued_events_pending_p ())
5171 break;
5173 /* This is so a breakpoint can be put here. */
5174 if (!timespec_valid_p (timer_delay))
5175 wait_reading_process_output_1 ();
5178 /* Cause C-g and alarm signals to take immediate action,
5179 and cause input available signals to zero out timeout.
5181 It is important that we do this before checking for process
5182 activity. If we get a SIGCHLD after the explicit checks for
5183 process activity, timeout is the only way we will know. */
5184 if (read_kbd < 0)
5185 set_waiting_for_input (&timeout);
5187 /* If status of something has changed, and no input is
5188 available, notify the user of the change right away. After
5189 this explicit check, we'll let the SIGCHLD handler zap
5190 timeout to get our attention. */
5191 if (update_tick != process_tick)
5193 fd_set Atemp;
5194 fd_set Ctemp;
5196 if (kbd_on_hold_p ())
5197 FD_ZERO (&Atemp);
5198 else
5199 compute_input_wait_mask (&Atemp);
5200 compute_write_mask (&Ctemp);
5202 timeout = make_timespec (0, 0);
5203 if ((thread_select (pselect, max_desc + 1,
5204 &Atemp,
5205 (num_pending_connects > 0 ? &Ctemp : NULL),
5206 NULL, &timeout, NULL)
5207 <= 0))
5209 /* It's okay for us to do this and then continue with
5210 the loop, since timeout has already been zeroed out. */
5211 clear_waiting_for_input ();
5212 got_some_output = status_notify (NULL, wait_proc);
5213 if (do_display) redisplay_preserve_echo_area (13);
5217 /* Don't wait for output from a non-running process. Just
5218 read whatever data has already been received. */
5219 if (wait_proc && wait_proc->raw_status_new)
5220 update_status (wait_proc);
5221 if (wait_proc
5222 && ! EQ (wait_proc->status, Qrun)
5223 && ! connecting_status (wait_proc->status))
5225 bool read_some_bytes = false;
5227 clear_waiting_for_input ();
5229 /* If data can be read from the process, do so until exhausted. */
5230 if (wait_proc->infd >= 0)
5232 XSETPROCESS (proc, wait_proc);
5234 while (true)
5236 int nread = read_process_output (proc, wait_proc->infd);
5237 if (nread < 0)
5239 if (errno == EIO || would_block (errno))
5240 break;
5242 else
5244 if (got_some_output < nread)
5245 got_some_output = nread;
5246 if (nread == 0)
5247 break;
5248 read_some_bytes = true;
5253 if (read_some_bytes && do_display)
5254 redisplay_preserve_echo_area (10);
5256 break;
5259 /* Wait till there is something to do. */
5261 if (wait_proc && just_wait_proc)
5263 if (wait_proc->infd < 0) /* Terminated. */
5264 break;
5265 FD_SET (wait_proc->infd, &Available);
5266 check_delay = 0;
5267 check_write = 0;
5269 else if (!NILP (wait_for_cell))
5271 compute_non_process_wait_mask (&Available);
5272 check_delay = 0;
5273 check_write = 0;
5275 else
5277 if (! read_kbd)
5278 compute_non_keyboard_wait_mask (&Available);
5279 else
5280 compute_input_wait_mask (&Available);
5281 compute_write_mask (&Writeok);
5282 check_delay = wait_proc ? 0 : process_output_delay_count;
5283 check_write = true;
5286 /* If frame size has changed or the window is newly mapped,
5287 redisplay now, before we start to wait. There is a race
5288 condition here; if a SIGIO arrives between now and the select
5289 and indicates that a frame is trashed, the select may block
5290 displaying a trashed screen. */
5291 if (frame_garbaged && do_display)
5293 clear_waiting_for_input ();
5294 redisplay_preserve_echo_area (11);
5295 if (read_kbd < 0)
5296 set_waiting_for_input (&timeout);
5299 /* Skip the `select' call if input is available and we're
5300 waiting for keyboard input or a cell change (which can be
5301 triggered by processing X events). In the latter case, set
5302 nfds to 1 to avoid breaking the loop. */
5303 no_avail = 0;
5304 if ((read_kbd || !NILP (wait_for_cell))
5305 && detect_input_pending ())
5307 nfds = read_kbd ? 0 : 1;
5308 no_avail = 1;
5309 FD_ZERO (&Available);
5311 else
5313 /* Set the timeout for adaptive read buffering if any
5314 process has non-zero read_output_skip and non-zero
5315 read_output_delay, and we are not reading output for a
5316 specific process. It is not executed if
5317 Vprocess_adaptive_read_buffering is nil. */
5318 if (process_output_skip && check_delay > 0)
5320 int adaptive_nsecs = timeout.tv_nsec;
5321 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5322 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5323 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5325 proc = chan_process[channel];
5326 if (NILP (proc))
5327 continue;
5328 /* Find minimum non-zero read_output_delay among the
5329 processes with non-zero read_output_skip. */
5330 if (XPROCESS (proc)->read_output_delay > 0)
5332 check_delay--;
5333 if (!XPROCESS (proc)->read_output_skip)
5334 continue;
5335 FD_CLR (channel, &Available);
5336 process_skipped = true;
5337 XPROCESS (proc)->read_output_skip = 0;
5338 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5339 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5342 timeout = make_timespec (0, adaptive_nsecs);
5343 process_output_skip = 0;
5346 /* If we've got some output and haven't limited our timeout
5347 with adaptive read buffering, limit it. */
5348 if (got_some_output > 0 && !process_skipped
5349 && (timeout.tv_sec
5350 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5351 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5354 if (NILP (wait_for_cell) && just_wait_proc >= 0
5355 && timespec_valid_p (timer_delay)
5356 && timespec_cmp (timer_delay, timeout) < 0)
5358 if (!timespec_valid_p (now))
5359 now = current_timespec ();
5360 struct timespec timeout_abs = timespec_add (now, timeout);
5361 if (!timespec_valid_p (got_output_end_time)
5362 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5363 got_output_end_time = timeout_abs;
5364 timeout = timer_delay;
5366 else
5367 got_output_end_time = invalid_timespec ();
5369 /* NOW can become inaccurate if time can pass during pselect. */
5370 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5371 now = invalid_timespec ();
5373 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5374 if (retry_for_async
5375 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5377 timeout.tv_sec = 0;
5378 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5380 #endif
5382 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5383 #if defined HAVE_GLIB && !defined HAVE_NS
5384 nfds = xg_select (max_desc + 1,
5385 &Available, (check_write ? &Writeok : 0),
5386 NULL, &timeout, NULL);
5387 #elif defined HAVE_NS
5388 /* And NS builds call thread_select in ns_select. */
5389 nfds = ns_select (max_desc + 1,
5390 &Available, (check_write ? &Writeok : 0),
5391 NULL, &timeout, NULL);
5392 #else /* !HAVE_GLIB */
5393 nfds = thread_select (pselect, max_desc + 1,
5394 &Available,
5395 (check_write ? &Writeok : 0),
5396 NULL, &timeout, NULL);
5397 #endif /* !HAVE_GLIB */
5399 #ifdef HAVE_GNUTLS
5400 /* GnuTLS buffers data internally. In lowat mode it leaves
5401 some data in the TCP buffers so that select works, but
5402 with custom pull/push functions we need to check if some
5403 data is available in the buffers manually. */
5404 if (nfds == 0)
5406 fd_set tls_available;
5407 int set = 0;
5409 FD_ZERO (&tls_available);
5410 if (! wait_proc)
5412 /* We're not waiting on a specific process, so loop
5413 through all the channels and check for data.
5414 This is a workaround needed for some versions of
5415 the gnutls library -- 2.12.14 has been confirmed
5416 to need it. See
5417 http://comments.gmane.org/gmane.emacs.devel/145074 */
5418 for (channel = 0; channel < FD_SETSIZE; ++channel)
5419 if (! NILP (chan_process[channel]))
5421 struct Lisp_Process *p =
5422 XPROCESS (chan_process[channel]);
5423 if (p && p->gnutls_p && p->gnutls_state
5424 && ((emacs_gnutls_record_check_pending
5425 (p->gnutls_state))
5426 > 0))
5428 nfds++;
5429 eassert (p->infd == channel);
5430 FD_SET (p->infd, &tls_available);
5431 set++;
5435 else
5437 /* Check this specific channel. */
5438 if (wait_proc->gnutls_p /* Check for valid process. */
5439 && wait_proc->gnutls_state
5440 /* Do we have pending data? */
5441 && ((emacs_gnutls_record_check_pending
5442 (wait_proc->gnutls_state))
5443 > 0))
5445 nfds = 1;
5446 eassert (0 <= wait_proc->infd);
5447 /* Set to Available. */
5448 FD_SET (wait_proc->infd, &tls_available);
5449 set++;
5452 if (set)
5453 Available = tls_available;
5455 #endif
5458 xerrno = errno;
5460 /* Make C-g and alarm signals set flags again. */
5461 clear_waiting_for_input ();
5463 /* If we woke up due to SIGWINCH, actually change size now. */
5464 do_pending_window_change (0);
5466 if (nfds == 0)
5468 /* Exit the main loop if we've passed the requested timeout,
5469 or have read some bytes from our wait_proc (either directly
5470 in this call or indirectly through timers / process filters),
5471 or aren't skipping processes and got some output and
5472 haven't lowered our timeout due to timers or SIGIO and
5473 have waited a long amount of time due to repeated
5474 timers. */
5475 struct timespec huge_timespec
5476 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5477 struct timespec cmp_time = huge_timespec;
5478 if (wait < TIMEOUT
5479 || (wait_proc
5480 && wait_proc->nbytes_read != prev_wait_proc_nbytes_read))
5481 break;
5482 if (wait == TIMEOUT)
5483 cmp_time = end_time;
5484 if (!process_skipped && got_some_output > 0
5485 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5487 if (!timespec_valid_p (got_output_end_time))
5488 break;
5489 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5490 cmp_time = got_output_end_time;
5492 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5494 now = current_timespec ();
5495 if (timespec_cmp (cmp_time, now) <= 0)
5496 break;
5500 if (nfds < 0)
5502 if (xerrno == EINTR)
5503 no_avail = 1;
5504 else if (xerrno == EBADF)
5505 emacs_abort ();
5506 else
5507 report_file_errno ("Failed select", Qnil, xerrno);
5510 /* Check for keyboard input. */
5511 /* If there is any, return immediately
5512 to give it higher priority than subprocesses. */
5514 if (read_kbd != 0)
5516 unsigned old_timers_run = timers_run;
5517 struct buffer *old_buffer = current_buffer;
5518 Lisp_Object old_window = selected_window;
5519 bool leave = false;
5521 if (detect_input_pending_run_timers (do_display))
5523 swallow_events (do_display);
5524 if (detect_input_pending_run_timers (do_display))
5525 leave = true;
5528 /* If a timer has run, this might have changed buffers
5529 an alike. Make read_key_sequence aware of that. */
5530 if (timers_run != old_timers_run
5531 && waiting_for_user_input_p == -1
5532 && (old_buffer != current_buffer
5533 || !EQ (old_window, selected_window)))
5534 record_asynch_buffer_change ();
5536 if (leave)
5537 break;
5540 /* If there is unread keyboard input, also return. */
5541 if (read_kbd != 0
5542 && requeued_events_pending_p ())
5543 break;
5545 /* If we are not checking for keyboard input now,
5546 do process events (but don't run any timers).
5547 This is so that X events will be processed.
5548 Otherwise they may have to wait until polling takes place.
5549 That would causes delays in pasting selections, for example.
5551 (We used to do this only if wait_for_cell.) */
5552 if (read_kbd == 0 && detect_input_pending ())
5554 swallow_events (do_display);
5555 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5556 if (detect_input_pending ())
5557 break;
5558 #endif
5561 /* Exit now if the cell we're waiting for became non-nil. */
5562 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5563 break;
5565 #ifdef USABLE_SIGIO
5566 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5567 go read it. This can happen with X on BSD after logging out.
5568 In that case, there really is no input and no SIGIO,
5569 but select says there is input. */
5571 if (read_kbd && interrupt_input
5572 && keyboard_bit_set (&Available) && ! noninteractive)
5573 handle_input_available_signal (SIGIO);
5574 #endif
5576 /* If checking input just got us a size-change event from X,
5577 obey it now if we should. */
5578 if (read_kbd || ! NILP (wait_for_cell))
5579 do_pending_window_change (0);
5581 /* Check for data from a process. */
5582 if (no_avail || nfds == 0)
5583 continue;
5585 for (channel = 0; channel <= max_desc; ++channel)
5587 struct fd_callback_data *d = &fd_callback_info[channel];
5588 if (d->func
5589 && ((d->flags & FOR_READ
5590 && FD_ISSET (channel, &Available))
5591 || ((d->flags & FOR_WRITE)
5592 && FD_ISSET (channel, &Writeok))))
5593 d->func (channel, d->data);
5596 for (channel = 0; channel <= max_desc; channel++)
5598 if (FD_ISSET (channel, &Available)
5599 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5600 == PROCESS_FD))
5602 int nread;
5604 /* If waiting for this channel, arrange to return as
5605 soon as no more input to be processed. No more
5606 waiting. */
5607 proc = chan_process[channel];
5608 if (NILP (proc))
5609 continue;
5611 /* If this is a server stream socket, accept connection. */
5612 if (EQ (XPROCESS (proc)->status, Qlisten))
5614 server_accept_connection (proc, channel);
5615 continue;
5618 /* Read data from the process, starting with our
5619 buffered-ahead character if we have one. */
5621 nread = read_process_output (proc, channel);
5622 if ((!wait_proc || wait_proc == XPROCESS (proc))
5623 && got_some_output < nread)
5624 got_some_output = nread;
5625 if (nread > 0)
5627 /* Vacuum up any leftovers without waiting. */
5628 if (wait_proc == XPROCESS (proc))
5629 wait = MINIMUM;
5630 /* Since read_process_output can run a filter,
5631 which can call accept-process-output,
5632 don't try to read from any other processes
5633 before doing the select again. */
5634 FD_ZERO (&Available);
5636 if (do_display)
5637 redisplay_preserve_echo_area (12);
5639 else if (nread == -1 && would_block (errno))
5641 #ifdef HAVE_PTYS
5642 /* On some OSs with ptys, when the process on one end of
5643 a pty exits, the other end gets an error reading with
5644 errno = EIO instead of getting an EOF (0 bytes read).
5645 Therefore, if we get an error reading and errno =
5646 EIO, just continue, because the child process has
5647 exited and should clean itself up soon (e.g. when we
5648 get a SIGCHLD). */
5649 else if (nread == -1 && errno == EIO)
5651 struct Lisp_Process *p = XPROCESS (proc);
5653 /* Clear the descriptor now, so we only raise the
5654 signal once. */
5655 delete_read_fd (channel);
5657 if (p->pid == -2)
5659 /* If the EIO occurs on a pty, the SIGCHLD handler's
5660 waitpid call will not find the process object to
5661 delete. Do it here. */
5662 p->tick = ++process_tick;
5663 pset_status (p, Qfailed);
5666 #endif /* HAVE_PTYS */
5667 /* If we can detect process termination, don't consider the
5668 process gone just because its pipe is closed. */
5669 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5670 && !PIPECONN_P (proc))
5672 else if (nread == 0 && PIPECONN_P (proc))
5674 /* Preserve status of processes already terminated. */
5675 XPROCESS (proc)->tick = ++process_tick;
5676 deactivate_process (proc);
5677 if (EQ (XPROCESS (proc)->status, Qrun))
5678 pset_status (XPROCESS (proc),
5679 list2 (Qexit, make_number (0)));
5681 else
5683 /* Preserve status of processes already terminated. */
5684 XPROCESS (proc)->tick = ++process_tick;
5685 deactivate_process (proc);
5686 if (XPROCESS (proc)->raw_status_new)
5687 update_status (XPROCESS (proc));
5688 if (EQ (XPROCESS (proc)->status, Qrun))
5689 pset_status (XPROCESS (proc),
5690 list2 (Qexit, make_number (256)));
5693 if (FD_ISSET (channel, &Writeok)
5694 && (fd_callback_info[channel].flags
5695 & NON_BLOCKING_CONNECT_FD) != 0)
5697 struct Lisp_Process *p;
5699 delete_write_fd (channel);
5701 proc = chan_process[channel];
5702 if (NILP (proc))
5703 continue;
5705 p = XPROCESS (proc);
5707 #ifndef WINDOWSNT
5709 socklen_t xlen = sizeof (xerrno);
5710 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5711 xerrno = errno;
5713 #else
5714 /* On MS-Windows, getsockopt clears the error for the
5715 entire process, which may not be the right thing; see
5716 w32.c. Use getpeername instead. */
5718 struct sockaddr pname;
5719 socklen_t pnamelen = sizeof (pname);
5721 /* If connection failed, getpeername will fail. */
5722 xerrno = 0;
5723 if (getpeername (channel, &pname, &pnamelen) < 0)
5725 /* Obtain connect failure code through error slippage. */
5726 char dummy;
5727 xerrno = errno;
5728 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5729 xerrno = errno;
5732 #endif
5733 if (xerrno)
5735 Lisp_Object addrinfos
5736 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5737 if (!NILP (addrinfos))
5738 XSETCDR (p->status, XCDR (addrinfos));
5739 else
5741 p->tick = ++process_tick;
5742 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5744 deactivate_process (proc);
5745 if (!NILP (addrinfos))
5746 connect_network_socket (proc, addrinfos, Qnil);
5748 else
5750 #ifdef HAVE_GNUTLS
5751 /* If we have an incompletely set up TLS connection,
5752 then defer the sentinel signaling until
5753 later. */
5754 if (NILP (p->gnutls_boot_parameters)
5755 && !p->gnutls_p)
5756 #endif
5758 pset_status (p, Qrun);
5759 /* Execute the sentinel here. If we had relied on
5760 status_notify to do it later, it will read input
5761 from the process before calling the sentinel. */
5762 exec_sentinel (proc, build_string ("open\n"));
5765 if (0 <= p->infd && !EQ (p->filter, Qt)
5766 && !EQ (p->command, Qt))
5767 add_process_read_fd (p->infd);
5770 } /* End for each file descriptor. */
5771 } /* End while exit conditions not met. */
5773 unbind_to (count, Qnil);
5775 /* If calling from keyboard input, do not quit
5776 since we want to return C-g as an input character.
5777 Otherwise, do pending quit if requested. */
5778 if (read_kbd >= 0)
5780 /* Prevent input_pending from remaining set if we quit. */
5781 clear_input_pending ();
5782 maybe_quit ();
5785 /* Timers and/or process filters that we have run could have themselves called
5786 `accept-process-output' (and by that indirectly this function), thus
5787 possibly reading some (or all) output of wait_proc without us noticing it.
5788 This could potentially lead to an endless wait (dealt with earlier in the
5789 function) and/or a wrong return value (dealt with here). */
5790 if (wait_proc && wait_proc->nbytes_read != prev_wait_proc_nbytes_read)
5791 got_some_output = min (INT_MAX, (wait_proc->nbytes_read
5792 - prev_wait_proc_nbytes_read));
5794 return got_some_output;
5797 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5799 static Lisp_Object
5800 read_process_output_call (Lisp_Object fun_and_args)
5802 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5805 static Lisp_Object
5806 read_process_output_error_handler (Lisp_Object error_val)
5808 cmd_error_internal (error_val, "error in process filter: ");
5809 Vinhibit_quit = Qt;
5810 update_echo_area ();
5811 Fsleep_for (make_number (2), Qnil);
5812 return Qt;
5815 static void
5816 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5817 ssize_t nbytes,
5818 struct coding_system *coding);
5820 /* Read pending output from the process channel,
5821 starting with our buffered-ahead character if we have one.
5822 Yield number of decoded characters read.
5824 This function reads at most 4096 characters.
5825 If you want to read all available subprocess output,
5826 you must call it repeatedly until it returns zero.
5828 The characters read are decoded according to PROC's coding-system
5829 for decoding. */
5831 static int
5832 read_process_output (Lisp_Object proc, int channel)
5834 ssize_t nbytes;
5835 struct Lisp_Process *p = XPROCESS (proc);
5836 struct coding_system *coding = proc_decode_coding_system[channel];
5837 int carryover = p->decoding_carryover;
5838 enum { readmax = 4096 };
5839 ptrdiff_t count = SPECPDL_INDEX ();
5840 Lisp_Object odeactivate;
5841 char chars[sizeof coding->carryover + readmax];
5843 if (carryover)
5844 /* See the comment above. */
5845 memcpy (chars, SDATA (p->decoding_buf), carryover);
5847 #ifdef DATAGRAM_SOCKETS
5848 /* We have a working select, so proc_buffered_char is always -1. */
5849 if (DATAGRAM_CHAN_P (channel))
5851 socklen_t len = datagram_address[channel].len;
5852 nbytes = recvfrom (channel, chars + carryover, readmax,
5853 0, datagram_address[channel].sa, &len);
5855 else
5856 #endif
5858 bool buffered = proc_buffered_char[channel] >= 0;
5859 if (buffered)
5861 chars[carryover] = proc_buffered_char[channel];
5862 proc_buffered_char[channel] = -1;
5864 #ifdef HAVE_GNUTLS
5865 if (p->gnutls_p && p->gnutls_state)
5866 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5867 readmax - buffered);
5868 else
5869 #endif
5870 nbytes = emacs_read (channel, chars + carryover + buffered,
5871 readmax - buffered);
5872 if (nbytes > 0 && p->adaptive_read_buffering)
5874 int delay = p->read_output_delay;
5875 if (nbytes < 256)
5877 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5879 if (delay == 0)
5880 process_output_delay_count++;
5881 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5884 else if (delay > 0 && nbytes == readmax - buffered)
5886 delay -= READ_OUTPUT_DELAY_INCREMENT;
5887 if (delay == 0)
5888 process_output_delay_count--;
5890 p->read_output_delay = delay;
5891 if (delay)
5893 p->read_output_skip = 1;
5894 process_output_skip = 1;
5897 nbytes += buffered;
5898 nbytes += buffered && nbytes <= 0;
5901 p->decoding_carryover = 0;
5903 /* At this point, NBYTES holds number of bytes just received
5904 (including the one in proc_buffered_char[channel]). */
5905 if (nbytes <= 0)
5907 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5908 return nbytes;
5909 coding->mode |= CODING_MODE_LAST_BLOCK;
5912 /* Ignore carryover, it's been added by a previous iteration already. */
5913 p->nbytes_read += nbytes;
5915 /* Now set NBYTES how many bytes we must decode. */
5916 nbytes += carryover;
5918 odeactivate = Vdeactivate_mark;
5919 /* There's no good reason to let process filters change the current
5920 buffer, and many callers of accept-process-output, sit-for, and
5921 friends don't expect current-buffer to be changed from under them. */
5922 record_unwind_current_buffer ();
5924 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5926 /* Handling the process output should not deactivate the mark. */
5927 Vdeactivate_mark = odeactivate;
5929 unbind_to (count, Qnil);
5930 return nbytes;
5933 static void
5934 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5935 ssize_t nbytes,
5936 struct coding_system *coding)
5938 Lisp_Object outstream = p->filter;
5939 Lisp_Object text;
5940 bool outer_running_asynch_code = running_asynch_code;
5941 int waiting = waiting_for_user_input_p;
5943 #if 0
5944 Lisp_Object obuffer, okeymap;
5945 XSETBUFFER (obuffer, current_buffer);
5946 okeymap = BVAR (current_buffer, keymap);
5947 #endif
5949 /* We inhibit quit here instead of just catching it so that
5950 hitting ^G when a filter happens to be running won't screw
5951 it up. */
5952 specbind (Qinhibit_quit, Qt);
5953 specbind (Qlast_nonmenu_event, Qt);
5955 /* In case we get recursively called,
5956 and we already saved the match data nonrecursively,
5957 save the same match data in safely recursive fashion. */
5958 if (outer_running_asynch_code)
5960 Lisp_Object tem;
5961 /* Don't clobber the CURRENT match data, either! */
5962 tem = Fmatch_data (Qnil, Qnil, Qnil);
5963 restore_search_regs ();
5964 record_unwind_save_match_data ();
5965 Fset_match_data (tem, Qt);
5968 /* For speed, if a search happens within this code,
5969 save the match data in a special nonrecursive fashion. */
5970 running_asynch_code = 1;
5972 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5973 text = coding->dst_object;
5974 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5975 /* A new coding system might be found. */
5976 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5978 pset_decode_coding_system (p, Vlast_coding_system_used);
5980 /* Don't call setup_coding_system for
5981 proc_decode_coding_system[channel] here. It is done in
5982 detect_coding called via decode_coding above. */
5984 /* If a coding system for encoding is not yet decided, we set
5985 it as the same as coding-system for decoding.
5987 But, before doing that we must check if
5988 proc_encode_coding_system[p->outfd] surely points to a
5989 valid memory because p->outfd will be changed once EOF is
5990 sent to the process. */
5991 if (NILP (p->encode_coding_system) && p->outfd >= 0
5992 && proc_encode_coding_system[p->outfd])
5994 pset_encode_coding_system
5995 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5996 setup_coding_system (p->encode_coding_system,
5997 proc_encode_coding_system[p->outfd]);
6001 if (coding->carryover_bytes > 0)
6003 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
6004 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
6005 memcpy (SDATA (p->decoding_buf), coding->carryover,
6006 coding->carryover_bytes);
6007 p->decoding_carryover = coding->carryover_bytes;
6009 if (SBYTES (text) > 0)
6010 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6011 sometimes it's simply wrong to wrap (e.g. when called from
6012 accept-process-output). */
6013 internal_condition_case_1 (read_process_output_call,
6014 list3 (outstream, make_lisp_proc (p), text),
6015 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6016 read_process_output_error_handler);
6018 /* If we saved the match data nonrecursively, restore it now. */
6019 restore_search_regs ();
6020 running_asynch_code = outer_running_asynch_code;
6022 /* Restore waiting_for_user_input_p as it was
6023 when we were called, in case the filter clobbered it. */
6024 waiting_for_user_input_p = waiting;
6026 #if 0 /* Call record_asynch_buffer_change unconditionally,
6027 because we might have changed minor modes or other things
6028 that affect key bindings. */
6029 if (! EQ (Fcurrent_buffer (), obuffer)
6030 || ! EQ (current_buffer->keymap, okeymap))
6031 #endif
6032 /* But do it only if the caller is actually going to read events.
6033 Otherwise there's no need to make him wake up, and it could
6034 cause trouble (for example it would make sit_for return). */
6035 if (waiting_for_user_input_p == -1)
6036 record_asynch_buffer_change ();
6039 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
6040 Sinternal_default_process_filter, 2, 2, 0,
6041 doc: /* Function used as default process filter.
6042 This inserts the process's output into its buffer, if there is one.
6043 Otherwise it discards the output. */)
6044 (Lisp_Object proc, Lisp_Object text)
6046 struct Lisp_Process *p;
6047 ptrdiff_t opoint;
6049 CHECK_PROCESS (proc);
6050 p = XPROCESS (proc);
6051 CHECK_STRING (text);
6053 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6055 Lisp_Object old_read_only;
6056 ptrdiff_t old_begv, old_zv;
6057 ptrdiff_t old_begv_byte, old_zv_byte;
6058 ptrdiff_t before, before_byte;
6059 ptrdiff_t opoint_byte;
6060 struct buffer *b;
6062 Fset_buffer (p->buffer);
6063 opoint = PT;
6064 opoint_byte = PT_BYTE;
6065 old_read_only = BVAR (current_buffer, read_only);
6066 old_begv = BEGV;
6067 old_zv = ZV;
6068 old_begv_byte = BEGV_BYTE;
6069 old_zv_byte = ZV_BYTE;
6071 bset_read_only (current_buffer, Qnil);
6073 /* Insert new output into buffer at the current end-of-output
6074 marker, thus preserving logical ordering of input and output. */
6075 if (XMARKER (p->mark)->buffer)
6076 set_point_from_marker (p->mark);
6077 else
6078 SET_PT_BOTH (ZV, ZV_BYTE);
6079 before = PT;
6080 before_byte = PT_BYTE;
6082 /* If the output marker is outside of the visible region, save
6083 the restriction and widen. */
6084 if (! (BEGV <= PT && PT <= ZV))
6085 Fwiden ();
6087 /* Adjust the multibyteness of TEXT to that of the buffer. */
6088 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6089 != ! STRING_MULTIBYTE (text))
6090 text = (STRING_MULTIBYTE (text)
6091 ? Fstring_as_unibyte (text)
6092 : Fstring_to_multibyte (text));
6093 /* Insert before markers in case we are inserting where
6094 the buffer's mark is, and the user's next command is Meta-y. */
6095 insert_from_string_before_markers (text, 0, 0,
6096 SCHARS (text), SBYTES (text), 0);
6098 /* Make sure the process marker's position is valid when the
6099 process buffer is changed in the signal_after_change above.
6100 W3 is known to do that. */
6101 if (BUFFERP (p->buffer)
6102 && (b = XBUFFER (p->buffer), b != current_buffer))
6103 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6104 else
6105 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6107 update_mode_lines = 23;
6109 /* Make sure opoint and the old restrictions
6110 float ahead of any new text just as point would. */
6111 if (opoint >= before)
6113 opoint += PT - before;
6114 opoint_byte += PT_BYTE - before_byte;
6116 if (old_begv > before)
6118 old_begv += PT - before;
6119 old_begv_byte += PT_BYTE - before_byte;
6121 if (old_zv >= before)
6123 old_zv += PT - before;
6124 old_zv_byte += PT_BYTE - before_byte;
6127 /* If the restriction isn't what it should be, set it. */
6128 if (old_begv != BEGV || old_zv != ZV)
6129 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
6131 bset_read_only (current_buffer, old_read_only);
6132 SET_PT_BOTH (opoint, opoint_byte);
6134 return Qnil;
6137 /* Sending data to subprocess. */
6139 /* In send_process, when a write fails temporarily,
6140 wait_reading_process_output is called. It may execute user code,
6141 e.g. timers, that attempts to write new data to the same process.
6142 We must ensure that data is sent in the right order, and not
6143 interspersed half-completed with other writes (Bug#10815). This is
6144 handled by the write_queue element of struct process. It is a list
6145 with each entry having the form
6147 (string . (offset . length))
6149 where STRING is a lisp string, OFFSET is the offset into the
6150 string's byte sequence from which we should begin to send, and
6151 LENGTH is the number of bytes left to send. */
6153 /* Create a new entry in write_queue.
6154 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6155 BUF is a pointer to the string sequence of the input_obj or a C
6156 string in case of Qt or Qnil. */
6158 static void
6159 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6160 const char *buf, ptrdiff_t len, bool front)
6162 ptrdiff_t offset;
6163 Lisp_Object entry, obj;
6165 if (STRINGP (input_obj))
6167 offset = buf - SSDATA (input_obj);
6168 obj = input_obj;
6170 else
6172 offset = 0;
6173 obj = make_unibyte_string (buf, len);
6176 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
6178 if (front)
6179 pset_write_queue (p, Fcons (entry, p->write_queue));
6180 else
6181 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6184 /* Remove the first element in the write_queue of process P, put its
6185 contents in OBJ, BUF and LEN, and return true. If the
6186 write_queue is empty, return false. */
6188 static bool
6189 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6190 const char **buf, ptrdiff_t *len)
6192 Lisp_Object entry, offset_length;
6193 ptrdiff_t offset;
6195 if (NILP (p->write_queue))
6196 return 0;
6198 entry = XCAR (p->write_queue);
6199 pset_write_queue (p, XCDR (p->write_queue));
6201 *obj = XCAR (entry);
6202 offset_length = XCDR (entry);
6204 *len = XINT (XCDR (offset_length));
6205 offset = XINT (XCAR (offset_length));
6206 *buf = SSDATA (*obj) + offset;
6208 return 1;
6211 /* Send some data to process PROC.
6212 BUF is the beginning of the data; LEN is the number of characters.
6213 OBJECT is the Lisp object that the data comes from. If OBJECT is
6214 nil or t, it means that the data comes from C string.
6216 If OBJECT is not nil, the data is encoded by PROC's coding-system
6217 for encoding before it is sent.
6219 This function can evaluate Lisp code and can garbage collect. */
6221 static void
6222 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6223 Lisp_Object object)
6225 struct Lisp_Process *p = XPROCESS (proc);
6226 ssize_t rv;
6227 struct coding_system *coding;
6229 if (NETCONN_P (proc))
6231 wait_while_connecting (proc);
6232 wait_for_tls_negotiation (proc);
6235 if (p->raw_status_new)
6236 update_status (p);
6237 if (! EQ (p->status, Qrun))
6238 error ("Process %s not running", SDATA (p->name));
6239 if (p->outfd < 0)
6240 error ("Output file descriptor of %s is closed", SDATA (p->name));
6242 coding = proc_encode_coding_system[p->outfd];
6243 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6245 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6246 || (BUFFERP (object)
6247 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6248 || EQ (object, Qt))
6250 pset_encode_coding_system
6251 (p, complement_process_encoding_system (p->encode_coding_system));
6252 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6254 /* The coding system for encoding was changed to raw-text
6255 because we sent a unibyte text previously. Now we are
6256 sending a multibyte text, thus we must encode it by the
6257 original coding system specified for the current process.
6259 Another reason we come here is that the coding system
6260 was just complemented and a new one was returned by
6261 complement_process_encoding_system. */
6262 setup_coding_system (p->encode_coding_system, coding);
6263 Vlast_coding_system_used = p->encode_coding_system;
6265 coding->src_multibyte = 1;
6267 else
6269 coding->src_multibyte = 0;
6270 /* For sending a unibyte text, character code conversion should
6271 not take place but EOL conversion should. So, setup raw-text
6272 or one of the subsidiary if we have not yet done it. */
6273 if (CODING_REQUIRE_ENCODING (coding))
6275 if (CODING_REQUIRE_FLUSHING (coding))
6277 /* But, before changing the coding, we must flush out data. */
6278 coding->mode |= CODING_MODE_LAST_BLOCK;
6279 send_process (proc, "", 0, Qt);
6280 coding->mode &= CODING_MODE_LAST_BLOCK;
6282 setup_coding_system (raw_text_coding_system
6283 (Vlast_coding_system_used),
6284 coding);
6285 coding->src_multibyte = 0;
6288 coding->dst_multibyte = 0;
6290 if (CODING_REQUIRE_ENCODING (coding))
6292 coding->dst_object = Qt;
6293 if (BUFFERP (object))
6295 ptrdiff_t from_byte, from, to;
6296 ptrdiff_t save_pt, save_pt_byte;
6297 struct buffer *cur = current_buffer;
6299 set_buffer_internal (XBUFFER (object));
6300 save_pt = PT, save_pt_byte = PT_BYTE;
6302 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6303 from = BYTE_TO_CHAR (from_byte);
6304 to = BYTE_TO_CHAR (from_byte + len);
6305 TEMP_SET_PT_BOTH (from, from_byte);
6306 encode_coding_object (coding, object, from, from_byte,
6307 to, from_byte + len, Qt);
6308 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6309 set_buffer_internal (cur);
6311 else if (STRINGP (object))
6313 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6314 SBYTES (object), Qt);
6316 else
6318 coding->dst_object = make_unibyte_string (buf, len);
6319 coding->produced = len;
6322 len = coding->produced;
6323 object = coding->dst_object;
6324 buf = SSDATA (object);
6327 /* If there is already data in the write_queue, put the new data
6328 in the back of queue. Otherwise, ignore it. */
6329 if (!NILP (p->write_queue))
6330 write_queue_push (p, object, buf, len, 0);
6332 do /* while !NILP (p->write_queue) */
6334 ptrdiff_t cur_len = -1;
6335 const char *cur_buf;
6336 Lisp_Object cur_object;
6338 /* If write_queue is empty, ignore it. */
6339 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6341 cur_len = len;
6342 cur_buf = buf;
6343 cur_object = object;
6346 while (cur_len > 0)
6348 /* Send this batch, using one or more write calls. */
6349 ptrdiff_t written = 0;
6350 int outfd = p->outfd;
6351 #ifdef DATAGRAM_SOCKETS
6352 if (DATAGRAM_CHAN_P (outfd))
6354 rv = sendto (outfd, cur_buf, cur_len,
6355 0, datagram_address[outfd].sa,
6356 datagram_address[outfd].len);
6357 if (rv >= 0)
6358 written = rv;
6359 else if (errno == EMSGSIZE)
6360 report_file_error ("Sending datagram", proc);
6362 else
6363 #endif
6365 #ifdef HAVE_GNUTLS
6366 if (p->gnutls_p && p->gnutls_state)
6367 written = emacs_gnutls_write (p, cur_buf, cur_len);
6368 else
6369 #endif
6370 written = emacs_write_sig (outfd, cur_buf, cur_len);
6371 rv = (written ? 0 : -1);
6372 if (p->read_output_delay > 0
6373 && p->adaptive_read_buffering == 1)
6375 p->read_output_delay = 0;
6376 process_output_delay_count--;
6377 p->read_output_skip = 0;
6381 if (rv < 0)
6383 if (would_block (errno))
6384 /* Buffer is full. Wait, accepting input;
6385 that may allow the program
6386 to finish doing output and read more. */
6388 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6389 /* A gross hack to work around a bug in FreeBSD.
6390 In the following sequence, read(2) returns
6391 bogus data:
6393 write(2) 1022 bytes
6394 write(2) 954 bytes, get EAGAIN
6395 read(2) 1024 bytes in process_read_output
6396 read(2) 11 bytes in process_read_output
6398 That is, read(2) returns more bytes than have
6399 ever been written successfully. The 1033 bytes
6400 read are the 1022 bytes written successfully
6401 after processing (for example with CRs added if
6402 the terminal is set up that way which it is
6403 here). The same bytes will be seen again in a
6404 later read(2), without the CRs. */
6406 if (errno == EAGAIN)
6408 int flags = FWRITE;
6409 ioctl (p->outfd, TIOCFLUSH, &flags);
6411 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6413 /* Put what we should have written in wait_queue. */
6414 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6415 wait_reading_process_output (0, 20 * 1000 * 1000,
6416 0, 0, Qnil, NULL, 0);
6417 /* Reread queue, to see what is left. */
6418 break;
6420 else if (errno == EPIPE)
6422 p->raw_status_new = 0;
6423 pset_status (p, list2 (Qexit, make_number (256)));
6424 p->tick = ++process_tick;
6425 deactivate_process (proc);
6426 error ("process %s no longer connected to pipe; closed it",
6427 SDATA (p->name));
6429 else
6430 /* This is a real error. */
6431 report_file_error ("Writing to process", proc);
6433 cur_buf += written;
6434 cur_len -= written;
6437 while (!NILP (p->write_queue));
6440 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6441 3, 3, 0,
6442 doc: /* Send current contents of region as input to PROCESS.
6443 PROCESS may be a process, a buffer, the name of a process or buffer, or
6444 nil, indicating the current buffer's process.
6445 Called from program, takes three arguments, PROCESS, START and END.
6446 If the region is more than 500 characters long,
6447 it is sent in several bunches. This may happen even for shorter regions.
6448 Output from processes can arrive in between bunches.
6450 If PROCESS is a non-blocking network process that hasn't been fully
6451 set up yet, this function will block until socket setup has completed. */)
6452 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6454 Lisp_Object proc = get_process (process);
6455 ptrdiff_t start_byte, end_byte;
6457 validate_region (&start, &end);
6459 start_byte = CHAR_TO_BYTE (XINT (start));
6460 end_byte = CHAR_TO_BYTE (XINT (end));
6462 if (XINT (start) < GPT && XINT (end) > GPT)
6463 move_gap_both (XINT (start), start_byte);
6465 if (NETCONN_P (proc))
6466 wait_while_connecting (proc);
6468 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6469 end_byte - start_byte, Fcurrent_buffer ());
6471 return Qnil;
6474 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6475 2, 2, 0,
6476 doc: /* Send PROCESS the contents of STRING as input.
6477 PROCESS may be a process, a buffer, the name of a process or buffer, or
6478 nil, indicating the current buffer's process.
6479 If STRING is more than 500 characters long,
6480 it is sent in several bunches. This may happen even for shorter strings.
6481 Output from processes can arrive in between bunches.
6483 If PROCESS is a non-blocking network process that hasn't been fully
6484 set up yet, this function will block until socket setup has completed. */)
6485 (Lisp_Object process, Lisp_Object string)
6487 CHECK_STRING (string);
6488 Lisp_Object proc = get_process (process);
6489 send_process (proc, SSDATA (string),
6490 SBYTES (string), string);
6491 return Qnil;
6494 /* Return the foreground process group for the tty/pty that
6495 the process P uses. */
6496 static pid_t
6497 emacs_get_tty_pgrp (struct Lisp_Process *p)
6499 pid_t gid = -1;
6501 #ifdef TIOCGPGRP
6502 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6504 int fd;
6505 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6506 master side. Try the slave side. */
6507 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6509 if (fd != -1)
6511 ioctl (fd, TIOCGPGRP, &gid);
6512 emacs_close (fd);
6515 #endif /* defined (TIOCGPGRP ) */
6517 return gid;
6520 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6521 Sprocess_running_child_p, 0, 1, 0,
6522 doc: /* Return non-nil if PROCESS has given the terminal to a
6523 child. If the operating system does not make it possible to find out,
6524 return t. If we can find out, return the numeric ID of the foreground
6525 process group. */)
6526 (Lisp_Object process)
6528 /* Initialize in case ioctl doesn't exist or gives an error,
6529 in a way that will cause returning t. */
6530 Lisp_Object proc = get_process (process);
6531 struct Lisp_Process *p = XPROCESS (proc);
6533 if (!EQ (p->type, Qreal))
6534 error ("Process %s is not a subprocess",
6535 SDATA (p->name));
6536 if (p->infd < 0)
6537 error ("Process %s is not active",
6538 SDATA (p->name));
6540 pid_t gid = emacs_get_tty_pgrp (p);
6542 if (gid == p->pid)
6543 return Qnil;
6544 if (gid != -1)
6545 return make_number (gid);
6546 return Qt;
6549 /* Send a signal number SIGNO to PROCESS.
6550 If CURRENT_GROUP is t, that means send to the process group
6551 that currently owns the terminal being used to communicate with PROCESS.
6552 This is used for various commands in shell mode.
6553 If CURRENT_GROUP is lambda, that means send to the process group
6554 that currently owns the terminal, but only if it is NOT the shell itself.
6556 If NOMSG is false, insert signal-announcements into process's buffers
6557 right away.
6559 If we can, we try to signal PROCESS by sending control characters
6560 down the pty. This allows us to signal inferiors who have changed
6561 their uid, for which kill would return an EPERM error. */
6563 static void
6564 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6565 bool nomsg)
6567 Lisp_Object proc;
6568 struct Lisp_Process *p;
6569 pid_t gid;
6570 bool no_pgrp = 0;
6572 proc = get_process (process);
6573 p = XPROCESS (proc);
6575 if (!EQ (p->type, Qreal))
6576 error ("Process %s is not a subprocess",
6577 SDATA (p->name));
6578 if (p->infd < 0)
6579 error ("Process %s is not active",
6580 SDATA (p->name));
6582 if (!p->pty_flag)
6583 current_group = Qnil;
6585 /* If we are using pgrps, get a pgrp number and make it negative. */
6586 if (NILP (current_group))
6587 /* Send the signal to the shell's process group. */
6588 gid = p->pid;
6589 else
6591 #ifdef SIGNALS_VIA_CHARACTERS
6592 /* If possible, send signals to the entire pgrp
6593 by sending an input character to it. */
6595 struct termios t;
6596 cc_t *sig_char = NULL;
6598 tcgetattr (p->infd, &t);
6600 switch (signo)
6602 case SIGINT:
6603 sig_char = &t.c_cc[VINTR];
6604 break;
6606 case SIGQUIT:
6607 sig_char = &t.c_cc[VQUIT];
6608 break;
6610 case SIGTSTP:
6611 #ifdef VSWTCH
6612 sig_char = &t.c_cc[VSWTCH];
6613 #else
6614 sig_char = &t.c_cc[VSUSP];
6615 #endif
6616 break;
6619 if (sig_char && *sig_char != CDISABLE)
6621 send_process (proc, (char *) sig_char, 1, Qnil);
6622 return;
6624 /* If we can't send the signal with a character,
6625 fall through and send it another way. */
6627 /* The code above may fall through if it can't
6628 handle the signal. */
6629 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6631 #ifdef TIOCGPGRP
6632 /* Get the current pgrp using the tty itself, if we have that.
6633 Otherwise, use the pty to get the pgrp.
6634 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6635 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6636 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6637 His patch indicates that if TIOCGPGRP returns an error, then
6638 we should just assume that p->pid is also the process group id. */
6640 gid = emacs_get_tty_pgrp (p);
6642 if (gid == -1)
6643 /* If we can't get the information, assume
6644 the shell owns the tty. */
6645 gid = p->pid;
6647 /* It is not clear whether anything really can set GID to -1.
6648 Perhaps on some system one of those ioctls can or could do so.
6649 Or perhaps this is vestigial. */
6650 if (gid == -1)
6651 no_pgrp = 1;
6652 #else /* ! defined (TIOCGPGRP) */
6653 /* Can't select pgrps on this system, so we know that
6654 the child itself heads the pgrp. */
6655 gid = p->pid;
6656 #endif /* ! defined (TIOCGPGRP) */
6658 /* If current_group is lambda, and the shell owns the terminal,
6659 don't send any signal. */
6660 if (EQ (current_group, Qlambda) && gid == p->pid)
6661 return;
6664 #ifdef SIGCONT
6665 if (signo == SIGCONT)
6667 p->raw_status_new = 0;
6668 pset_status (p, Qrun);
6669 p->tick = ++process_tick;
6670 if (!nomsg)
6672 status_notify (NULL, NULL);
6673 redisplay_preserve_echo_area (13);
6676 #endif
6678 #ifdef TIOCSIGSEND
6679 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6680 We don't know whether the bug is fixed in later HP-UX versions. */
6681 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6682 return;
6683 #endif
6685 /* If we don't have process groups, send the signal to the immediate
6686 subprocess. That isn't really right, but it's better than any
6687 obvious alternative. */
6688 pid_t pid = no_pgrp ? gid : - gid;
6690 /* Do not kill an already-reaped process, as that could kill an
6691 innocent bystander that happens to have the same process ID. */
6692 sigset_t oldset;
6693 block_child_signal (&oldset);
6694 if (p->alive)
6695 kill (pid, signo);
6696 unblock_child_signal (&oldset);
6699 DEFUN ("internal-default-interrupt-process",
6700 Finternal_default_interrupt_process,
6701 Sinternal_default_interrupt_process, 0, 2, 0,
6702 doc: /* Default function to interrupt process PROCESS.
6703 It shall be the last element in list `interrupt-process-functions'.
6704 See function `interrupt-process' for more details on usage. */)
6705 (Lisp_Object process, Lisp_Object current_group)
6707 process_send_signal (process, SIGINT, current_group, 0);
6708 return process;
6711 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6712 doc: /* Interrupt process PROCESS.
6713 PROCESS may be a process, a buffer, or the name of a process or buffer.
6714 No arg or nil means current buffer's process.
6715 Second arg CURRENT-GROUP non-nil means send signal to
6716 the current process-group of the process's controlling terminal
6717 rather than to the process's own process group.
6718 If the process is a shell, this means interrupt current subjob
6719 rather than the shell.
6721 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6722 don't send the signal.
6724 This function calls the functions of `interrupt-process-functions' in
6725 the order of the list, until one of them returns non-`nil'. */)
6726 (Lisp_Object process, Lisp_Object current_group)
6728 return CALLN (Frun_hook_with_args_until_success, Qinterrupt_process_functions,
6729 process, current_group);
6732 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6733 doc: /* Kill process PROCESS. May be process or name of one.
6734 See function `interrupt-process' for more details on usage. */)
6735 (Lisp_Object process, Lisp_Object current_group)
6737 process_send_signal (process, SIGKILL, current_group, 0);
6738 return process;
6741 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6742 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6743 See function `interrupt-process' for more details on usage. */)
6744 (Lisp_Object process, Lisp_Object current_group)
6746 process_send_signal (process, SIGQUIT, current_group, 0);
6747 return process;
6750 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6751 doc: /* Stop process PROCESS. May be process or name of one.
6752 See function `interrupt-process' for more details on usage.
6753 If PROCESS is a network or serial or pipe connection, inhibit handling
6754 of incoming traffic. */)
6755 (Lisp_Object process, Lisp_Object current_group)
6757 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6758 || PIPECONN_P (process)))
6760 struct Lisp_Process *p;
6762 p = XPROCESS (process);
6763 if (NILP (p->command)
6764 && p->infd >= 0)
6765 delete_read_fd (p->infd);
6766 pset_command (p, Qt);
6767 return process;
6769 #ifndef SIGTSTP
6770 error ("No SIGTSTP support");
6771 #else
6772 process_send_signal (process, SIGTSTP, current_group, 0);
6773 #endif
6774 return process;
6777 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6778 doc: /* Continue process PROCESS. May be process or name of one.
6779 See function `interrupt-process' for more details on usage.
6780 If PROCESS is a network or serial process, resume handling of incoming
6781 traffic. */)
6782 (Lisp_Object process, Lisp_Object current_group)
6784 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6785 || PIPECONN_P (process)))
6787 struct Lisp_Process *p;
6789 p = XPROCESS (process);
6790 if (EQ (p->command, Qt)
6791 && p->infd >= 0
6792 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6794 add_process_read_fd (p->infd);
6795 #ifdef WINDOWSNT
6796 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6797 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6798 #else /* not WINDOWSNT */
6799 tcflush (p->infd, TCIFLUSH);
6800 #endif /* not WINDOWSNT */
6802 pset_command (p, Qnil);
6803 return process;
6805 #ifdef SIGCONT
6806 process_send_signal (process, SIGCONT, current_group, 0);
6807 #else
6808 error ("No SIGCONT support");
6809 #endif
6810 return process;
6813 /* Return the integer value of the signal whose abbreviation is ABBR,
6814 or a negative number if there is no such signal. */
6815 static int
6816 abbr_to_signal (char const *name)
6818 int i, signo;
6819 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6821 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6822 name += 3;
6824 for (i = 0; i < sizeof sigbuf; i++)
6826 sigbuf[i] = c_toupper (name[i]);
6827 if (! sigbuf[i])
6828 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6831 return -1;
6834 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6835 2, 2, "sProcess (name or number): \nnSignal code: ",
6836 doc: /* Send PROCESS the signal with code SIGCODE.
6837 PROCESS may also be a number specifying the process id of the
6838 process to signal; in this case, the process need not be a child of
6839 this Emacs.
6840 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6841 (Lisp_Object process, Lisp_Object sigcode)
6843 pid_t pid;
6844 int signo;
6846 if (STRINGP (process))
6848 Lisp_Object tem = Fget_process (process);
6849 if (NILP (tem))
6850 tem = string_to_number (SSDATA (process), 10, S2N_OVERFLOW_TO_FLOAT);
6851 process = tem;
6853 else if (!NUMBERP (process))
6854 process = get_process (process);
6856 if (NILP (process))
6857 return process;
6859 if (NUMBERP (process))
6860 CONS_TO_INTEGER (process, pid_t, pid);
6861 else
6863 CHECK_PROCESS (process);
6864 pid = XPROCESS (process)->pid;
6865 if (pid <= 0)
6866 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6869 if (INTEGERP (sigcode))
6871 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6872 signo = XINT (sigcode);
6874 else
6876 char *name;
6878 CHECK_SYMBOL (sigcode);
6879 name = SSDATA (SYMBOL_NAME (sigcode));
6881 signo = abbr_to_signal (name);
6882 if (signo < 0)
6883 error ("Undefined signal name %s", name);
6886 return make_number (kill (pid, signo));
6889 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6890 doc: /* Make PROCESS see end-of-file in its input.
6891 EOF comes after any text already sent to it.
6892 PROCESS may be a process, a buffer, the name of a process or buffer, or
6893 nil, indicating the current buffer's process.
6894 If PROCESS is a network connection, or is a process communicating
6895 through a pipe (as opposed to a pty), then you cannot send any more
6896 text to PROCESS after you call this function.
6897 If PROCESS is a serial process, wait until all output written to the
6898 process has been transmitted to the serial port. */)
6899 (Lisp_Object process)
6901 Lisp_Object proc;
6902 struct coding_system *coding = NULL;
6903 int outfd;
6905 proc = get_process (process);
6907 if (NETCONN_P (proc))
6908 wait_while_connecting (proc);
6910 if (DATAGRAM_CONN_P (proc))
6911 return process;
6914 outfd = XPROCESS (proc)->outfd;
6915 if (outfd >= 0)
6916 coding = proc_encode_coding_system[outfd];
6918 /* Make sure the process is really alive. */
6919 if (XPROCESS (proc)->raw_status_new)
6920 update_status (XPROCESS (proc));
6921 if (! EQ (XPROCESS (proc)->status, Qrun))
6922 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6924 if (coding && CODING_REQUIRE_FLUSHING (coding))
6926 coding->mode |= CODING_MODE_LAST_BLOCK;
6927 send_process (proc, "", 0, Qnil);
6930 if (XPROCESS (proc)->pty_flag)
6931 send_process (proc, "\004", 1, Qnil);
6932 else if (EQ (XPROCESS (proc)->type, Qserial))
6934 #ifndef WINDOWSNT
6935 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6936 report_file_error ("Failed tcdrain", Qnil);
6937 #endif /* not WINDOWSNT */
6938 /* Do nothing on Windows because writes are blocking. */
6940 else
6942 struct Lisp_Process *p = XPROCESS (proc);
6943 int old_outfd = p->outfd;
6944 int new_outfd;
6946 #ifdef HAVE_SHUTDOWN
6947 /* If this is a network connection, or socketpair is used
6948 for communication with the subprocess, call shutdown to cause EOF.
6949 (In some old system, shutdown to socketpair doesn't work.
6950 Then we just can't win.) */
6951 if (0 <= old_outfd
6952 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6953 shutdown (old_outfd, 1);
6954 #endif
6955 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6956 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6957 if (new_outfd < 0)
6958 report_file_error ("Opening null device", Qnil);
6959 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6960 p->outfd = new_outfd;
6962 if (!proc_encode_coding_system[new_outfd])
6963 proc_encode_coding_system[new_outfd]
6964 = xmalloc (sizeof (struct coding_system));
6965 if (old_outfd >= 0)
6967 *proc_encode_coding_system[new_outfd]
6968 = *proc_encode_coding_system[old_outfd];
6969 memset (proc_encode_coding_system[old_outfd], 0,
6970 sizeof (struct coding_system));
6972 else
6973 setup_coding_system (p->encode_coding_system,
6974 proc_encode_coding_system[new_outfd]);
6976 return process;
6979 /* The main Emacs thread records child processes in three places:
6981 - Vprocess_alist, for asynchronous subprocesses, which are child
6982 processes visible to Lisp.
6984 - deleted_pid_list, for child processes invisible to Lisp,
6985 typically because of delete-process. These are recorded so that
6986 the processes can be reaped when they exit, so that the operating
6987 system's process table is not cluttered by zombies.
6989 - the local variable PID in Fcall_process, call_process_cleanup and
6990 call_process_kill, for synchronous subprocesses.
6991 record_unwind_protect is used to make sure this process is not
6992 forgotten: if the user interrupts call-process and the child
6993 process refuses to exit immediately even with two C-g's,
6994 call_process_kill adds PID's contents to deleted_pid_list before
6995 returning.
6997 The main Emacs thread invokes waitpid only on child processes that
6998 it creates and that have not been reaped. This avoid races on
6999 platforms such as GTK, where other threads create their own
7000 subprocesses which the main thread should not reap. For example,
7001 if the main thread attempted to reap an already-reaped child, it
7002 might inadvertently reap a GTK-created process that happened to
7003 have the same process ID. */
7005 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7006 its own SIGCHLD handling. On POSIXish systems, glib needs this to
7007 keep track of its own children. GNUstep is similar. */
7009 static void dummy_handler (int sig) {}
7010 static signal_handler_t volatile lib_child_handler;
7012 /* Handle a SIGCHLD signal by looking for known child processes of
7013 Emacs whose status have changed. For each one found, record its
7014 new status.
7016 All we do is change the status; we do not run sentinels or print
7017 notifications. That is saved for the next time keyboard input is
7018 done, in order to avoid timing errors.
7020 ** WARNING: this can be called during garbage collection.
7021 Therefore, it must not be fooled by the presence of mark bits in
7022 Lisp objects.
7024 ** USG WARNING: Although it is not obvious from the documentation
7025 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7026 signal() before executing at least one wait(), otherwise the
7027 handler will be called again, resulting in an infinite loop. The
7028 relevant portion of the documentation reads "SIGCLD signals will be
7029 queued and the signal-catching function will be continually
7030 reentered until the queue is empty". Invoking signal() causes the
7031 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7032 Inc.
7034 ** Malloc WARNING: This should never call malloc either directly or
7035 indirectly; if it does, that is a bug. */
7037 static void
7038 handle_child_signal (int sig)
7040 Lisp_Object tail, proc;
7042 /* Find the process that signaled us, and record its status. */
7044 /* The process can have been deleted by Fdelete_process, or have
7045 been started asynchronously by Fcall_process. */
7046 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
7048 bool all_pids_are_fixnums
7049 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
7050 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
7051 Lisp_Object head = XCAR (tail);
7052 Lisp_Object xpid;
7053 if (! CONSP (head))
7054 continue;
7055 xpid = XCAR (head);
7056 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
7058 pid_t deleted_pid;
7059 if (INTEGERP (xpid))
7060 deleted_pid = XINT (xpid);
7061 else
7062 deleted_pid = XFLOAT_DATA (xpid);
7063 if (child_status_changed (deleted_pid, 0, 0))
7065 if (STRINGP (XCDR (head)))
7066 unlink (SSDATA (XCDR (head)));
7067 XSETCAR (tail, Qnil);
7072 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7073 FOR_EACH_PROCESS (tail, proc)
7075 struct Lisp_Process *p = XPROCESS (proc);
7076 int status;
7078 if (p->alive
7079 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7081 /* Change the status of the process that was found. */
7082 p->tick = ++process_tick;
7083 p->raw_status = status;
7084 p->raw_status_new = 1;
7086 /* If process has terminated, stop waiting for its output. */
7087 if (WIFSIGNALED (status) || WIFEXITED (status))
7089 bool clear_desc_flag = 0;
7090 p->alive = 0;
7091 if (p->infd >= 0)
7092 clear_desc_flag = 1;
7094 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7095 if (clear_desc_flag)
7096 delete_read_fd (p->infd);
7101 lib_child_handler (sig);
7102 #ifdef NS_IMPL_GNUSTEP
7103 /* NSTask in GNUstep sets its child handler each time it is called.
7104 So we must re-set ours. */
7105 catch_child_signal ();
7106 #endif
7109 static void
7110 deliver_child_signal (int sig)
7112 deliver_process_signal (sig, handle_child_signal);
7116 static Lisp_Object
7117 exec_sentinel_error_handler (Lisp_Object error_val)
7119 /* Make sure error_val is a cons cell, as all the rest of error
7120 handling expects that, and will barf otherwise. */
7121 if (!CONSP (error_val))
7122 error_val = Fcons (Qerror, error_val);
7123 cmd_error_internal (error_val, "error in process sentinel: ");
7124 Vinhibit_quit = Qt;
7125 update_echo_area ();
7126 Fsleep_for (make_number (2), Qnil);
7127 return Qt;
7130 static void
7131 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7133 Lisp_Object sentinel, odeactivate;
7134 struct Lisp_Process *p = XPROCESS (proc);
7135 ptrdiff_t count = SPECPDL_INDEX ();
7136 bool outer_running_asynch_code = running_asynch_code;
7137 int waiting = waiting_for_user_input_p;
7139 if (inhibit_sentinels)
7140 return;
7142 odeactivate = Vdeactivate_mark;
7143 #if 0
7144 Lisp_Object obuffer, okeymap;
7145 XSETBUFFER (obuffer, current_buffer);
7146 okeymap = BVAR (current_buffer, keymap);
7147 #endif
7149 /* There's no good reason to let sentinels change the current
7150 buffer, and many callers of accept-process-output, sit-for, and
7151 friends don't expect current-buffer to be changed from under them. */
7152 record_unwind_current_buffer ();
7154 sentinel = p->sentinel;
7156 /* Inhibit quit so that random quits don't screw up a running filter. */
7157 specbind (Qinhibit_quit, Qt);
7158 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7160 /* In case we get recursively called,
7161 and we already saved the match data nonrecursively,
7162 save the same match data in safely recursive fashion. */
7163 if (outer_running_asynch_code)
7165 Lisp_Object tem;
7166 tem = Fmatch_data (Qnil, Qnil, Qnil);
7167 restore_search_regs ();
7168 record_unwind_save_match_data ();
7169 Fset_match_data (tem, Qt);
7172 /* For speed, if a search happens within this code,
7173 save the match data in a special nonrecursive fashion. */
7174 running_asynch_code = 1;
7176 internal_condition_case_1 (read_process_output_call,
7177 list3 (sentinel, proc, reason),
7178 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7179 exec_sentinel_error_handler);
7181 /* If we saved the match data nonrecursively, restore it now. */
7182 restore_search_regs ();
7183 running_asynch_code = outer_running_asynch_code;
7185 Vdeactivate_mark = odeactivate;
7187 /* Restore waiting_for_user_input_p as it was
7188 when we were called, in case the filter clobbered it. */
7189 waiting_for_user_input_p = waiting;
7191 #if 0
7192 if (! EQ (Fcurrent_buffer (), obuffer)
7193 || ! EQ (current_buffer->keymap, okeymap))
7194 #endif
7195 /* But do it only if the caller is actually going to read events.
7196 Otherwise there's no need to make him wake up, and it could
7197 cause trouble (for example it would make sit_for return). */
7198 if (waiting_for_user_input_p == -1)
7199 record_asynch_buffer_change ();
7201 unbind_to (count, Qnil);
7204 /* Report all recent events of a change in process status
7205 (either run the sentinel or output a message).
7206 This is usually done while Emacs is waiting for keyboard input
7207 but can be done at other times.
7209 Return positive if any input was received from WAIT_PROC (or from
7210 any process if WAIT_PROC is null), zero if input was attempted but
7211 none received, and negative if we didn't even try. */
7213 static int
7214 status_notify (struct Lisp_Process *deleting_process,
7215 struct Lisp_Process *wait_proc)
7217 Lisp_Object proc;
7218 Lisp_Object tail, msg;
7219 int got_some_output = -1;
7221 tail = Qnil;
7222 msg = Qnil;
7224 /* Set this now, so that if new processes are created by sentinels
7225 that we run, we get called again to handle their status changes. */
7226 update_tick = process_tick;
7228 FOR_EACH_PROCESS (tail, proc)
7230 Lisp_Object symbol;
7231 register struct Lisp_Process *p = XPROCESS (proc);
7233 if (p->tick != p->update_tick)
7235 p->update_tick = p->tick;
7237 /* If process is still active, read any output that remains. */
7238 while (! EQ (p->filter, Qt)
7239 && ! connecting_status (p->status)
7240 && ! EQ (p->status, Qlisten)
7241 /* Network or serial process not stopped: */
7242 && ! EQ (p->command, Qt)
7243 && p->infd >= 0
7244 && p != deleting_process)
7246 int nread = read_process_output (proc, p->infd);
7247 if ((!wait_proc || wait_proc == XPROCESS (proc))
7248 && got_some_output < nread)
7249 got_some_output = nread;
7250 if (nread <= 0)
7251 break;
7254 /* Get the text to use for the message. */
7255 if (p->raw_status_new)
7256 update_status (p);
7257 msg = status_message (p);
7259 /* If process is terminated, deactivate it or delete it. */
7260 symbol = p->status;
7261 if (CONSP (p->status))
7262 symbol = XCAR (p->status);
7264 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7265 || EQ (symbol, Qclosed))
7267 if (delete_exited_processes)
7268 remove_process (proc);
7269 else
7270 deactivate_process (proc);
7273 /* The actions above may have further incremented p->tick.
7274 So set p->update_tick again so that an error in the sentinel will
7275 not cause this code to be run again. */
7276 p->update_tick = p->tick;
7277 /* Now output the message suitably. */
7278 exec_sentinel (proc, msg);
7279 if (BUFFERP (p->buffer))
7280 /* In case it uses %s in mode-line-format. */
7281 bset_update_mode_line (XBUFFER (p->buffer));
7283 } /* end for */
7285 return got_some_output;
7288 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7289 Sinternal_default_process_sentinel, 2, 2, 0,
7290 doc: /* Function used as default sentinel for processes.
7291 This inserts a status message into the process's buffer, if there is one. */)
7292 (Lisp_Object proc, Lisp_Object msg)
7294 Lisp_Object buffer, symbol;
7295 struct Lisp_Process *p;
7296 CHECK_PROCESS (proc);
7297 p = XPROCESS (proc);
7298 buffer = p->buffer;
7299 symbol = p->status;
7300 if (CONSP (symbol))
7301 symbol = XCAR (symbol);
7303 if (!EQ (symbol, Qrun) && !NILP (buffer))
7305 Lisp_Object tem;
7306 struct buffer *old = current_buffer;
7307 ptrdiff_t opoint, opoint_byte;
7308 ptrdiff_t before, before_byte;
7310 /* Avoid error if buffer is deleted
7311 (probably that's why the process is dead, too). */
7312 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7313 return Qnil;
7314 Fset_buffer (buffer);
7316 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7317 msg = (code_convert_string_norecord
7318 (msg, Vlocale_coding_system, 1));
7320 opoint = PT;
7321 opoint_byte = PT_BYTE;
7322 /* Insert new output into buffer
7323 at the current end-of-output marker,
7324 thus preserving logical ordering of input and output. */
7325 if (XMARKER (p->mark)->buffer)
7326 Fgoto_char (p->mark);
7327 else
7328 SET_PT_BOTH (ZV, ZV_BYTE);
7330 before = PT;
7331 before_byte = PT_BYTE;
7333 tem = BVAR (current_buffer, read_only);
7334 bset_read_only (current_buffer, Qnil);
7335 insert_string ("\nProcess ");
7336 { /* FIXME: temporary kludge. */
7337 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7338 insert_string (" ");
7339 Finsert (1, &msg);
7340 bset_read_only (current_buffer, tem);
7341 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7343 if (opoint >= before)
7344 SET_PT_BOTH (opoint + (PT - before),
7345 opoint_byte + (PT_BYTE - before_byte));
7346 else
7347 SET_PT_BOTH (opoint, opoint_byte);
7349 set_buffer_internal (old);
7351 return Qnil;
7355 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7356 Sset_process_coding_system, 1, 3, 0,
7357 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7358 DECODING will be used to decode subprocess output and ENCODING to
7359 encode subprocess input. */)
7360 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7362 CHECK_PROCESS (process);
7364 struct Lisp_Process *p = XPROCESS (process);
7366 Fcheck_coding_system (decoding);
7367 Fcheck_coding_system (encoding);
7368 encoding = coding_inherit_eol_type (encoding, Qnil);
7369 pset_decode_coding_system (p, decoding);
7370 pset_encode_coding_system (p, encoding);
7372 /* If the sockets haven't been set up yet, the final setup part of
7373 this will be called asynchronously. */
7374 if (p->infd < 0 || p->outfd < 0)
7375 return Qnil;
7377 setup_process_coding_systems (process);
7379 return Qnil;
7382 DEFUN ("process-coding-system",
7383 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7384 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7385 (register Lisp_Object process)
7387 CHECK_PROCESS (process);
7388 return Fcons (XPROCESS (process)->decode_coding_system,
7389 XPROCESS (process)->encode_coding_system);
7392 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7393 Sset_process_filter_multibyte, 2, 2, 0,
7394 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7395 If FLAG is non-nil, the filter is given multibyte strings.
7396 If FLAG is nil, the filter is given unibyte strings. In this case,
7397 all character code conversion except for end-of-line conversion is
7398 suppressed. */)
7399 (Lisp_Object process, Lisp_Object flag)
7401 CHECK_PROCESS (process);
7403 struct Lisp_Process *p = XPROCESS (process);
7404 if (NILP (flag))
7405 pset_decode_coding_system
7406 (p, raw_text_coding_system (p->decode_coding_system));
7408 /* If the sockets haven't been set up yet, the final setup part of
7409 this will be called asynchronously. */
7410 if (p->infd < 0 || p->outfd < 0)
7411 return Qnil;
7413 setup_process_coding_systems (process);
7415 return Qnil;
7418 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7419 Sprocess_filter_multibyte_p, 1, 1, 0,
7420 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7421 (Lisp_Object process)
7423 CHECK_PROCESS (process);
7424 struct Lisp_Process *p = XPROCESS (process);
7425 if (p->infd < 0)
7426 return Qnil;
7427 struct coding_system *coding = proc_decode_coding_system[p->infd];
7428 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7434 # ifdef HAVE_GPM
7436 void
7437 add_gpm_wait_descriptor (int desc)
7439 add_keyboard_wait_descriptor (desc);
7442 void
7443 delete_gpm_wait_descriptor (int desc)
7445 delete_keyboard_wait_descriptor (desc);
7448 # endif
7450 # ifdef USABLE_SIGIO
7452 /* Return true if *MASK has a bit set
7453 that corresponds to one of the keyboard input descriptors. */
7455 static bool
7456 keyboard_bit_set (fd_set *mask)
7458 int fd;
7460 for (fd = 0; fd <= max_desc; fd++)
7461 if (FD_ISSET (fd, mask)
7462 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7463 == (FOR_READ | KEYBOARD_FD)))
7464 return 1;
7466 return 0;
7468 # endif
7470 #else /* not subprocesses */
7472 /* This is referenced in thread.c:run_thread (which is never actually
7473 called, since threads are not enabled for this configuration. */
7474 void
7475 update_processes_for_thread_death (Lisp_Object dying_thread)
7479 /* Defined in msdos.c. */
7480 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7481 struct timespec *, void *);
7483 /* Implementation of wait_reading_process_output, assuming that there
7484 are no subprocesses. Used only by the MS-DOS build.
7486 Wait for timeout to elapse and/or keyboard input to be available.
7488 TIME_LIMIT is:
7489 timeout in seconds
7490 If negative, gobble data immediately available but don't wait for any.
7492 NSECS is:
7493 an additional duration to wait, measured in nanoseconds
7494 If TIME_LIMIT is zero, then:
7495 If NSECS == 0, there is no limit.
7496 If NSECS > 0, the timeout consists of NSECS only.
7497 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7499 READ_KBD is:
7500 0 to ignore keyboard input, or
7501 1 to return when input is available, or
7502 -1 means caller will actually read the input, so don't throw to
7503 the quit handler.
7505 see full version for other parameters. We know that wait_proc will
7506 always be NULL, since `subprocesses' isn't defined.
7508 DO_DISPLAY means redisplay should be done to show subprocess
7509 output that arrives.
7511 Return -1 signifying we got no output and did not try. */
7514 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7515 bool do_display,
7516 Lisp_Object wait_for_cell,
7517 struct Lisp_Process *wait_proc, int just_wait_proc)
7519 register int nfds;
7520 struct timespec end_time, timeout;
7521 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7523 if (TYPE_MAXIMUM (time_t) < time_limit)
7524 time_limit = TYPE_MAXIMUM (time_t);
7526 if (time_limit < 0 || nsecs < 0)
7527 wait = MINIMUM;
7528 else if (time_limit > 0 || nsecs > 0)
7530 wait = TIMEOUT;
7531 end_time = timespec_add (current_timespec (),
7532 make_timespec (time_limit, nsecs));
7534 else
7535 wait = INFINITY;
7537 /* Turn off periodic alarms (in case they are in use)
7538 and then turn off any other atimers,
7539 because the select emulator uses alarms. */
7540 stop_polling ();
7541 turn_on_atimers (0);
7543 while (1)
7545 bool timeout_reduced_for_timers = false;
7546 fd_set waitchannels;
7547 int xerrno;
7549 /* If calling from keyboard input, do not quit
7550 since we want to return C-g as an input character.
7551 Otherwise, do pending quit if requested. */
7552 if (read_kbd >= 0)
7553 maybe_quit ();
7555 /* Exit now if the cell we're waiting for became non-nil. */
7556 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7557 break;
7559 /* Compute time from now till when time limit is up. */
7560 /* Exit if already run out. */
7561 if (wait == TIMEOUT)
7563 struct timespec now = current_timespec ();
7564 if (timespec_cmp (end_time, now) <= 0)
7565 break;
7566 timeout = timespec_sub (end_time, now);
7568 else
7569 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7571 /* If our caller will not immediately handle keyboard events,
7572 run timer events directly.
7573 (Callers that will immediately read keyboard events
7574 call timer_delay on their own.) */
7575 if (NILP (wait_for_cell))
7577 struct timespec timer_delay;
7581 unsigned old_timers_run = timers_run;
7582 timer_delay = timer_check ();
7583 if (timers_run != old_timers_run && do_display)
7584 /* We must retry, since a timer may have requeued itself
7585 and that could alter the time delay. */
7586 redisplay_preserve_echo_area (14);
7587 else
7588 break;
7590 while (!detect_input_pending ());
7592 /* If there is unread keyboard input, also return. */
7593 if (read_kbd != 0
7594 && requeued_events_pending_p ())
7595 break;
7597 if (timespec_valid_p (timer_delay))
7599 if (timespec_cmp (timer_delay, timeout) < 0)
7601 timeout = timer_delay;
7602 timeout_reduced_for_timers = true;
7607 /* Cause C-g and alarm signals to take immediate action,
7608 and cause input available signals to zero out timeout. */
7609 if (read_kbd < 0)
7610 set_waiting_for_input (&timeout);
7612 /* If a frame has been newly mapped and needs updating,
7613 reprocess its display stuff. */
7614 if (frame_garbaged && do_display)
7616 clear_waiting_for_input ();
7617 redisplay_preserve_echo_area (15);
7618 if (read_kbd < 0)
7619 set_waiting_for_input (&timeout);
7622 /* Wait till there is something to do. */
7623 FD_ZERO (&waitchannels);
7624 if (read_kbd && detect_input_pending ())
7625 nfds = 0;
7626 else
7628 if (read_kbd || !NILP (wait_for_cell))
7629 FD_SET (0, &waitchannels);
7630 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7633 xerrno = errno;
7635 /* Make C-g and alarm signals set flags again. */
7636 clear_waiting_for_input ();
7638 /* If we woke up due to SIGWINCH, actually change size now. */
7639 do_pending_window_change (0);
7641 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7642 /* We waited the full specified time, so return now. */
7643 break;
7645 if (nfds == -1)
7647 /* If the system call was interrupted, then go around the
7648 loop again. */
7649 if (xerrno == EINTR)
7650 FD_ZERO (&waitchannels);
7651 else
7652 report_file_errno ("Failed select", Qnil, xerrno);
7655 /* Check for keyboard input. */
7657 if (read_kbd
7658 && detect_input_pending_run_timers (do_display))
7660 swallow_events (do_display);
7661 if (detect_input_pending_run_timers (do_display))
7662 break;
7665 /* If there is unread keyboard input, also return. */
7666 if (read_kbd
7667 && requeued_events_pending_p ())
7668 break;
7670 /* If wait_for_cell. check for keyboard input
7671 but don't run any timers.
7672 ??? (It seems wrong to me to check for keyboard
7673 input at all when wait_for_cell, but the code
7674 has been this way since July 1994.
7675 Try changing this after version 19.31.) */
7676 if (! NILP (wait_for_cell)
7677 && detect_input_pending ())
7679 swallow_events (do_display);
7680 if (detect_input_pending ())
7681 break;
7684 /* Exit now if the cell we're waiting for became non-nil. */
7685 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7686 break;
7689 start_polling ();
7691 return -1;
7694 #endif /* not subprocesses */
7696 /* The following functions are needed even if async subprocesses are
7697 not supported. Some of them are no-op stubs in that case. */
7699 #ifdef HAVE_TIMERFD
7701 /* Add FD, which is a descriptor returned by timerfd_create,
7702 to the set of non-keyboard input descriptors. */
7704 void
7705 add_timer_wait_descriptor (int fd)
7707 add_read_fd (fd, timerfd_callback, NULL);
7708 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7711 #endif /* HAVE_TIMERFD */
7713 /* If program file NAME starts with /: for quoting a magic
7714 name, remove that, preserving the multibyteness of NAME. */
7716 Lisp_Object
7717 remove_slash_colon (Lisp_Object name)
7719 return
7720 (SREF (name, 0) == '/' && SREF (name, 1) == ':'
7721 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7722 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7723 : name);
7726 /* Add DESC to the set of keyboard input descriptors. */
7728 void
7729 add_keyboard_wait_descriptor (int desc)
7731 #ifdef subprocesses /* Actually means "not MSDOS". */
7732 eassert (desc >= 0 && desc < FD_SETSIZE);
7733 fd_callback_info[desc].flags &= ~PROCESS_FD;
7734 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7735 if (desc > max_desc)
7736 max_desc = desc;
7737 #endif
7740 /* From now on, do not expect DESC to give keyboard input. */
7742 void
7743 delete_keyboard_wait_descriptor (int desc)
7745 #ifdef subprocesses
7746 eassert (desc >= 0 && desc < FD_SETSIZE);
7748 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7750 if (desc == max_desc)
7751 recompute_max_desc ();
7752 #endif
7755 /* Setup coding systems of PROCESS. */
7757 void
7758 setup_process_coding_systems (Lisp_Object process)
7760 #ifdef subprocesses
7761 struct Lisp_Process *p = XPROCESS (process);
7762 int inch = p->infd;
7763 int outch = p->outfd;
7764 Lisp_Object coding_system;
7766 if (inch < 0 || outch < 0)
7767 return;
7769 if (!proc_decode_coding_system[inch])
7770 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7771 coding_system = p->decode_coding_system;
7772 if (EQ (p->filter, Qinternal_default_process_filter)
7773 && BUFFERP (p->buffer))
7775 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7776 coding_system = raw_text_coding_system (coding_system);
7778 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7780 if (!proc_encode_coding_system[outch])
7781 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7782 setup_coding_system (p->encode_coding_system,
7783 proc_encode_coding_system[outch]);
7784 #endif
7787 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7788 doc: /* Return the (or a) live process associated with BUFFER.
7789 BUFFER may be a buffer or the name of one.
7790 Return nil if all processes associated with BUFFER have been
7791 deleted or killed. */)
7792 (register Lisp_Object buffer)
7794 #ifdef subprocesses
7795 register Lisp_Object buf, tail, proc;
7797 if (NILP (buffer)) return Qnil;
7798 buf = Fget_buffer (buffer);
7799 if (NILP (buf)) return Qnil;
7801 FOR_EACH_PROCESS (tail, proc)
7802 if (EQ (XPROCESS (proc)->buffer, buf))
7803 return proc;
7804 #endif /* subprocesses */
7805 return Qnil;
7808 DEFUN ("process-inherit-coding-system-flag",
7809 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7810 1, 1, 0,
7811 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7812 If this flag is t, `buffer-file-coding-system' of the buffer
7813 associated with PROCESS will inherit the coding system used to decode
7814 the process output. */)
7815 (register Lisp_Object process)
7817 #ifdef subprocesses
7818 CHECK_PROCESS (process);
7819 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7820 #else
7821 /* Ignore the argument and return the value of
7822 inherit-process-coding-system. */
7823 return inherit_process_coding_system ? Qt : Qnil;
7824 #endif
7827 /* Kill all processes associated with `buffer'.
7828 If `buffer' is nil, kill all processes. */
7830 void
7831 kill_buffer_processes (Lisp_Object buffer)
7833 #ifdef subprocesses
7834 Lisp_Object tail, proc;
7836 FOR_EACH_PROCESS (tail, proc)
7837 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7839 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7840 Fdelete_process (proc);
7841 else if (XPROCESS (proc)->infd >= 0)
7842 process_send_signal (proc, SIGHUP, Qnil, 1);
7844 #else /* subprocesses */
7845 /* Since we have no subprocesses, this does nothing. */
7846 #endif /* subprocesses */
7849 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7850 Swaiting_for_user_input_p, 0, 0, 0,
7851 doc: /* Return non-nil if Emacs is waiting for input from the user.
7852 This is intended for use by asynchronous process output filters and sentinels. */)
7853 (void)
7855 #ifdef subprocesses
7856 return (waiting_for_user_input_p ? Qt : Qnil);
7857 #else
7858 return Qnil;
7859 #endif
7862 /* Stop reading input from keyboard sources. */
7864 void
7865 hold_keyboard_input (void)
7867 kbd_is_on_hold = 1;
7870 /* Resume reading input from keyboard sources. */
7872 void
7873 unhold_keyboard_input (void)
7875 kbd_is_on_hold = 0;
7878 /* Return true if keyboard input is on hold, zero otherwise. */
7880 bool
7881 kbd_on_hold_p (void)
7883 return kbd_is_on_hold;
7887 /* Enumeration of and access to system processes a-la ps(1). */
7889 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7890 0, 0, 0,
7891 doc: /* Return a list of numerical process IDs of all running processes.
7892 If this functionality is unsupported, return nil.
7894 See `process-attributes' for getting attributes of a process given its ID. */)
7895 (void)
7897 return list_system_processes ();
7900 DEFUN ("process-attributes", Fprocess_attributes,
7901 Sprocess_attributes, 1, 1, 0,
7902 doc: /* Return attributes of the process given by its PID, a number.
7904 Value is an alist where each element is a cons cell of the form
7906 (KEY . VALUE)
7908 If this functionality is unsupported, the value is nil.
7910 See `list-system-processes' for getting a list of all process IDs.
7912 The KEYs of the attributes that this function may return are listed
7913 below, together with the type of the associated VALUE (in parentheses).
7914 Not all platforms support all of these attributes; unsupported
7915 attributes will not appear in the returned alist.
7916 Unless explicitly indicated otherwise, numbers can have either
7917 integer or floating point values.
7919 euid -- Effective user User ID of the process (number)
7920 user -- User name corresponding to euid (string)
7921 egid -- Effective user Group ID of the process (number)
7922 group -- Group name corresponding to egid (string)
7923 comm -- Command name (executable name only) (string)
7924 state -- Process state code, such as "S", "R", or "T" (string)
7925 ppid -- Parent process ID (number)
7926 pgrp -- Process group ID (number)
7927 sess -- Session ID, i.e. process ID of session leader (number)
7928 ttname -- Controlling tty name (string)
7929 tpgid -- ID of foreground process group on the process's tty (number)
7930 minflt -- number of minor page faults (number)
7931 majflt -- number of major page faults (number)
7932 cminflt -- cumulative number of minor page faults (number)
7933 cmajflt -- cumulative number of major page faults (number)
7934 utime -- user time used by the process, in (current-time) format,
7935 which is a list of integers (HIGH LOW USEC PSEC)
7936 stime -- system time used by the process (current-time)
7937 time -- sum of utime and stime (current-time)
7938 cutime -- user time used by the process and its children (current-time)
7939 cstime -- system time used by the process and its children (current-time)
7940 ctime -- sum of cutime and cstime (current-time)
7941 pri -- priority of the process (number)
7942 nice -- nice value of the process (number)
7943 thcount -- process thread count (number)
7944 start -- time the process started (current-time)
7945 vsize -- virtual memory size of the process in KB's (number)
7946 rss -- resident set size of the process in KB's (number)
7947 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7948 pcpu -- percents of CPU time used by the process (floating-point number)
7949 pmem -- percents of total physical memory used by process's resident set
7950 (floating-point number)
7951 args -- command line which invoked the process (string). */)
7952 ( Lisp_Object pid)
7954 return system_process_attributes (pid);
7957 #ifdef subprocesses
7958 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7959 Invoke this after init_process_emacs, and after glib and/or GNUstep
7960 futz with the SIGCHLD handler, but before Emacs forks any children.
7961 This function's caller should block SIGCHLD. */
7963 void
7964 catch_child_signal (void)
7966 struct sigaction action, old_action;
7967 sigset_t oldset;
7968 emacs_sigaction_init (&action, deliver_child_signal);
7969 block_child_signal (&oldset);
7970 sigaction (SIGCHLD, &action, &old_action);
7971 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7972 || ! (old_action.sa_flags & SA_SIGINFO));
7974 if (old_action.sa_handler != deliver_child_signal)
7975 lib_child_handler
7976 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7977 ? dummy_handler
7978 : old_action.sa_handler);
7979 unblock_child_signal (&oldset);
7981 #endif /* subprocesses */
7983 /* Limit the number of open files to the value it had at startup. */
7985 void
7986 restore_nofile_limit (void)
7988 #ifdef HAVE_SETRLIMIT
7989 if (FD_SETSIZE < nofile_limit.rlim_cur)
7990 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7991 #endif
7995 /* This is not called "init_process" because that is the name of a
7996 Mach system call, so it would cause problems on Darwin systems. */
7997 void
7998 init_process_emacs (int sockfd)
8000 #ifdef subprocesses
8001 int i;
8003 inhibit_sentinels = 0;
8005 #ifndef CANNOT_DUMP
8006 if (! noninteractive || initialized)
8007 #endif
8009 #if defined HAVE_GLIB && !defined WINDOWSNT
8010 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8011 this should always fail, but is enough to initialize glib's
8012 private SIGCHLD handler, allowing catch_child_signal to copy
8013 it into lib_child_handler. */
8014 g_source_unref (g_child_watch_source_new (getpid ()));
8015 #endif
8016 catch_child_signal ();
8019 #ifdef HAVE_SETRLIMIT
8020 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8021 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
8022 nofile_limit.rlim_cur = 0;
8023 else if (FD_SETSIZE < nofile_limit.rlim_cur)
8025 struct rlimit rlim = nofile_limit;
8026 rlim.rlim_cur = FD_SETSIZE;
8027 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
8028 nofile_limit.rlim_cur = 0;
8030 #endif
8032 external_sock_fd = sockfd;
8033 Lisp_Object sockname = Qnil;
8034 # if HAVE_GETSOCKNAME
8035 if (0 <= sockfd)
8037 union u_sockaddr sa;
8038 socklen_t salen = sizeof sa;
8039 if (getsockname (sockfd, &sa.sa, &salen) == 0)
8040 sockname = conv_sockaddr_to_lisp (&sa.sa, salen);
8042 # endif
8043 Vinternal__daemon_sockname = sockname;
8045 max_desc = -1;
8046 memset (fd_callback_info, 0, sizeof (fd_callback_info));
8048 num_pending_connects = 0;
8050 process_output_delay_count = 0;
8051 process_output_skip = 0;
8053 /* Don't do this, it caused infinite select loops. The display
8054 method should call add_keyboard_wait_descriptor on stdin if it
8055 needs that. */
8056 #if 0
8057 FD_SET (0, &input_wait_mask);
8058 #endif
8060 Vprocess_alist = Qnil;
8061 deleted_pid_list = Qnil;
8062 for (i = 0; i < FD_SETSIZE; i++)
8064 chan_process[i] = Qnil;
8065 proc_buffered_char[i] = -1;
8067 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
8068 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
8069 #ifdef DATAGRAM_SOCKETS
8070 memset (datagram_address, 0, sizeof datagram_address);
8071 #endif
8073 #if defined (DARWIN_OS)
8074 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8075 processes. As such, we only change the default value. */
8076 if (initialized)
8078 char const *release = (STRINGP (Voperating_system_release)
8079 ? SSDATA (Voperating_system_release)
8080 : 0);
8081 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
8082 Vprocess_connection_type = Qnil;
8085 #endif
8086 #endif /* subprocesses */
8087 kbd_is_on_hold = 0;
8090 void
8091 syms_of_process (void)
8093 #ifdef subprocesses
8095 DEFSYM (Qprocessp, "processp");
8096 DEFSYM (Qrun, "run");
8097 DEFSYM (Qstop, "stop");
8098 DEFSYM (Qsignal, "signal");
8100 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8101 here again. */
8103 DEFSYM (Qopen, "open");
8104 DEFSYM (Qclosed, "closed");
8105 DEFSYM (Qconnect, "connect");
8106 DEFSYM (Qfailed, "failed");
8107 DEFSYM (Qlisten, "listen");
8108 DEFSYM (Qlocal, "local");
8109 DEFSYM (Qipv4, "ipv4");
8110 #ifdef AF_INET6
8111 DEFSYM (Qipv6, "ipv6");
8112 #endif
8113 DEFSYM (Qdatagram, "datagram");
8114 DEFSYM (Qseqpacket, "seqpacket");
8116 DEFSYM (QCport, ":port");
8117 DEFSYM (QCspeed, ":speed");
8118 DEFSYM (QCprocess, ":process");
8120 DEFSYM (QCbytesize, ":bytesize");
8121 DEFSYM (QCstopbits, ":stopbits");
8122 DEFSYM (QCparity, ":parity");
8123 DEFSYM (Qodd, "odd");
8124 DEFSYM (Qeven, "even");
8125 DEFSYM (QCflowcontrol, ":flowcontrol");
8126 DEFSYM (Qhw, "hw");
8127 DEFSYM (Qsw, "sw");
8128 DEFSYM (QCsummary, ":summary");
8130 DEFSYM (Qreal, "real");
8131 DEFSYM (Qnetwork, "network");
8132 DEFSYM (Qserial, "serial");
8133 DEFSYM (QCbuffer, ":buffer");
8134 DEFSYM (QChost, ":host");
8135 DEFSYM (QCservice, ":service");
8136 DEFSYM (QClocal, ":local");
8137 DEFSYM (QCremote, ":remote");
8138 DEFSYM (QCcoding, ":coding");
8139 DEFSYM (QCserver, ":server");
8140 DEFSYM (QCnowait, ":nowait");
8141 DEFSYM (QCsentinel, ":sentinel");
8142 DEFSYM (QCuse_external_socket, ":use-external-socket");
8143 DEFSYM (QCtls_parameters, ":tls-parameters");
8144 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8145 DEFSYM (QClog, ":log");
8146 DEFSYM (QCnoquery, ":noquery");
8147 DEFSYM (QCstop, ":stop");
8148 DEFSYM (QCplist, ":plist");
8149 DEFSYM (QCcommand, ":command");
8150 DEFSYM (QCconnection_type, ":connection-type");
8151 DEFSYM (QCstderr, ":stderr");
8152 DEFSYM (Qpty, "pty");
8153 DEFSYM (Qpipe, "pipe");
8155 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8157 staticpro (&Vprocess_alist);
8158 staticpro (&deleted_pid_list);
8160 #endif /* subprocesses */
8162 DEFSYM (QCname, ":name");
8163 DEFSYM (QCtype, ":type");
8165 DEFSYM (Qeuid, "euid");
8166 DEFSYM (Qegid, "egid");
8167 DEFSYM (Quser, "user");
8168 DEFSYM (Qgroup, "group");
8169 DEFSYM (Qcomm, "comm");
8170 DEFSYM (Qstate, "state");
8171 DEFSYM (Qppid, "ppid");
8172 DEFSYM (Qpgrp, "pgrp");
8173 DEFSYM (Qsess, "sess");
8174 DEFSYM (Qttname, "ttname");
8175 DEFSYM (Qtpgid, "tpgid");
8176 DEFSYM (Qminflt, "minflt");
8177 DEFSYM (Qmajflt, "majflt");
8178 DEFSYM (Qcminflt, "cminflt");
8179 DEFSYM (Qcmajflt, "cmajflt");
8180 DEFSYM (Qutime, "utime");
8181 DEFSYM (Qstime, "stime");
8182 DEFSYM (Qtime, "time");
8183 DEFSYM (Qcutime, "cutime");
8184 DEFSYM (Qcstime, "cstime");
8185 DEFSYM (Qctime, "ctime");
8186 #ifdef subprocesses
8187 DEFSYM (Qinternal_default_process_sentinel,
8188 "internal-default-process-sentinel");
8189 DEFSYM (Qinternal_default_process_filter,
8190 "internal-default-process-filter");
8191 #endif
8192 DEFSYM (Qpri, "pri");
8193 DEFSYM (Qnice, "nice");
8194 DEFSYM (Qthcount, "thcount");
8195 DEFSYM (Qstart, "start");
8196 DEFSYM (Qvsize, "vsize");
8197 DEFSYM (Qrss, "rss");
8198 DEFSYM (Qetime, "etime");
8199 DEFSYM (Qpcpu, "pcpu");
8200 DEFSYM (Qpmem, "pmem");
8201 DEFSYM (Qargs, "args");
8203 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8204 doc: /* Non-nil means delete processes immediately when they exit.
8205 A value of nil means don't delete them until `list-processes' is run. */);
8207 delete_exited_processes = 1;
8209 #ifdef subprocesses
8210 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8211 doc: /* Control type of device used to communicate with subprocesses.
8212 Values are nil to use a pipe, or t or `pty' to use a pty.
8213 The value has no effect if the system has no ptys or if all ptys are busy:
8214 then a pipe is used in any case.
8215 The value takes effect when `start-process' is called. */);
8216 Vprocess_connection_type = Qt;
8218 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8219 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8220 On some systems, when Emacs reads the output from a subprocess, the output data
8221 is read in very small blocks, potentially resulting in very poor performance.
8222 This behavior can be remedied to some extent by setting this variable to a
8223 non-nil value, as it will automatically delay reading from such processes, to
8224 allow them to produce more output before Emacs tries to read it.
8225 If the value is t, the delay is reset after each write to the process; any other
8226 non-nil value means that the delay is not reset on write.
8227 The variable takes effect when `start-process' is called. */);
8228 Vprocess_adaptive_read_buffering = Qt;
8230 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions,
8231 doc: /* List of functions to be called for `interrupt-process'.
8232 The arguments of the functions are the same as for `interrupt-process'.
8233 These functions are called in the order of the list, until one of them
8234 returns non-`nil'. */);
8235 Vinterrupt_process_functions = list1 (Qinternal_default_interrupt_process);
8237 DEFVAR_LISP ("internal--daemon-sockname", Vinternal__daemon_sockname,
8238 doc: /* Name of external socket passed to Emacs, or nil if none. */);
8239 Vinternal__daemon_sockname = Qnil;
8241 DEFSYM (Qinternal_default_interrupt_process,
8242 "internal-default-interrupt-process");
8243 DEFSYM (Qinterrupt_process_functions, "interrupt-process-functions");
8245 defsubr (&Sprocessp);
8246 defsubr (&Sget_process);
8247 defsubr (&Sdelete_process);
8248 defsubr (&Sprocess_status);
8249 defsubr (&Sprocess_exit_status);
8250 defsubr (&Sprocess_id);
8251 defsubr (&Sprocess_name);
8252 defsubr (&Sprocess_tty_name);
8253 defsubr (&Sprocess_command);
8254 defsubr (&Sset_process_buffer);
8255 defsubr (&Sprocess_buffer);
8256 defsubr (&Sprocess_mark);
8257 defsubr (&Sset_process_filter);
8258 defsubr (&Sprocess_filter);
8259 defsubr (&Sset_process_sentinel);
8260 defsubr (&Sprocess_sentinel);
8261 defsubr (&Sset_process_thread);
8262 defsubr (&Sprocess_thread);
8263 defsubr (&Sset_process_window_size);
8264 defsubr (&Sset_process_inherit_coding_system_flag);
8265 defsubr (&Sset_process_query_on_exit_flag);
8266 defsubr (&Sprocess_query_on_exit_flag);
8267 defsubr (&Sprocess_contact);
8268 defsubr (&Sprocess_plist);
8269 defsubr (&Sset_process_plist);
8270 defsubr (&Sprocess_list);
8271 defsubr (&Smake_process);
8272 defsubr (&Smake_pipe_process);
8273 defsubr (&Sserial_process_configure);
8274 defsubr (&Smake_serial_process);
8275 defsubr (&Sset_network_process_option);
8276 defsubr (&Smake_network_process);
8277 defsubr (&Sformat_network_address);
8278 defsubr (&Snetwork_interface_list);
8279 defsubr (&Snetwork_interface_info);
8280 #ifdef DATAGRAM_SOCKETS
8281 defsubr (&Sprocess_datagram_address);
8282 defsubr (&Sset_process_datagram_address);
8283 #endif
8284 defsubr (&Saccept_process_output);
8285 defsubr (&Sprocess_send_region);
8286 defsubr (&Sprocess_send_string);
8287 defsubr (&Sinternal_default_interrupt_process);
8288 defsubr (&Sinterrupt_process);
8289 defsubr (&Skill_process);
8290 defsubr (&Squit_process);
8291 defsubr (&Sstop_process);
8292 defsubr (&Scontinue_process);
8293 defsubr (&Sprocess_running_child_p);
8294 defsubr (&Sprocess_send_eof);
8295 defsubr (&Ssignal_process);
8296 defsubr (&Swaiting_for_user_input_p);
8297 defsubr (&Sprocess_type);
8298 defsubr (&Sinternal_default_process_sentinel);
8299 defsubr (&Sinternal_default_process_filter);
8300 defsubr (&Sset_process_coding_system);
8301 defsubr (&Sprocess_coding_system);
8302 defsubr (&Sset_process_filter_multibyte);
8303 defsubr (&Sprocess_filter_multibyte_p);
8306 Lisp_Object subfeatures = Qnil;
8307 const struct socket_options *sopt;
8309 #define ADD_SUBFEATURE(key, val) \
8310 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8312 ADD_SUBFEATURE (QCnowait, Qt);
8313 #ifdef DATAGRAM_SOCKETS
8314 ADD_SUBFEATURE (QCtype, Qdatagram);
8315 #endif
8316 #ifdef HAVE_SEQPACKET
8317 ADD_SUBFEATURE (QCtype, Qseqpacket);
8318 #endif
8319 #ifdef HAVE_LOCAL_SOCKETS
8320 ADD_SUBFEATURE (QCfamily, Qlocal);
8321 #endif
8322 ADD_SUBFEATURE (QCfamily, Qipv4);
8323 #ifdef AF_INET6
8324 ADD_SUBFEATURE (QCfamily, Qipv6);
8325 #endif
8326 #ifdef HAVE_GETSOCKNAME
8327 ADD_SUBFEATURE (QCservice, Qt);
8328 #endif
8329 ADD_SUBFEATURE (QCserver, Qt);
8331 for (sopt = socket_options; sopt->name; sopt++)
8332 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8334 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8337 #endif /* subprocesses */
8339 defsubr (&Sget_buffer_process);
8340 defsubr (&Sprocess_inherit_coding_system_flag);
8341 defsubr (&Slist_system_processes);
8342 defsubr (&Sprocess_attributes);