Use new function overflow_error in a few places
[emacs.git] / src / process.c
blobb4ba641f31b32060f564be51ace375eed9a4445e
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_HZ / 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_fixnum (WSTOPSIG (w)), Qnil));
688 else if (WIFEXITED (w))
689 return Fcons (Qexit, Fcons (make_fixnum (WEXITSTATUS (w)),
690 WCOREDUMP (w) ? Qt : Qnil));
691 else if (WIFSIGNALED (w))
692 return Fcons (Qsignal, Fcons (make_fixnum (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_fixnum (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 (XFIXNAT (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_fixnum (0), make_fixnum (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 (XFIXNAT (code) == 0
773 ? "deleted\n"
774 : "connection broken by remote peer\n");
775 if (XFIXNAT (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 (INT_TO_INTEGER (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_fixnum (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_fixnum (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_fixnum (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 It is a fixnum if the value is small enough, otherwise a bignum.
1161 For a network, serial, and pipe connections, this value is nil. */)
1162 (register Lisp_Object process)
1164 pid_t pid;
1166 CHECK_PROCESS (process);
1167 pid = XPROCESS (process)->pid;
1168 return pid ? INT_TO_INTEGER (pid) : Qnil;
1171 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1172 doc: /* Return the name of PROCESS, as a string.
1173 This is the name of the program invoked in PROCESS,
1174 possibly modified to make it unique among process names. */)
1175 (register Lisp_Object process)
1177 CHECK_PROCESS (process);
1178 return XPROCESS (process)->name;
1181 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1182 doc: /* Return the command that was executed to start PROCESS.
1183 This is a list of strings, the first string being the program executed
1184 and the rest of the strings being the arguments given to it.
1185 For a network or serial or pipe connection, this is nil (process is running)
1186 or t (process is stopped). */)
1187 (register Lisp_Object process)
1189 CHECK_PROCESS (process);
1190 return XPROCESS (process)->command;
1193 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1194 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1195 This is the terminal that the process itself reads and writes on,
1196 not the name of the pty that Emacs uses to talk with that terminal. */)
1197 (register Lisp_Object process)
1199 CHECK_PROCESS (process);
1200 return XPROCESS (process)->tty_name;
1203 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1204 2, 2, 0,
1205 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1206 Return BUFFER. */)
1207 (register Lisp_Object process, Lisp_Object buffer)
1209 struct Lisp_Process *p;
1211 CHECK_PROCESS (process);
1212 if (!NILP (buffer))
1213 CHECK_BUFFER (buffer);
1214 p = XPROCESS (process);
1215 pset_buffer (p, buffer);
1216 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1217 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1218 setup_process_coding_systems (process);
1219 return buffer;
1222 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1223 1, 1, 0,
1224 doc: /* Return the buffer PROCESS is associated with.
1225 The default process filter inserts output from PROCESS into this buffer. */)
1226 (register Lisp_Object process)
1228 CHECK_PROCESS (process);
1229 return XPROCESS (process)->buffer;
1232 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1233 1, 1, 0,
1234 doc: /* Return the marker for the end of the last output from PROCESS. */)
1235 (register Lisp_Object process)
1237 CHECK_PROCESS (process);
1238 return XPROCESS (process)->mark;
1241 static void
1242 set_process_filter_masks (struct Lisp_Process *p)
1244 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1245 delete_read_fd (p->infd);
1246 else if (EQ (p->filter, Qt)
1247 /* Network or serial process not stopped: */
1248 && !EQ (p->command, Qt))
1249 add_process_read_fd (p->infd);
1252 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1253 2, 2, 0,
1254 doc: /* Give PROCESS the filter function FILTER; nil means default.
1255 A value of t means stop accepting output from the process.
1257 When a process has a non-default filter, its buffer is not used for output.
1258 Instead, each time it does output, the entire string of output is
1259 passed to the filter.
1261 The filter gets two arguments: the process and the string of output.
1262 The string argument is normally a multibyte string, except:
1263 - if the process's input coding system is no-conversion or raw-text,
1264 it is a unibyte string (the non-converted input). */)
1265 (Lisp_Object process, Lisp_Object filter)
1267 CHECK_PROCESS (process);
1268 struct Lisp_Process *p = XPROCESS (process);
1270 /* Don't signal an error if the process's input file descriptor
1271 is closed. This could make debugging Lisp more difficult,
1272 for example when doing something like
1274 (setq process (start-process ...))
1275 (debug)
1276 (set-process-filter process ...) */
1278 if (NILP (filter))
1279 filter = Qinternal_default_process_filter;
1281 pset_filter (p, filter);
1283 if (p->infd >= 0)
1284 set_process_filter_masks (p);
1286 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1287 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1288 setup_process_coding_systems (process);
1289 return filter;
1292 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1293 1, 1, 0,
1294 doc: /* Return the filter function of PROCESS.
1295 See `set-process-filter' for more info on filter functions. */)
1296 (register Lisp_Object process)
1298 CHECK_PROCESS (process);
1299 return XPROCESS (process)->filter;
1302 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1303 2, 2, 0,
1304 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1305 The sentinel is called as a function when the process changes state.
1306 It gets two arguments: the process, and a string describing the change. */)
1307 (register Lisp_Object process, Lisp_Object sentinel)
1309 struct Lisp_Process *p;
1311 CHECK_PROCESS (process);
1312 p = XPROCESS (process);
1314 if (NILP (sentinel))
1315 sentinel = Qinternal_default_process_sentinel;
1317 pset_sentinel (p, sentinel);
1318 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1319 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1320 return sentinel;
1323 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1324 1, 1, 0,
1325 doc: /* Return the sentinel of PROCESS.
1326 See `set-process-sentinel' for more info on sentinels. */)
1327 (register Lisp_Object process)
1329 CHECK_PROCESS (process);
1330 return XPROCESS (process)->sentinel;
1333 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1334 2, 2, 0,
1335 doc: /* Set the locking thread of PROCESS to be THREAD.
1336 If THREAD is nil, the process is unlocked. */)
1337 (Lisp_Object process, Lisp_Object thread)
1339 struct Lisp_Process *proc;
1340 struct thread_state *tstate;
1342 CHECK_PROCESS (process);
1343 if (NILP (thread))
1344 tstate = NULL;
1345 else
1347 CHECK_THREAD (thread);
1348 tstate = XTHREAD (thread);
1351 proc = XPROCESS (process);
1352 pset_thread (proc, thread);
1353 if (proc->infd >= 0)
1354 fd_callback_info[proc->infd].thread = tstate;
1355 if (proc->outfd >= 0)
1356 fd_callback_info[proc->outfd].thread = tstate;
1358 return thread;
1361 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1362 1, 1, 0,
1363 doc: /* Ret the locking thread of PROCESS.
1364 If PROCESS is unlocked, this function returns nil. */)
1365 (Lisp_Object process)
1367 CHECK_PROCESS (process);
1368 return XPROCESS (process)->thread;
1371 DEFUN ("set-process-window-size", Fset_process_window_size,
1372 Sset_process_window_size, 3, 3, 0,
1373 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1374 Value is t if PROCESS was successfully told about the window size,
1375 nil otherwise. */)
1376 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1378 CHECK_PROCESS (process);
1380 /* All known platforms store window sizes as 'unsigned short'. */
1381 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1382 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1384 if (NETCONN_P (process)
1385 || XPROCESS (process)->infd < 0
1386 || (set_window_size (XPROCESS (process)->infd,
1387 XFIXNUM (height), XFIXNUM (width))
1388 < 0))
1389 return Qnil;
1390 else
1391 return Qt;
1394 DEFUN ("set-process-inherit-coding-system-flag",
1395 Fset_process_inherit_coding_system_flag,
1396 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1397 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1398 If the second argument FLAG is non-nil, then the variable
1399 `buffer-file-coding-system' of the buffer associated with PROCESS
1400 will be bound to the value of the coding system used to decode
1401 the process output.
1403 This is useful when the coding system specified for the process buffer
1404 leaves either the character code conversion or the end-of-line conversion
1405 unspecified, or if the coding system used to decode the process output
1406 is more appropriate for saving the process buffer.
1408 Binding the variable `inherit-process-coding-system' to non-nil before
1409 starting the process is an alternative way of setting the inherit flag
1410 for the process which will run.
1412 This function returns FLAG. */)
1413 (register Lisp_Object process, Lisp_Object flag)
1415 CHECK_PROCESS (process);
1416 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1417 return flag;
1420 DEFUN ("set-process-query-on-exit-flag",
1421 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1422 2, 2, 0,
1423 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1424 If the second argument FLAG is non-nil, Emacs will query the user before
1425 exiting or killing a buffer if PROCESS is running. This function
1426 returns FLAG. */)
1427 (register Lisp_Object process, Lisp_Object flag)
1429 CHECK_PROCESS (process);
1430 XPROCESS (process)->kill_without_query = NILP (flag);
1431 return flag;
1434 DEFUN ("process-query-on-exit-flag",
1435 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1436 1, 1, 0,
1437 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1438 (register Lisp_Object process)
1440 CHECK_PROCESS (process);
1441 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1444 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1445 1, 2, 0,
1446 doc: /* Return the contact info of PROCESS; t for a real child.
1447 For a network or serial or pipe connection, the value depends on the
1448 optional KEY arg. If KEY is nil, value is a cons cell of the form
1449 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1450 connection; it is t for a pipe connection. If KEY is t, the complete
1451 contact information for the connection is returned, else the specific
1452 value for the keyword KEY is returned. See `make-network-process',
1453 `make-serial-process', or `make-pipe-process' for the list of keywords.
1454 If PROCESS is a non-blocking network process that hasn't been fully
1455 set up yet, this function will block until socket setup has completed. */)
1456 (Lisp_Object process, Lisp_Object key)
1458 Lisp_Object contact;
1460 CHECK_PROCESS (process);
1461 contact = XPROCESS (process)->childp;
1463 #ifdef DATAGRAM_SOCKETS
1465 if (NETCONN_P (process))
1466 wait_for_socket_fds (process, "process-contact");
1468 if (DATAGRAM_CONN_P (process)
1469 && (EQ (key, Qt) || EQ (key, QCremote)))
1470 contact = Fplist_put (contact, QCremote,
1471 Fprocess_datagram_address (process));
1472 #endif
1474 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1475 || EQ (key, Qt))
1476 return contact;
1477 if (NILP (key) && NETCONN_P (process))
1478 return list2 (Fplist_get (contact, QChost),
1479 Fplist_get (contact, QCservice));
1480 if (NILP (key) && SERIALCONN_P (process))
1481 return list2 (Fplist_get (contact, QCport),
1482 Fplist_get (contact, QCspeed));
1483 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1484 if the pipe process is useful for purposes other than receiving
1485 stderr. */
1486 if (NILP (key) && PIPECONN_P (process))
1487 return Qt;
1488 return Fplist_get (contact, key);
1491 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1492 1, 1, 0,
1493 doc: /* Return the plist of PROCESS. */)
1494 (register Lisp_Object process)
1496 CHECK_PROCESS (process);
1497 return XPROCESS (process)->plist;
1500 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1501 2, 2, 0,
1502 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1503 (Lisp_Object process, Lisp_Object plist)
1505 CHECK_PROCESS (process);
1506 CHECK_LIST (plist);
1508 pset_plist (XPROCESS (process), plist);
1509 return plist;
1512 #if 0 /* Turned off because we don't currently record this info
1513 in the process. Perhaps add it. */
1514 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1515 doc: /* Return the connection type of PROCESS.
1516 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1517 a socket connection. */)
1518 (Lisp_Object process)
1520 return XPROCESS (process)->type;
1522 #endif
1524 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1525 doc: /* Return the connection type of PROCESS.
1526 The value is either the symbol `real', `network', `serial', or `pipe'.
1527 PROCESS may be a process, a buffer, the name of a process or buffer, or
1528 nil, indicating the current buffer's process. */)
1529 (Lisp_Object process)
1531 Lisp_Object proc;
1532 proc = get_process (process);
1533 return XPROCESS (proc)->type;
1536 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1537 1, 2, 0,
1538 doc: /* Convert network ADDRESS from internal format to a string.
1539 A 4 or 5 element vector represents an IPv4 address (with port number).
1540 An 8 or 9 element vector represents an IPv6 address (with port number).
1541 If optional second argument OMIT-PORT is non-nil, don't include a port
1542 number in the string, even when present in ADDRESS.
1543 Return nil if format of ADDRESS is invalid. */)
1544 (Lisp_Object address, Lisp_Object omit_port)
1546 if (NILP (address))
1547 return Qnil;
1549 if (STRINGP (address)) /* AF_LOCAL */
1550 return address;
1552 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1554 register struct Lisp_Vector *p = XVECTOR (address);
1555 ptrdiff_t size = p->header.size;
1556 Lisp_Object args[10];
1557 int nargs, i;
1558 char const *format;
1560 if (size == 4 || (size == 5 && !NILP (omit_port)))
1562 format = "%d.%d.%d.%d";
1563 nargs = 4;
1565 else if (size == 5)
1567 format = "%d.%d.%d.%d:%d";
1568 nargs = 5;
1570 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1572 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1573 nargs = 8;
1575 else if (size == 9)
1577 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1578 nargs = 9;
1580 else
1581 return Qnil;
1583 AUTO_STRING (format_obj, format);
1584 args[0] = format_obj;
1586 for (i = 0; i < nargs; i++)
1588 if (! RANGED_FIXNUMP (0, p->contents[i], 65535))
1589 return Qnil;
1591 if (nargs <= 5 /* IPv4 */
1592 && i < 4 /* host, not port */
1593 && XFIXNUM (p->contents[i]) > 255)
1594 return Qnil;
1596 args[i + 1] = p->contents[i];
1599 return Fformat (nargs + 1, args);
1602 if (CONSP (address))
1604 AUTO_STRING (format, "<Family %d>");
1605 return CALLN (Fformat, format, Fcar (address));
1608 return Qnil;
1611 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1612 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1613 (void)
1615 return Fmapcar (Qcdr, Vprocess_alist);
1618 /* Starting asynchronous inferior processes. */
1620 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1621 doc: /* Start a program in a subprocess. Return the process object for it.
1623 This is similar to `start-process', but arguments are specified as
1624 keyword/argument pairs. The following arguments are defined:
1626 :name NAME -- NAME is name for process. It is modified if necessary
1627 to make it unique.
1629 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1630 with the process. Process output goes at end of that buffer, unless
1631 you specify a filter function to handle the output. BUFFER may be
1632 also nil, meaning that this process is not associated with any buffer.
1634 :command COMMAND -- COMMAND is a list starting with the program file
1635 name, followed by strings to give to the program as arguments.
1637 :coding CODING -- If CODING is a symbol, it specifies the coding
1638 system used for both reading and writing for this process. If CODING
1639 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1640 ENCODING is used for writing.
1642 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1643 the process is running. If BOOL is not given, query before exiting.
1645 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1646 In the stopped state, a process does not accept incoming data, but you
1647 can send outgoing data. The stopped state is cleared by
1648 `continue-process' and set by `stop-process'.
1650 :connection-type TYPE -- TYPE is control type of device used to
1651 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1652 to use a pty, or nil to use the default specified through
1653 `process-connection-type'.
1655 :filter FILTER -- Install FILTER as the process filter.
1657 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1659 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1660 to the standard error of subprocess. Specifying this implies
1661 `:connection-type' is set to `pipe'. If STDERR is nil, standard error
1662 is mixed with standard output and sent to BUFFER or FILTER.
1664 usage: (make-process &rest ARGS) */)
1665 (ptrdiff_t nargs, Lisp_Object *args)
1667 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1668 Lisp_Object xstderr, stderrproc;
1669 ptrdiff_t count = SPECPDL_INDEX ();
1671 if (nargs == 0)
1672 return Qnil;
1674 /* Save arguments for process-contact and clone-process. */
1675 contact = Flist (nargs, args);
1677 buffer = Fplist_get (contact, QCbuffer);
1678 if (!NILP (buffer))
1679 buffer = Fget_buffer_create (buffer);
1681 /* Make sure that the child will be able to chdir to the current
1682 buffer's current directory, or its unhandled equivalent. We
1683 can't just have the child check for an error when it does the
1684 chdir, since it's in a vfork. */
1685 current_dir = encode_current_directory ();
1687 name = Fplist_get (contact, QCname);
1688 CHECK_STRING (name);
1690 command = Fplist_get (contact, QCcommand);
1691 if (CONSP (command))
1692 program = XCAR (command);
1693 else
1694 program = Qnil;
1696 if (!NILP (program))
1697 CHECK_STRING (program);
1699 bool query_on_exit = NILP (Fplist_get (contact, QCnoquery));
1701 stderrproc = Qnil;
1702 xstderr = Fplist_get (contact, QCstderr);
1703 if (PROCESSP (xstderr))
1705 if (!PIPECONN_P (xstderr))
1706 error ("Process is not a pipe process");
1707 stderrproc = xstderr;
1709 else if (!NILP (xstderr))
1711 CHECK_STRING (program);
1712 stderrproc = CALLN (Fmake_pipe_process,
1713 QCname,
1714 concat2 (name, build_string (" stderr")),
1715 QCbuffer,
1716 Fget_buffer_create (xstderr),
1717 QCnoquery,
1718 query_on_exit ? Qnil : Qt);
1721 proc = make_process (name);
1722 record_unwind_protect (start_process_unwind, proc);
1724 pset_childp (XPROCESS (proc), Qt);
1725 eassert (NILP (XPROCESS (proc)->plist));
1726 pset_type (XPROCESS (proc), Qreal);
1727 pset_buffer (XPROCESS (proc), buffer);
1728 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1729 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1730 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1732 if (!query_on_exit)
1733 XPROCESS (proc)->kill_without_query = 1;
1734 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1735 pset_command (XPROCESS (proc), Qt);
1737 tem = Fplist_get (contact, QCconnection_type);
1738 if (EQ (tem, Qpty))
1739 XPROCESS (proc)->pty_flag = true;
1740 else if (EQ (tem, Qpipe))
1741 XPROCESS (proc)->pty_flag = false;
1742 else if (NILP (tem))
1743 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1744 else
1745 report_file_error ("Unknown connection type", tem);
1747 if (!NILP (stderrproc))
1749 pset_stderrproc (XPROCESS (proc), stderrproc);
1751 XPROCESS (proc)->pty_flag = false;
1754 #ifdef HAVE_GNUTLS
1755 /* AKA GNUTLS_INITSTAGE(proc). */
1756 verify (GNUTLS_STAGE_EMPTY == 0);
1757 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1758 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1759 #endif
1761 XPROCESS (proc)->adaptive_read_buffering
1762 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1763 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1765 /* Make the process marker point into the process buffer (if any). */
1766 if (BUFFERP (buffer))
1767 set_marker_both (XPROCESS (proc)->mark, buffer,
1768 BUF_ZV (XBUFFER (buffer)),
1769 BUF_ZV_BYTE (XBUFFER (buffer)));
1771 USE_SAFE_ALLOCA;
1774 /* Decide coding systems for communicating with the process. Here
1775 we don't setup the structure coding_system nor pay attention to
1776 unibyte mode. They are done in create_process. */
1778 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1779 Lisp_Object coding_systems = Qt;
1780 Lisp_Object val, *args2;
1782 tem = Fplist_get (contact, QCcoding);
1783 if (!NILP (tem))
1785 val = tem;
1786 if (CONSP (val))
1787 val = XCAR (val);
1789 else
1790 val = Vcoding_system_for_read;
1791 if (NILP (val))
1793 ptrdiff_t nargs2 = 3 + XFIXNUM (Flength (command));
1794 Lisp_Object tem2;
1795 SAFE_ALLOCA_LISP (args2, nargs2);
1796 ptrdiff_t i = 0;
1797 args2[i++] = Qstart_process;
1798 args2[i++] = name;
1799 args2[i++] = buffer;
1800 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1801 args2[i++] = XCAR (tem2);
1802 if (!NILP (program))
1803 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1804 if (CONSP (coding_systems))
1805 val = XCAR (coding_systems);
1806 else if (CONSP (Vdefault_process_coding_system))
1807 val = XCAR (Vdefault_process_coding_system);
1809 pset_decode_coding_system (XPROCESS (proc), val);
1811 if (!NILP (tem))
1813 val = tem;
1814 if (CONSP (val))
1815 val = XCDR (val);
1817 else
1818 val = Vcoding_system_for_write;
1819 if (NILP (val))
1821 if (EQ (coding_systems, Qt))
1823 ptrdiff_t nargs2 = 3 + XFIXNUM (Flength (command));
1824 Lisp_Object tem2;
1825 SAFE_ALLOCA_LISP (args2, nargs2);
1826 ptrdiff_t i = 0;
1827 args2[i++] = Qstart_process;
1828 args2[i++] = name;
1829 args2[i++] = buffer;
1830 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1831 args2[i++] = XCAR (tem2);
1832 if (!NILP (program))
1833 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1835 if (CONSP (coding_systems))
1836 val = XCDR (coding_systems);
1837 else if (CONSP (Vdefault_process_coding_system))
1838 val = XCDR (Vdefault_process_coding_system);
1840 pset_encode_coding_system (XPROCESS (proc), val);
1841 /* Note: At this moment, the above coding system may leave
1842 text-conversion or eol-conversion unspecified. They will be
1843 decided after we read output from the process and decode it by
1844 some coding system, or just before we actually send a text to
1845 the process. */
1849 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1850 eassert (XPROCESS (proc)->decoding_carryover == 0);
1851 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1853 XPROCESS (proc)->inherit_coding_system_flag
1854 = !(NILP (buffer) || !inherit_process_coding_system);
1856 if (!NILP (program))
1858 Lisp_Object program_args = XCDR (command);
1860 /* If program file name is not absolute, search our path for it.
1861 Put the name we will really use in TEM. */
1862 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1863 && !(SCHARS (program) > 1
1864 && IS_DEVICE_SEP (SREF (program, 1))))
1866 tem = Qnil;
1867 openp (Vexec_path, program, Vexec_suffixes, &tem,
1868 make_fixnum (X_OK), false);
1869 if (NILP (tem))
1870 report_file_error ("Searching for program", program);
1871 tem = Fexpand_file_name (tem, Qnil);
1873 else
1875 if (!NILP (Ffile_directory_p (program)))
1876 error ("Specified program for new process is a directory");
1877 tem = program;
1880 /* Remove "/:" from TEM. */
1881 tem = remove_slash_colon (tem);
1883 Lisp_Object arg_encoding = Qnil;
1885 /* Encode the file name and put it in NEW_ARGV.
1886 That's where the child will use it to execute the program. */
1887 tem = list1 (ENCODE_FILE (tem));
1888 ptrdiff_t new_argc = 1;
1890 /* Here we encode arguments by the coding system used for sending
1891 data to the process. We don't support using different coding
1892 systems for encoding arguments and for encoding data sent to the
1893 process. */
1895 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1897 Lisp_Object arg = XCAR (tem2);
1898 CHECK_STRING (arg);
1899 if (STRING_MULTIBYTE (arg))
1901 if (NILP (arg_encoding))
1902 arg_encoding = (complement_process_encoding_system
1903 (XPROCESS (proc)->encode_coding_system));
1904 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1906 tem = Fcons (arg, tem);
1907 new_argc++;
1910 /* Now that everything is encoded we can collect the strings into
1911 NEW_ARGV. */
1912 char **new_argv;
1913 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1914 new_argv[new_argc] = 0;
1916 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1918 new_argv[i] = SSDATA (XCAR (tem));
1919 tem = XCDR (tem);
1922 create_process (proc, new_argv, current_dir);
1924 else
1925 create_pty (proc);
1927 return SAFE_FREE_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_fixnum (len), Qnil);
2508 p = XVECTOR (address);
2509 p->contents[--len] = make_fixnum (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_fixnum (len), Qnil);
2520 p = XVECTOR (address);
2521 p->contents[--len] = make_fixnum (ntohs (sin6->sin6_port));
2522 for (i = 0; i < len; i++)
2523 p->contents[i] = make_fixnum (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_fixnum (sa->sa_family),
2552 Fmake_vector (make_fixnum (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_fixnum (*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_fixnum (res->ai_protocol);
2571 eassert (XFIXNUM (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_FIXNUMP (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 = XFIXNUM (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 = XFIXNUM (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 = XFIXNUM (p->contents[--len]);
2655 sin6->sin6_port = htons (hostport);
2656 for (i = 0; i < len; i++)
2657 if (FIXNUMP (p->contents[i]))
2659 int j = XFIXNAT (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 (FIXNUMP (p->contents[i]))
2691 *cp++ = XFIXNAT (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_FIXNUMP (int, val))
2823 optval = XFIXNUM (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_FIXNUMP (int, val))
2862 linger.l_linger = XFIXNUM (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_FIXNUM (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 int s = -1, outch, inch;
3335 int xerrno = 0;
3336 int family;
3337 int ret;
3338 ptrdiff_t addrlen UNINIT;
3339 struct Lisp_Process *p = XPROCESS (proc);
3340 Lisp_Object contact = p->childp;
3341 int optbits = 0;
3342 int socket_to_use = -1;
3344 if (!NILP (use_external_socket_p))
3346 socket_to_use = external_sock_fd;
3348 /* Ensure we don't consume the external socket twice. */
3349 external_sock_fd = -1;
3352 /* Do this in case we never enter the while-loop below. */
3353 s = -1;
3355 struct sockaddr *sa = NULL;
3356 ptrdiff_t count = SPECPDL_INDEX ();
3357 record_unwind_protect_nothing ();
3358 ptrdiff_t count1 = SPECPDL_INDEX ();
3360 while (!NILP (addrinfos))
3362 Lisp_Object addrinfo = XCAR (addrinfos);
3363 addrinfos = XCDR (addrinfos);
3364 int protocol = XFIXNUM (XCAR (addrinfo));
3365 Lisp_Object ip_address = XCDR (addrinfo);
3367 #ifdef WINDOWSNT
3368 retry_connect:
3369 #endif
3371 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3372 sa = xrealloc (sa, addrlen);
3373 set_unwind_protect_ptr (count, xfree, sa);
3374 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3376 s = socket_to_use;
3377 if (s < 0)
3379 int socktype = p->socktype | SOCK_CLOEXEC;
3380 if (p->is_non_blocking_client)
3381 socktype |= SOCK_NONBLOCK;
3382 s = socket (family, socktype, protocol);
3383 if (s < 0)
3385 xerrno = errno;
3386 continue;
3390 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3392 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3393 if (ret < 0)
3395 xerrno = errno;
3396 emacs_close (s);
3397 s = -1;
3398 if (0 <= socket_to_use)
3399 break;
3400 continue;
3404 #ifdef DATAGRAM_SOCKETS
3405 if (!p->is_server && p->socktype == SOCK_DGRAM)
3406 break;
3407 #endif /* DATAGRAM_SOCKETS */
3409 /* Make us close S if quit. */
3410 record_unwind_protect_int (close_file_unwind, s);
3412 /* Parse network options in the arg list. We simply ignore anything
3413 which isn't a known option (including other keywords). An error
3414 is signaled if setting a known option fails. */
3416 Lisp_Object params = contact, key, val;
3418 while (!NILP (params))
3420 key = XCAR (params);
3421 params = XCDR (params);
3422 val = XCAR (params);
3423 params = XCDR (params);
3424 optbits |= set_socket_option (s, key, val);
3428 if (p->is_server)
3430 /* Configure as a server socket. */
3432 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3433 explicit :reuseaddr key to override this. */
3434 #ifdef HAVE_LOCAL_SOCKETS
3435 if (family != AF_LOCAL)
3436 #endif
3437 if (!(optbits & (1 << OPIX_REUSEADDR)))
3439 int optval = 1;
3440 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3441 report_file_error ("Cannot set reuse option on server socket", Qnil);
3444 /* If passed a socket descriptor, it should be already bound. */
3445 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3446 report_file_error ("Cannot bind server socket", Qnil);
3448 #ifdef HAVE_GETSOCKNAME
3449 if (p->port == 0
3450 #ifdef HAVE_LOCAL_SOCKETS
3451 && family != AF_LOCAL
3452 #endif
3455 struct sockaddr_in sa1;
3456 socklen_t len1 = sizeof (sa1);
3457 #ifdef AF_INET6
3458 /* The code below assumes the port is at the same offset
3459 and of the same width in both IPv4 and IPv6
3460 structures, but the standards don't guarantee that,
3461 so verify it here. */
3462 struct sockaddr_in6 sa6;
3463 verify ((offsetof (struct sockaddr_in, sin_port)
3464 == offsetof (struct sockaddr_in6, sin6_port))
3465 && sizeof (sa1.sin_port) == sizeof (sa6.sin6_port));
3466 #endif
3467 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3468 if (getsockname (s, psa1, &len1) == 0)
3470 Lisp_Object service = make_fixnum (ntohs (sa1.sin_port));
3471 contact = Fplist_put (contact, QCservice, service);
3472 /* Save the port number so that we can stash it in
3473 the process object later. */
3474 DECLARE_POINTER_ALIAS (psa, struct sockaddr_in, sa);
3475 psa->sin_port = sa1.sin_port;
3478 #endif
3480 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3481 report_file_error ("Cannot listen on server socket", Qnil);
3483 break;
3486 maybe_quit ();
3488 ret = connect (s, sa, addrlen);
3489 xerrno = errno;
3491 if (ret == 0 || xerrno == EISCONN)
3493 /* The unwind-protect will be discarded afterwards. */
3494 break;
3497 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3498 break;
3500 #ifndef WINDOWSNT
3501 if (xerrno == EINTR)
3503 /* Unlike most other syscalls connect() cannot be called
3504 again. (That would return EALREADY.) The proper way to
3505 wait for completion is pselect(). */
3506 int sc;
3507 socklen_t len;
3508 fd_set fdset;
3509 retry_select:
3510 FD_ZERO (&fdset);
3511 FD_SET (s, &fdset);
3512 maybe_quit ();
3513 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3514 if (sc == -1)
3516 if (errno == EINTR)
3517 goto retry_select;
3518 else
3519 report_file_error ("Failed select", Qnil);
3521 eassert (sc > 0);
3523 len = sizeof xerrno;
3524 eassert (FD_ISSET (s, &fdset));
3525 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3526 report_file_error ("Failed getsockopt", Qnil);
3527 if (xerrno == 0)
3528 break;
3529 if (NILP (addrinfos))
3530 report_file_errno ("Failed connect", Qnil, xerrno);
3532 #endif /* !WINDOWSNT */
3534 /* Discard the unwind protect closing S. */
3535 specpdl_ptr = specpdl + count1;
3536 emacs_close (s);
3537 s = -1;
3538 if (0 <= socket_to_use)
3539 break;
3541 #ifdef WINDOWSNT
3542 if (xerrno == EINTR)
3543 goto retry_connect;
3544 #endif
3547 if (s >= 0)
3549 #ifdef DATAGRAM_SOCKETS
3550 if (p->socktype == SOCK_DGRAM)
3552 if (datagram_address[s].sa)
3553 emacs_abort ();
3555 datagram_address[s].sa = xmalloc (addrlen);
3556 datagram_address[s].len = addrlen;
3557 if (p->is_server)
3559 Lisp_Object remote;
3560 memset (datagram_address[s].sa, 0, addrlen);
3561 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3563 int rfamily;
3564 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3565 if (rlen != 0 && rfamily == family
3566 && rlen == addrlen)
3567 conv_lisp_to_sockaddr (rfamily, remote,
3568 datagram_address[s].sa, rlen);
3571 else
3572 memcpy (datagram_address[s].sa, sa, addrlen);
3574 #endif
3576 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3577 conv_sockaddr_to_lisp (sa, addrlen));
3578 #ifdef HAVE_GETSOCKNAME
3579 if (!p->is_server)
3581 struct sockaddr_storage sa1;
3582 socklen_t len1 = sizeof (sa1);
3583 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3584 if (getsockname (s, psa1, &len1) == 0)
3585 contact = Fplist_put (contact, QClocal,
3586 conv_sockaddr_to_lisp (psa1, len1));
3588 #endif
3591 if (s < 0)
3593 const char *err = (p->is_server
3594 ? "make server process failed"
3595 : "make client process failed");
3597 /* If non-blocking got this far - and failed - assume non-blocking is
3598 not supported after all. This is probably a wrong assumption, but
3599 the normal blocking calls to open-network-stream handles this error
3600 better. */
3601 if (p->is_non_blocking_client)
3603 Lisp_Object data = get_file_errno_data (err, contact, xerrno);
3605 pset_status (p, list2 (Fcar (data), Fcdr (data)));
3606 unbind_to (count, Qnil);
3607 return;
3610 report_file_errno (err, contact, xerrno);
3613 inch = s;
3614 outch = s;
3616 chan_process[inch] = proc;
3618 fcntl (inch, F_SETFL, O_NONBLOCK);
3620 p = XPROCESS (proc);
3621 p->open_fd[SUBPROCESS_STDIN] = inch;
3622 p->infd = inch;
3623 p->outfd = outch;
3625 /* Discard the unwind protect for closing S, if any. */
3626 specpdl_ptr = specpdl + count1;
3628 if (p->is_server && p->socktype != SOCK_DGRAM)
3629 pset_status (p, Qlisten);
3631 /* Make the process marker point into the process buffer (if any). */
3632 if (BUFFERP (p->buffer))
3633 set_marker_both (p->mark, p->buffer,
3634 BUF_ZV (XBUFFER (p->buffer)),
3635 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3637 if (p->is_non_blocking_client)
3639 /* We may get here if connect did succeed immediately. However,
3640 in that case, we still need to signal this like a non-blocking
3641 connection. */
3642 if (! (connecting_status (p->status)
3643 && EQ (XCDR (p->status), addrinfos)))
3644 pset_status (p, Fcons (Qconnect, addrinfos));
3645 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3646 add_non_blocking_write_fd (inch);
3648 else
3649 /* A server may have a client filter setting of Qt, but it must
3650 still listen for incoming connects unless it is stopped. */
3651 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3652 || (EQ (p->status, Qlisten) && NILP (p->command)))
3653 add_process_read_fd (inch);
3655 if (inch > max_desc)
3656 max_desc = inch;
3658 /* Set up the masks based on the process filter. */
3659 set_process_filter_masks (p);
3661 setup_process_coding_systems (proc);
3663 #ifdef HAVE_GNUTLS
3664 /* Continue the asynchronous connection. */
3665 if (!NILP (p->gnutls_boot_parameters))
3667 Lisp_Object boot, params = p->gnutls_boot_parameters;
3669 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3670 p->gnutls_boot_parameters = Qnil;
3672 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3673 /* Run sentinels, etc. */
3674 finish_after_tls_connection (proc);
3675 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3677 deactivate_process (proc);
3678 if (NILP (boot))
3679 pset_status (p, list2 (Qfailed,
3680 build_string ("TLS negotiation failed")));
3681 else
3682 pset_status (p, list2 (Qfailed, boot));
3685 #endif
3687 unbind_to (count, Qnil);
3690 /* Create a network stream/datagram client/server process. Treated
3691 exactly like a normal process when reading and writing. Primary
3692 differences are in status display and process deletion. A network
3693 connection has no PID; you cannot signal it. All you can do is
3694 stop/continue it and deactivate/close it via delete-process. */
3696 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3697 0, MANY, 0,
3698 doc: /* Create and return a network server or client process.
3700 In Emacs, network connections are represented by process objects, so
3701 input and output work as for subprocesses and `delete-process' closes
3702 a network connection. However, a network process has no process id,
3703 it cannot be signaled, and the status codes are different from normal
3704 processes.
3706 Arguments are specified as keyword/argument pairs. The following
3707 arguments are defined:
3709 :name NAME -- NAME is name for process. It is modified if necessary
3710 to make it unique.
3712 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3713 with the process. Process output goes at end of that buffer, unless
3714 you specify a filter function to handle the output. BUFFER may be
3715 also nil, meaning that this process is not associated with any buffer.
3717 :host HOST -- HOST is name of the host to connect to, or its IP
3718 address. The symbol `local' specifies the local host. If specified
3719 for a server process, it must be a valid name or address for the local
3720 host, and only clients connecting to that address will be accepted.
3722 :service SERVICE -- SERVICE is name of the service desired, or an
3723 integer specifying a port number to connect to. If SERVICE is t,
3724 a random port number is selected for the server. A port number can
3725 be specified as an integer string, e.g., "80", as well as an integer.
3727 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3728 stream type connection, `datagram' creates a datagram type connection,
3729 `seqpacket' creates a reliable datagram connection.
3731 :family FAMILY -- FAMILY is the address (and protocol) family for the
3732 service specified by HOST and SERVICE. The default (nil) is to use
3733 whatever address family (IPv4 or IPv6) that is defined for the host
3734 and port number specified by HOST and SERVICE. Other address families
3735 supported are:
3736 local -- for a local (i.e. UNIX) address specified by SERVICE.
3737 ipv4 -- use IPv4 address family only.
3738 ipv6 -- use IPv6 address family only.
3740 :local ADDRESS -- ADDRESS is the local address used for the connection.
3741 This parameter is ignored when opening a client process. When specified
3742 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3744 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3745 connection. This parameter is ignored when opening a stream server
3746 process. For a datagram server process, it specifies the initial
3747 setting of the remote datagram address. When specified for a client
3748 process, the FAMILY, HOST, and SERVICE args are ignored.
3750 The format of ADDRESS depends on the address family:
3751 - An IPv4 address is represented as a vector of integers [A B C D P]
3752 corresponding to numeric IP address A.B.C.D and port number P.
3753 - A local address is represented as a string with the address in the
3754 local address space.
3755 - An "unsupported family" address is represented by a cons (F . AV)
3756 where F is the family number and AV is a vector containing the socket
3757 address data with one element per address data byte. Do not rely on
3758 this format in portable code, as it may depend on implementation
3759 defined constants, data sizes, and data structure alignment.
3761 :coding CODING -- If CODING is a symbol, it specifies the coding
3762 system used for both reading and writing for this process. If CODING
3763 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3764 ENCODING is used for writing.
3766 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3767 process, return without waiting for the connection to complete;
3768 instead, the sentinel function will be called with second arg matching
3769 "open" (if successful) or "failed" when the connect completes.
3770 Default is to use a blocking connect (i.e. wait) for stream type
3771 connections.
3773 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3774 running when Emacs is exited.
3776 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3777 In the stopped state, a server process does not accept new
3778 connections, and a client process does not handle incoming traffic.
3779 The stopped state is cleared by `continue-process' and set by
3780 `stop-process'.
3782 :filter FILTER -- Install FILTER as the process filter.
3784 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3785 process filter are multibyte, otherwise they are unibyte.
3786 If this keyword is not specified, the strings are multibyte.
3788 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3790 :log LOG -- Install LOG as the server process log function. This
3791 function is called when the server accepts a network connection from a
3792 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3793 is the server process, CLIENT is the new process for the connection,
3794 and MESSAGE is a string.
3796 :plist PLIST -- Install PLIST as the new process's initial plist.
3798 :tls-parameters LIST -- is a list that should be supplied if you're
3799 opening a TLS connection. The first element is the TLS type (either
3800 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3801 be a keyword list accepted by gnutls-boot (as returned by
3802 `gnutls-boot-parameters').
3804 :server QLEN -- if QLEN is non-nil, create a server process for the
3805 specified FAMILY, SERVICE, and connection type (stream or datagram).
3806 If QLEN is an integer, it is used as the max. length of the server's
3807 pending connection queue (also known as the backlog); the default
3808 queue length is 5. Default is to create a client process.
3810 The following network options can be specified for this connection:
3812 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3813 :dontroute BOOL -- Only send to directly connected hosts.
3814 :keepalive BOOL -- Send keep-alive messages on network stream.
3815 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3816 :oobinline BOOL -- Place out-of-band data in receive data stream.
3817 :priority INT -- Set protocol defined priority for sent packets.
3818 :reuseaddr BOOL -- Allow reusing a recently used local address
3819 (this is allowed by default for a server process).
3820 :bindtodevice NAME -- bind to interface NAME. Using this may require
3821 special privileges on some systems.
3822 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3823 been passed to Emacs. If Emacs wasn't
3824 passed a socket, this option is silently
3825 ignored.
3828 Consult the relevant system programmer's manual pages for more
3829 information on using these options.
3832 A server process will listen for and accept connections from clients.
3833 When a client connection is accepted, a new network process is created
3834 for the connection with the following parameters:
3836 - The client's process name is constructed by concatenating the server
3837 process's NAME and a client identification string.
3838 - If the FILTER argument is non-nil, the client process will not get a
3839 separate process buffer; otherwise, the client's process buffer is a newly
3840 created buffer named after the server process's BUFFER name or process
3841 NAME concatenated with the client identification string.
3842 - The connection type and the process filter and sentinel parameters are
3843 inherited from the server process's TYPE, FILTER and SENTINEL.
3844 - The client process's contact info is set according to the client's
3845 addressing information (typically an IP address and a port number).
3846 - The client process's plist is initialized from the server's plist.
3848 Notice that the FILTER and SENTINEL args are never used directly by
3849 the server process. Also, the BUFFER argument is not used directly by
3850 the server process, but via the optional :log function, accepted (and
3851 failed) connections may be logged in the server process's buffer.
3853 The original argument list, modified with the actual connection
3854 information, is available via the `process-contact' function.
3856 usage: (make-network-process &rest ARGS) */)
3857 (ptrdiff_t nargs, Lisp_Object *args)
3859 Lisp_Object proc;
3860 Lisp_Object contact;
3861 struct Lisp_Process *p;
3862 const char *portstring UNINIT;
3863 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3864 #ifdef HAVE_LOCAL_SOCKETS
3865 struct sockaddr_un address_un;
3866 #endif
3867 EMACS_INT port = 0;
3868 Lisp_Object tem;
3869 Lisp_Object name, buffer, host, service, address;
3870 Lisp_Object filter, sentinel, use_external_socket_p;
3871 Lisp_Object addrinfos = Qnil;
3872 int socktype;
3873 int family = -1;
3874 enum { any_protocol = 0 };
3875 #ifdef HAVE_GETADDRINFO_A
3876 struct gaicb *dns_request = NULL;
3877 #endif
3878 ptrdiff_t count = SPECPDL_INDEX ();
3880 if (nargs == 0)
3881 return Qnil;
3883 /* Save arguments for process-contact and clone-process. */
3884 contact = Flist (nargs, args);
3886 #ifdef WINDOWSNT
3887 /* Ensure socket support is loaded if available. */
3888 init_winsock (TRUE);
3889 #endif
3891 /* :type TYPE (nil: stream, datagram */
3892 tem = Fplist_get (contact, QCtype);
3893 if (NILP (tem))
3894 socktype = SOCK_STREAM;
3895 #ifdef DATAGRAM_SOCKETS
3896 else if (EQ (tem, Qdatagram))
3897 socktype = SOCK_DGRAM;
3898 #endif
3899 #ifdef HAVE_SEQPACKET
3900 else if (EQ (tem, Qseqpacket))
3901 socktype = SOCK_SEQPACKET;
3902 #endif
3903 else
3904 error ("Unsupported connection type");
3906 name = Fplist_get (contact, QCname);
3907 buffer = Fplist_get (contact, QCbuffer);
3908 filter = Fplist_get (contact, QCfilter);
3909 sentinel = Fplist_get (contact, QCsentinel);
3910 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3911 Lisp_Object server = Fplist_get (contact, QCserver);
3912 bool nowait = !NILP (Fplist_get (contact, QCnowait));
3914 if (!NILP (server) && nowait)
3915 error ("`:server' is incompatible with `:nowait'");
3916 CHECK_STRING (name);
3918 /* :local ADDRESS or :remote ADDRESS */
3919 if (NILP (server))
3920 address = Fplist_get (contact, QCremote);
3921 else
3922 address = Fplist_get (contact, QClocal);
3923 if (!NILP (address))
3925 host = service = Qnil;
3927 if (!get_lisp_to_sockaddr_size (address, &family))
3928 error ("Malformed :address");
3930 addrinfos = list1 (Fcons (make_fixnum (any_protocol), address));
3931 goto open_socket;
3934 /* :family FAMILY -- nil (for Inet), local, or integer. */
3935 tem = Fplist_get (contact, QCfamily);
3936 if (NILP (tem))
3938 #ifdef AF_INET6
3939 family = AF_UNSPEC;
3940 #else
3941 family = AF_INET;
3942 #endif
3944 #ifdef HAVE_LOCAL_SOCKETS
3945 else if (EQ (tem, Qlocal))
3946 family = AF_LOCAL;
3947 #endif
3948 #ifdef AF_INET6
3949 else if (EQ (tem, Qipv6))
3950 family = AF_INET6;
3951 #endif
3952 else if (EQ (tem, Qipv4))
3953 family = AF_INET;
3954 else if (TYPE_RANGED_FIXNUMP (int, tem))
3955 family = XFIXNUM (tem);
3956 else
3957 error ("Unknown address family");
3959 /* :service SERVICE -- string, integer (port number), or t (random port). */
3960 service = Fplist_get (contact, QCservice);
3962 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3963 host = Fplist_get (contact, QChost);
3964 if (NILP (host))
3966 /* The "connection" function gets it bind info from the address we're
3967 given, so use this dummy address if nothing is specified. */
3968 #ifdef HAVE_LOCAL_SOCKETS
3969 if (family != AF_LOCAL)
3970 #endif
3971 host = build_string ("127.0.0.1");
3973 else
3975 if (EQ (host, Qlocal))
3976 /* Depending on setup, "localhost" may map to different IPv4 and/or
3977 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3978 host = build_string ("127.0.0.1");
3979 CHECK_STRING (host);
3982 #ifdef HAVE_LOCAL_SOCKETS
3983 if (family == AF_LOCAL)
3985 if (!NILP (host))
3987 message (":family local ignores the :host property");
3988 contact = Fplist_put (contact, QChost, Qnil);
3989 host = Qnil;
3991 CHECK_STRING (service);
3992 if (sizeof address_un.sun_path <= SBYTES (service))
3993 error ("Service name too long");
3994 addrinfos = list1 (Fcons (make_fixnum (any_protocol), service));
3995 goto open_socket;
3997 #endif
3999 /* Slow down polling to every ten seconds.
4000 Some kernels have a bug which causes retrying connect to fail
4001 after a connect. Polling can interfere with gethostbyname too. */
4002 #ifdef POLL_FOR_INPUT
4003 if (socktype != SOCK_DGRAM)
4005 record_unwind_protect_void (run_all_atimers);
4006 bind_polling_period (10);
4008 #endif
4010 if (!NILP (host))
4012 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
4014 /* SERVICE can either be a string or int.
4015 Convert to a C string for later use by getaddrinfo. */
4016 if (EQ (service, Qt))
4018 portstring = "0";
4019 portstringlen = 1;
4021 else if (FIXNUMP (service))
4023 portstring = portbuf;
4024 portstringlen = sprintf (portbuf, "%"pI"d", XFIXNUM (service));
4026 else
4028 CHECK_STRING (service);
4029 portstring = SSDATA (service);
4030 portstringlen = SBYTES (service);
4033 #ifdef HAVE_GETADDRINFO_A
4034 if (nowait)
4036 ptrdiff_t hostlen = SBYTES (host);
4037 struct req
4039 struct gaicb gaicb;
4040 struct addrinfo hints;
4041 char str[FLEXIBLE_ARRAY_MEMBER];
4042 } *req = xmalloc (FLEXSIZEOF (struct req, str,
4043 hostlen + 1 + portstringlen + 1));
4044 dns_request = &req->gaicb;
4045 dns_request->ar_name = req->str;
4046 dns_request->ar_service = req->str + hostlen + 1;
4047 dns_request->ar_request = &req->hints;
4048 dns_request->ar_result = NULL;
4049 memset (&req->hints, 0, sizeof req->hints);
4050 req->hints.ai_family = family;
4051 req->hints.ai_socktype = socktype;
4052 strcpy (req->str, SSDATA (host));
4053 strcpy (req->str + hostlen + 1, portstring);
4055 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4056 if (ret)
4057 error ("%s/%s getaddrinfo_a error %d",
4058 SSDATA (host), portstring, ret);
4060 goto open_socket;
4062 #endif /* HAVE_GETADDRINFO_A */
4065 /* If we have a host, use getaddrinfo to resolve both host and service.
4066 Otherwise, use getservbyname to lookup the service. */
4068 if (!NILP (host))
4070 struct addrinfo *res, *lres;
4071 int ret;
4073 maybe_quit ();
4075 struct addrinfo hints;
4076 memset (&hints, 0, sizeof hints);
4077 hints.ai_family = family;
4078 hints.ai_socktype = socktype;
4080 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4081 if (ret)
4082 #ifdef HAVE_GAI_STRERROR
4084 synchronize_system_messages_locale ();
4085 char const *str = gai_strerror (ret);
4086 if (! NILP (Vlocale_coding_system))
4087 str = SSDATA (code_convert_string_norecord
4088 (build_string (str), Vlocale_coding_system, 0));
4089 error ("%s/%s %s", SSDATA (host), portstring, str);
4091 #else
4092 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4093 #endif
4095 for (lres = res; lres; lres = lres->ai_next)
4096 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4098 addrinfos = Fnreverse (addrinfos);
4100 freeaddrinfo (res);
4102 goto open_socket;
4105 /* No hostname has been specified (e.g., a local server process). */
4107 if (EQ (service, Qt))
4108 port = 0;
4109 else if (FIXNUMP (service))
4110 port = XFIXNUM (service);
4111 else
4113 CHECK_STRING (service);
4115 port = -1;
4116 if (SBYTES (service) != 0)
4118 /* Allow the service to be a string containing the port number,
4119 because that's allowed if you have getaddrbyname. */
4120 char *service_end;
4121 long int lport = strtol (SSDATA (service), &service_end, 10);
4122 if (service_end == SSDATA (service) + SBYTES (service))
4123 port = lport;
4124 else
4126 struct servent *svc_info
4127 = getservbyname (SSDATA (service),
4128 socktype == SOCK_DGRAM ? "udp" : "tcp");
4129 if (svc_info)
4130 port = ntohs (svc_info->s_port);
4135 if (! (0 <= port && port < 1 << 16))
4137 AUTO_STRING (unknown_service, "Unknown service: %s");
4138 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4141 open_socket:
4143 if (!NILP (buffer))
4144 buffer = Fget_buffer_create (buffer);
4146 /* Unwind bind_polling_period. */
4147 unbind_to (count, Qnil);
4149 proc = make_process (name);
4150 record_unwind_protect (remove_process, proc);
4151 p = XPROCESS (proc);
4152 pset_childp (p, contact);
4153 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4154 pset_type (p, Qnetwork);
4156 pset_buffer (p, buffer);
4157 pset_sentinel (p, sentinel);
4158 pset_filter (p, filter);
4159 pset_log (p, Fplist_get (contact, QClog));
4160 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4161 p->kill_without_query = 1;
4162 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4163 pset_command (p, Qt);
4164 eassert (p->pid == 0);
4165 p->backlog = 5;
4166 eassert (! p->is_non_blocking_client);
4167 eassert (! p->is_server);
4168 p->port = port;
4169 p->socktype = socktype;
4170 #ifdef HAVE_GETADDRINFO_A
4171 eassert (! p->dns_request);
4172 #endif
4173 #ifdef HAVE_GNUTLS
4174 tem = Fplist_get (contact, QCtls_parameters);
4175 CHECK_LIST (tem);
4176 p->gnutls_boot_parameters = tem;
4177 #endif
4179 set_network_socket_coding_system (proc, host, service, name);
4181 /* :server QLEN */
4182 p->is_server = !NILP (server);
4183 if (TYPE_RANGED_FIXNUMP (int, server))
4184 p->backlog = XFIXNUM (server);
4186 /* :nowait BOOL */
4187 if (!p->is_server && socktype != SOCK_DGRAM && nowait)
4188 p->is_non_blocking_client = true;
4190 bool postpone_connection = false;
4191 #ifdef HAVE_GETADDRINFO_A
4192 /* With async address resolution, the list of addresses is empty, so
4193 postpone connecting to the server. */
4194 if (!p->is_server && NILP (addrinfos))
4196 p->dns_request = dns_request;
4197 p->status = list1 (Qconnect);
4198 postpone_connection = true;
4200 #endif
4201 if (! postpone_connection)
4202 connect_network_socket (proc, addrinfos, use_external_socket_p);
4204 specpdl_ptr = specpdl + count;
4205 return proc;
4209 #ifdef HAVE_NET_IF_H
4211 #ifdef SIOCGIFCONF
4212 static Lisp_Object
4213 network_interface_list (void)
4215 struct ifconf ifconf;
4216 struct ifreq *ifreq;
4217 void *buf = NULL;
4218 ptrdiff_t buf_size = 512;
4219 int s;
4220 Lisp_Object res;
4221 ptrdiff_t count;
4223 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4224 if (s < 0)
4225 return Qnil;
4226 count = SPECPDL_INDEX ();
4227 record_unwind_protect_int (close_file_unwind, s);
4231 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4232 ifconf.ifc_buf = buf;
4233 ifconf.ifc_len = buf_size;
4234 if (ioctl (s, SIOCGIFCONF, &ifconf))
4236 emacs_close (s);
4237 xfree (buf);
4238 return Qnil;
4241 while (ifconf.ifc_len == buf_size);
4243 res = unbind_to (count, Qnil);
4244 ifreq = ifconf.ifc_req;
4245 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4247 struct ifreq *ifq = ifreq;
4248 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4249 #define SIZEOF_IFREQ(sif) \
4250 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4251 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4253 int len = SIZEOF_IFREQ (ifq);
4254 #else
4255 int len = sizeof (*ifreq);
4256 #endif
4257 char namebuf[sizeof (ifq->ifr_name) + 1];
4258 ifreq = (struct ifreq *) ((char *) ifreq + len);
4260 if (ifq->ifr_addr.sa_family != AF_INET)
4261 continue;
4263 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4264 namebuf[sizeof (ifq->ifr_name)] = 0;
4265 res = Fcons (Fcons (build_string (namebuf),
4266 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4267 sizeof (struct sockaddr))),
4268 res);
4271 xfree (buf);
4272 return res;
4274 #endif /* SIOCGIFCONF */
4276 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4278 struct ifflag_def {
4279 int flag_bit;
4280 const char *flag_sym;
4283 static const struct ifflag_def ifflag_table[] = {
4284 #ifdef IFF_UP
4285 { IFF_UP, "up" },
4286 #endif
4287 #ifdef IFF_BROADCAST
4288 { IFF_BROADCAST, "broadcast" },
4289 #endif
4290 #ifdef IFF_DEBUG
4291 { IFF_DEBUG, "debug" },
4292 #endif
4293 #ifdef IFF_LOOPBACK
4294 { IFF_LOOPBACK, "loopback" },
4295 #endif
4296 #ifdef IFF_POINTOPOINT
4297 { IFF_POINTOPOINT, "pointopoint" },
4298 #endif
4299 #ifdef IFF_RUNNING
4300 { IFF_RUNNING, "running" },
4301 #endif
4302 #ifdef IFF_NOARP
4303 { IFF_NOARP, "noarp" },
4304 #endif
4305 #ifdef IFF_PROMISC
4306 { IFF_PROMISC, "promisc" },
4307 #endif
4308 #ifdef IFF_NOTRAILERS
4309 #ifdef NS_IMPL_COCOA
4310 /* Really means smart, notrailers is obsolete. */
4311 { IFF_NOTRAILERS, "smart" },
4312 #else
4313 { IFF_NOTRAILERS, "notrailers" },
4314 #endif
4315 #endif
4316 #ifdef IFF_ALLMULTI
4317 { IFF_ALLMULTI, "allmulti" },
4318 #endif
4319 #ifdef IFF_MASTER
4320 { IFF_MASTER, "master" },
4321 #endif
4322 #ifdef IFF_SLAVE
4323 { IFF_SLAVE, "slave" },
4324 #endif
4325 #ifdef IFF_MULTICAST
4326 { IFF_MULTICAST, "multicast" },
4327 #endif
4328 #ifdef IFF_PORTSEL
4329 { IFF_PORTSEL, "portsel" },
4330 #endif
4331 #ifdef IFF_AUTOMEDIA
4332 { IFF_AUTOMEDIA, "automedia" },
4333 #endif
4334 #ifdef IFF_DYNAMIC
4335 { IFF_DYNAMIC, "dynamic" },
4336 #endif
4337 #ifdef IFF_OACTIVE
4338 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4339 #endif
4340 #ifdef IFF_SIMPLEX
4341 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4342 #endif
4343 #ifdef IFF_LINK0
4344 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4345 #endif
4346 #ifdef IFF_LINK1
4347 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4348 #endif
4349 #ifdef IFF_LINK2
4350 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4351 #endif
4352 { 0, 0 }
4355 static Lisp_Object
4356 network_interface_info (Lisp_Object ifname)
4358 struct ifreq rq;
4359 Lisp_Object res = Qnil;
4360 Lisp_Object elt;
4361 int s;
4362 bool any = 0;
4363 ptrdiff_t count;
4364 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4365 && defined HAVE_GETIFADDRS && defined LLADDR)
4366 struct ifaddrs *ifap;
4367 #endif
4369 CHECK_STRING (ifname);
4371 if (sizeof rq.ifr_name <= SBYTES (ifname))
4372 error ("interface name too long");
4373 lispstpcpy (rq.ifr_name, ifname);
4375 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4376 if (s < 0)
4377 return Qnil;
4378 count = SPECPDL_INDEX ();
4379 record_unwind_protect_int (close_file_unwind, s);
4381 elt = Qnil;
4382 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4383 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4385 int flags = rq.ifr_flags;
4386 const struct ifflag_def *fp;
4387 int fnum;
4389 /* If flags is smaller than int (i.e. short) it may have the high bit set
4390 due to IFF_MULTICAST. In that case, sign extending it into
4391 an int is wrong. */
4392 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4393 flags = (unsigned short) rq.ifr_flags;
4395 any = 1;
4396 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4398 if (flags & fp->flag_bit)
4400 elt = Fcons (intern (fp->flag_sym), elt);
4401 flags -= fp->flag_bit;
4404 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4406 if (flags & 1)
4408 elt = Fcons (make_fixnum (fnum), elt);
4412 #endif
4413 res = Fcons (elt, res);
4415 elt = Qnil;
4416 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4417 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4419 Lisp_Object hwaddr = Fmake_vector (make_fixnum (6), Qnil);
4420 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4421 int n;
4423 any = 1;
4424 for (n = 0; n < 6; n++)
4425 p->contents[n] = make_fixnum (((unsigned char *)
4426 &rq.ifr_hwaddr.sa_data[0])
4427 [n]);
4428 elt = Fcons (make_fixnum (rq.ifr_hwaddr.sa_family), hwaddr);
4430 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4431 if (getifaddrs (&ifap) != -1)
4433 Lisp_Object hwaddr = Fmake_vector (make_fixnum (6), Qnil);
4434 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4435 struct ifaddrs *it;
4437 for (it = ifap; it != NULL; it = it->ifa_next)
4439 DECLARE_POINTER_ALIAS (sdl, struct sockaddr_dl, it->ifa_addr);
4440 unsigned char linkaddr[6];
4441 int n;
4443 if (it->ifa_addr->sa_family != AF_LINK
4444 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4445 || sdl->sdl_alen != 6)
4446 continue;
4448 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4449 for (n = 0; n < 6; n++)
4450 p->contents[n] = make_fixnum (linkaddr[n]);
4452 elt = Fcons (make_fixnum (it->ifa_addr->sa_family), hwaddr);
4453 break;
4456 #ifdef HAVE_FREEIFADDRS
4457 freeifaddrs (ifap);
4458 #endif
4460 #endif /* HAVE_GETIFADDRS && LLADDR */
4462 res = Fcons (elt, res);
4464 elt = Qnil;
4465 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4466 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4468 any = 1;
4469 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4470 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4471 #else
4472 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4473 #endif
4475 #endif
4476 res = Fcons (elt, res);
4478 elt = Qnil;
4479 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4480 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4482 any = 1;
4483 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4485 #endif
4486 res = Fcons (elt, res);
4488 elt = Qnil;
4489 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4490 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4492 any = 1;
4493 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4495 #endif
4496 res = Fcons (elt, res);
4498 return unbind_to (count, any ? res : Qnil);
4500 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4501 #endif /* defined (HAVE_NET_IF_H) */
4503 DEFUN ("network-interface-list", Fnetwork_interface_list,
4504 Snetwork_interface_list, 0, 0, 0,
4505 doc: /* Return an alist of all network interfaces and their network address.
4506 Each element is a cons, the car of which is a string containing the
4507 interface name, and the cdr is the network address in internal
4508 format; see the description of ADDRESS in `make-network-process'.
4510 If the information is not available, return nil. */)
4511 (void)
4513 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4514 return network_interface_list ();
4515 #else
4516 return Qnil;
4517 #endif
4520 DEFUN ("network-interface-info", Fnetwork_interface_info,
4521 Snetwork_interface_info, 1, 1, 0,
4522 doc: /* Return information about network interface named IFNAME.
4523 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4524 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4525 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4526 FLAGS is the current flags of the interface.
4528 Data that is unavailable is returned as nil. */)
4529 (Lisp_Object ifname)
4531 #if ((defined HAVE_NET_IF_H \
4532 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4533 || defined SIOCGIFFLAGS)) \
4534 || defined WINDOWSNT)
4535 return network_interface_info (ifname);
4536 #else
4537 return Qnil;
4538 #endif
4541 /* Turn off input and output for process PROC. */
4543 static void
4544 deactivate_process (Lisp_Object proc)
4546 int inchannel;
4547 struct Lisp_Process *p = XPROCESS (proc);
4548 int i;
4550 #ifdef HAVE_GNUTLS
4551 /* Delete GnuTLS structures in PROC, if any. */
4552 emacs_gnutls_deinit (proc);
4553 #endif /* HAVE_GNUTLS */
4555 if (p->read_output_delay > 0)
4557 if (--process_output_delay_count < 0)
4558 process_output_delay_count = 0;
4559 p->read_output_delay = 0;
4560 p->read_output_skip = 0;
4563 /* Beware SIGCHLD hereabouts. */
4565 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4566 close_process_fd (&p->open_fd[i]);
4568 inchannel = p->infd;
4569 if (inchannel >= 0)
4571 p->infd = -1;
4572 p->outfd = -1;
4573 #ifdef DATAGRAM_SOCKETS
4574 if (DATAGRAM_CHAN_P (inchannel))
4576 xfree (datagram_address[inchannel].sa);
4577 datagram_address[inchannel].sa = 0;
4578 datagram_address[inchannel].len = 0;
4580 #endif
4581 chan_process[inchannel] = Qnil;
4582 delete_read_fd (inchannel);
4583 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4584 delete_write_fd (inchannel);
4585 if (inchannel == max_desc)
4586 recompute_max_desc ();
4591 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4592 0, 4, 0,
4593 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4594 It is given to their filter functions.
4595 Optional argument PROCESS means do not return until output has been
4596 received from PROCESS.
4598 Optional second argument SECONDS and third argument MILLISEC
4599 specify a timeout; return after that much time even if there is
4600 no subprocess output. If SECONDS is a floating point number,
4601 it specifies a fractional number of seconds to wait.
4602 The MILLISEC argument is obsolete and should be avoided.
4604 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4605 from PROCESS only, suspending reading output from other processes.
4606 If JUST-THIS-ONE is an integer, don't run any timers either.
4607 Return non-nil if we received any output from PROCESS (or, if PROCESS
4608 is nil, from any process) before the timeout expired. */)
4609 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4610 Lisp_Object just_this_one)
4612 intmax_t secs;
4613 int nsecs;
4615 if (! NILP (process))
4617 CHECK_PROCESS (process);
4618 struct Lisp_Process *proc = XPROCESS (process);
4620 /* Can't wait for a process that is dedicated to a different
4621 thread. */
4622 if (!NILP (proc->thread) && !EQ (proc->thread, Fcurrent_thread ()))
4624 Lisp_Object proc_thread_name = XTHREAD (proc->thread)->name;
4626 error ("Attempt to accept output from process %s locked to thread %s",
4627 SDATA (proc->name),
4628 STRINGP (proc_thread_name)
4629 ? SDATA (proc_thread_name)
4630 : SDATA (Fprin1_to_string (proc->thread, Qt)));
4633 else
4634 just_this_one = Qnil;
4636 if (!NILP (millisec))
4637 { /* Obsolete calling convention using integers rather than floats. */
4638 CHECK_FIXNUM (millisec);
4639 if (NILP (seconds))
4640 seconds = make_float (XFIXNUM (millisec) / 1000.0);
4641 else
4643 CHECK_FIXNUM (seconds);
4644 seconds = make_float (XFIXNUM (millisec) / 1000.0 + XFIXNUM (seconds));
4648 secs = 0;
4649 nsecs = -1;
4651 if (!NILP (seconds))
4653 if (FIXNUMP (seconds))
4655 if (XFIXNUM (seconds) > 0)
4657 secs = XFIXNUM (seconds);
4658 nsecs = 0;
4661 else if (FLOATP (seconds))
4663 if (XFLOAT_DATA (seconds) > 0)
4665 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4666 secs = min (t.tv_sec, WAIT_READING_MAX);
4667 nsecs = t.tv_nsec;
4670 else
4671 wrong_type_argument (Qnumberp, seconds);
4673 else if (! NILP (process))
4674 nsecs = 0;
4676 return
4677 ((wait_reading_process_output (secs, nsecs, 0, 0,
4678 Qnil,
4679 !NILP (process) ? XPROCESS (process) : NULL,
4680 (NILP (just_this_one) ? 0
4681 : !FIXNUMP (just_this_one) ? 1 : -1))
4682 <= 0)
4683 ? Qnil : Qt);
4686 /* Accept a connection for server process SERVER on CHANNEL. */
4688 static EMACS_INT connect_counter = 0;
4690 static void
4691 server_accept_connection (Lisp_Object server, int channel)
4693 Lisp_Object buffer;
4694 Lisp_Object contact, host, service;
4695 struct Lisp_Process *ps = XPROCESS (server);
4696 struct Lisp_Process *p;
4697 int s;
4698 union u_sockaddr saddr;
4699 socklen_t len = sizeof saddr;
4700 ptrdiff_t count;
4702 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4704 if (s < 0)
4706 int code = errno;
4707 if (!would_block (code) && !NILP (ps->log))
4708 call3 (ps->log, server, Qnil,
4709 concat3 (build_string ("accept failed with code"),
4710 Fnumber_to_string (make_fixnum (code)),
4711 build_string ("\n")));
4712 return;
4715 count = SPECPDL_INDEX ();
4716 record_unwind_protect_int (close_file_unwind, s);
4718 connect_counter++;
4720 /* Setup a new process to handle the connection. */
4722 /* Generate a unique identification of the caller, and build contact
4723 information for this process. */
4724 host = Qt;
4725 service = Qnil;
4726 Lisp_Object args[11];
4727 int nargs = 0;
4728 AUTO_STRING (procname_format_in, "%s <%d.%d.%d.%d:%d>");
4729 AUTO_STRING (procname_format_in6, "%s <[%x:%x:%x:%x:%x:%x:%x:%x]:%d>");
4730 AUTO_STRING (procname_format_default, "%s <%d>");
4731 switch (saddr.sa.sa_family)
4733 case AF_INET:
4735 args[nargs++] = procname_format_in;
4736 nargs++;
4737 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4738 service = make_fixnum (ntohs (saddr.in.sin_port));
4739 for (int i = 0; i < 4; i++)
4740 args[nargs++] = make_fixnum (ip[i]);
4741 args[nargs++] = service;
4743 break;
4745 #ifdef AF_INET6
4746 case AF_INET6:
4748 args[nargs++] = procname_format_in6;
4749 nargs++;
4750 DECLARE_POINTER_ALIAS (ip6, uint16_t, &saddr.in6.sin6_addr);
4751 service = make_fixnum (ntohs (saddr.in.sin_port));
4752 for (int i = 0; i < 8; i++)
4753 args[nargs++] = make_fixnum (ip6[i]);
4754 args[nargs++] = service;
4756 break;
4757 #endif
4759 default:
4760 args[nargs++] = procname_format_default;
4761 nargs++;
4762 args[nargs++] = make_fixnum (connect_counter);
4763 break;
4766 /* Create a new buffer name for this process if it doesn't have a
4767 filter. The new buffer name is based on the buffer name or
4768 process name of the server process concatenated with the caller
4769 identification. */
4771 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4772 || EQ (ps->filter, Qt)))
4773 buffer = Qnil;
4774 else
4776 buffer = ps->buffer;
4777 if (!NILP (buffer))
4778 buffer = Fbuffer_name (buffer);
4779 else
4780 buffer = ps->name;
4781 if (!NILP (buffer))
4783 args[1] = buffer;
4784 buffer = Fget_buffer_create (Fformat (nargs, args));
4788 /* Generate a unique name for the new server process. Combine the
4789 server process name with the caller identification. */
4791 args[1] = ps->name;
4792 Lisp_Object name = Fformat (nargs, args);
4793 Lisp_Object proc = make_process (name);
4795 chan_process[s] = proc;
4797 fcntl (s, F_SETFL, O_NONBLOCK);
4799 p = XPROCESS (proc);
4801 /* Build new contact information for this setup. */
4802 contact = Fcopy_sequence (ps->childp);
4803 contact = Fplist_put (contact, QCserver, Qnil);
4804 contact = Fplist_put (contact, QChost, host);
4805 if (!NILP (service))
4806 contact = Fplist_put (contact, QCservice, service);
4807 contact = Fplist_put (contact, QCremote,
4808 conv_sockaddr_to_lisp (&saddr.sa, len));
4809 #ifdef HAVE_GETSOCKNAME
4810 len = sizeof saddr;
4811 if (getsockname (s, &saddr.sa, &len) == 0)
4812 contact = Fplist_put (contact, QClocal,
4813 conv_sockaddr_to_lisp (&saddr.sa, len));
4814 #endif
4816 pset_childp (p, contact);
4817 pset_plist (p, Fcopy_sequence (ps->plist));
4818 pset_type (p, Qnetwork);
4820 pset_buffer (p, buffer);
4821 pset_sentinel (p, ps->sentinel);
4822 pset_filter (p, ps->filter);
4823 eassert (NILP (p->command));
4824 eassert (p->pid == 0);
4826 /* Discard the unwind protect for closing S. */
4827 specpdl_ptr = specpdl + count;
4829 p->open_fd[SUBPROCESS_STDIN] = s;
4830 p->infd = s;
4831 p->outfd = s;
4832 pset_status (p, Qrun);
4834 /* Client processes for accepted connections are not stopped initially. */
4835 if (!EQ (p->filter, Qt))
4836 add_process_read_fd (s);
4837 if (s > max_desc)
4838 max_desc = s;
4840 /* Setup coding system for new process based on server process.
4841 This seems to be the proper thing to do, as the coding system
4842 of the new process should reflect the settings at the time the
4843 server socket was opened; not the current settings. */
4845 pset_decode_coding_system (p, ps->decode_coding_system);
4846 pset_encode_coding_system (p, ps->encode_coding_system);
4847 setup_process_coding_systems (proc);
4849 pset_decoding_buf (p, empty_unibyte_string);
4850 eassert (p->decoding_carryover == 0);
4851 pset_encoding_buf (p, empty_unibyte_string);
4853 p->inherit_coding_system_flag
4854 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4856 AUTO_STRING (dash, "-");
4857 AUTO_STRING (nl, "\n");
4858 Lisp_Object host_string = STRINGP (host) ? host : dash;
4860 if (!NILP (ps->log))
4862 AUTO_STRING (accept_from, "accept from ");
4863 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4866 AUTO_STRING (open_from, "open from ");
4867 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4870 #ifdef HAVE_GETADDRINFO_A
4871 static Lisp_Object
4872 check_for_dns (Lisp_Object proc)
4874 struct Lisp_Process *p = XPROCESS (proc);
4875 Lisp_Object addrinfos = Qnil;
4877 /* Sanity check. */
4878 if (! p->dns_request)
4879 return Qnil;
4881 int ret = gai_error (p->dns_request);
4882 if (ret == EAI_INPROGRESS)
4883 return Qt;
4885 /* We got a response. */
4886 if (ret == 0)
4888 struct addrinfo *res;
4890 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4891 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4893 addrinfos = Fnreverse (addrinfos);
4895 /* The DNS lookup failed. */
4896 else if (connecting_status (p->status))
4898 deactivate_process (proc);
4899 pset_status (p, (list2
4900 (Qfailed,
4901 concat3 (build_string ("Name lookup of "),
4902 build_string (p->dns_request->ar_name),
4903 build_string (" failed")))));
4906 free_dns_request (proc);
4908 /* This process should not already be connected (or killed). */
4909 if (! connecting_status (p->status))
4910 return Qnil;
4912 return addrinfos;
4915 #endif /* HAVE_GETADDRINFO_A */
4917 static void
4918 wait_for_socket_fds (Lisp_Object process, char const *name)
4920 while (XPROCESS (process)->infd < 0
4921 && connecting_status (XPROCESS (process)->status))
4923 add_to_log ("Waiting for socket from %s...", build_string (name));
4924 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4928 static void
4929 wait_while_connecting (Lisp_Object process)
4931 while (connecting_status (XPROCESS (process)->status))
4933 add_to_log ("Waiting for connection...");
4934 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4938 static void
4939 wait_for_tls_negotiation (Lisp_Object process)
4941 #ifdef HAVE_GNUTLS
4942 while (XPROCESS (process)->gnutls_p
4943 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4945 add_to_log ("Waiting for TLS...");
4946 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4948 #endif
4951 static void
4952 wait_reading_process_output_unwind (int data)
4954 clear_waiting_thread_info ();
4955 waiting_for_user_input_p = data;
4958 /* This is here so breakpoints can be put on it. */
4959 static void
4960 wait_reading_process_output_1 (void)
4964 /* Read and dispose of subprocess output while waiting for timeout to
4965 elapse and/or keyboard input to be available.
4967 TIME_LIMIT is:
4968 timeout in seconds
4969 If negative, gobble data immediately available but don't wait for any.
4971 NSECS is:
4972 an additional duration to wait, measured in nanoseconds
4973 If TIME_LIMIT is zero, then:
4974 If NSECS == 0, there is no limit.
4975 If NSECS > 0, the timeout consists of NSECS only.
4976 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4978 READ_KBD is:
4979 0 to ignore keyboard input, or
4980 1 to return when input is available, or
4981 -1 meaning caller will actually read the input, so don't throw to
4982 the quit handler
4984 DO_DISPLAY means redisplay should be done to show subprocess
4985 output that arrives.
4987 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4988 (and gobble terminal input into the buffer if any arrives).
4990 If WAIT_PROC is specified, wait until something arrives from that
4991 process.
4993 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4994 (suspending output from other processes). A negative value
4995 means don't run any timers either.
4997 Return positive if we received input from WAIT_PROC (or from any
4998 process if WAIT_PROC is null), zero if we attempted to receive
4999 input but got none, and negative if we didn't even try. */
5002 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
5003 bool do_display,
5004 Lisp_Object wait_for_cell,
5005 struct Lisp_Process *wait_proc, int just_wait_proc)
5007 int channel, nfds;
5008 fd_set Available;
5009 fd_set Writeok;
5010 bool check_write;
5011 int check_delay;
5012 bool no_avail;
5013 int xerrno;
5014 Lisp_Object proc;
5015 struct timespec timeout, end_time, timer_delay;
5016 struct timespec got_output_end_time = invalid_timespec ();
5017 enum { MINIMUM = -1, TIMEOUT, FOREVER } wait;
5018 int got_some_output = -1;
5019 uintmax_t prev_wait_proc_nbytes_read = wait_proc ? wait_proc->nbytes_read : 0;
5020 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5021 bool retry_for_async;
5022 #endif
5023 ptrdiff_t count = SPECPDL_INDEX ();
5025 /* Close to the current time if known, an invalid timespec otherwise. */
5026 struct timespec now = invalid_timespec ();
5028 eassert (wait_proc == NULL
5029 || NILP (wait_proc->thread)
5030 || XTHREAD (wait_proc->thread) == current_thread);
5032 FD_ZERO (&Available);
5033 FD_ZERO (&Writeok);
5035 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
5036 && !(CONSP (wait_proc->status)
5037 && EQ (XCAR (wait_proc->status), Qexit)))
5038 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5040 record_unwind_protect_int (wait_reading_process_output_unwind,
5041 waiting_for_user_input_p);
5042 waiting_for_user_input_p = read_kbd;
5044 if (TYPE_MAXIMUM (time_t) < time_limit)
5045 time_limit = TYPE_MAXIMUM (time_t);
5047 if (time_limit < 0 || nsecs < 0)
5048 wait = MINIMUM;
5049 else if (time_limit > 0 || nsecs > 0)
5051 wait = TIMEOUT;
5052 now = current_timespec ();
5053 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5055 else
5056 wait = FOREVER;
5058 while (1)
5060 bool process_skipped = false;
5062 /* If calling from keyboard input, do not quit
5063 since we want to return C-g as an input character.
5064 Otherwise, do pending quit if requested. */
5065 if (read_kbd >= 0)
5066 maybe_quit ();
5067 else if (pending_signals)
5068 process_pending_signals ();
5070 /* Exit now if the cell we're waiting for became non-nil. */
5071 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5072 break;
5074 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5076 Lisp_Object process_list_head, aproc;
5077 struct Lisp_Process *p;
5079 retry_for_async = false;
5080 FOR_EACH_PROCESS(process_list_head, aproc)
5082 p = XPROCESS (aproc);
5084 if (! wait_proc || p == wait_proc)
5086 #ifdef HAVE_GETADDRINFO_A
5087 /* Check for pending DNS requests. */
5088 if (p->dns_request)
5090 Lisp_Object addrinfos = check_for_dns (aproc);
5091 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5092 connect_network_socket (aproc, addrinfos, Qnil);
5093 else
5094 retry_for_async = true;
5096 #endif
5097 #ifdef HAVE_GNUTLS
5098 /* Continue TLS negotiation. */
5099 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5100 && p->is_non_blocking_client)
5102 gnutls_try_handshake (p);
5103 p->gnutls_handshakes_tried++;
5105 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5107 gnutls_verify_boot (aproc, Qnil);
5108 finish_after_tls_connection (aproc);
5110 else
5112 retry_for_async = true;
5113 if (p->gnutls_handshakes_tried
5114 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5116 deactivate_process (aproc);
5117 pset_status (p, list2 (Qfailed,
5118 build_string ("TLS negotiation failed")));
5122 #endif
5126 #endif /* GETADDRINFO_A or GNUTLS */
5128 /* Compute time from now till when time limit is up. */
5129 /* Exit if already run out. */
5130 if (wait == TIMEOUT)
5132 if (!timespec_valid_p (now))
5133 now = current_timespec ();
5134 if (timespec_cmp (end_time, now) <= 0)
5135 break;
5136 timeout = timespec_sub (end_time, now);
5138 else
5139 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5141 /* Normally we run timers here.
5142 But not if wait_for_cell; in those cases,
5143 the wait is supposed to be short,
5144 and those callers cannot handle running arbitrary Lisp code here. */
5145 if (NILP (wait_for_cell)
5146 && just_wait_proc >= 0)
5150 unsigned old_timers_run = timers_run;
5151 struct buffer *old_buffer = current_buffer;
5152 Lisp_Object old_window = selected_window;
5154 timer_delay = timer_check ();
5156 /* If a timer has run, this might have changed buffers
5157 an alike. Make read_key_sequence aware of that. */
5158 if (timers_run != old_timers_run
5159 && (old_buffer != current_buffer
5160 || !EQ (old_window, selected_window))
5161 && waiting_for_user_input_p == -1)
5162 record_asynch_buffer_change ();
5164 if (timers_run != old_timers_run && do_display)
5165 /* We must retry, since a timer may have requeued itself
5166 and that could alter the time_delay. */
5167 redisplay_preserve_echo_area (9);
5168 else
5169 break;
5171 while (!detect_input_pending ());
5173 /* If there is unread keyboard input, also return. */
5174 if (read_kbd != 0
5175 && requeued_events_pending_p ())
5176 break;
5178 /* This is so a breakpoint can be put here. */
5179 if (!timespec_valid_p (timer_delay))
5180 wait_reading_process_output_1 ();
5183 /* Cause C-g and alarm signals to take immediate action,
5184 and cause input available signals to zero out timeout.
5186 It is important that we do this before checking for process
5187 activity. If we get a SIGCHLD after the explicit checks for
5188 process activity, timeout is the only way we will know. */
5189 if (read_kbd < 0)
5190 set_waiting_for_input (&timeout);
5192 /* If status of something has changed, and no input is
5193 available, notify the user of the change right away. After
5194 this explicit check, we'll let the SIGCHLD handler zap
5195 timeout to get our attention. */
5196 if (update_tick != process_tick)
5198 fd_set Atemp;
5199 fd_set Ctemp;
5201 if (kbd_on_hold_p ())
5202 FD_ZERO (&Atemp);
5203 else
5204 compute_input_wait_mask (&Atemp);
5205 compute_write_mask (&Ctemp);
5207 timeout = make_timespec (0, 0);
5208 if ((thread_select (pselect, max_desc + 1,
5209 &Atemp,
5210 (num_pending_connects > 0 ? &Ctemp : NULL),
5211 NULL, &timeout, NULL)
5212 <= 0))
5214 /* It's okay for us to do this and then continue with
5215 the loop, since timeout has already been zeroed out. */
5216 clear_waiting_for_input ();
5217 got_some_output = status_notify (NULL, wait_proc);
5218 if (do_display) redisplay_preserve_echo_area (13);
5222 /* Don't wait for output from a non-running process. Just
5223 read whatever data has already been received. */
5224 if (wait_proc && wait_proc->raw_status_new)
5225 update_status (wait_proc);
5226 if (wait_proc
5227 && ! EQ (wait_proc->status, Qrun)
5228 && ! connecting_status (wait_proc->status))
5230 bool read_some_bytes = false;
5232 clear_waiting_for_input ();
5234 /* If data can be read from the process, do so until exhausted. */
5235 if (wait_proc->infd >= 0)
5237 XSETPROCESS (proc, wait_proc);
5239 while (true)
5241 int nread = read_process_output (proc, wait_proc->infd);
5242 if (nread < 0)
5244 if (errno == EIO || would_block (errno))
5245 break;
5247 else
5249 if (got_some_output < nread)
5250 got_some_output = nread;
5251 if (nread == 0)
5252 break;
5253 read_some_bytes = true;
5258 if (read_some_bytes && do_display)
5259 redisplay_preserve_echo_area (10);
5261 break;
5264 /* Wait till there is something to do. */
5266 if (wait_proc && just_wait_proc)
5268 if (wait_proc->infd < 0) /* Terminated. */
5269 break;
5270 FD_SET (wait_proc->infd, &Available);
5271 check_delay = 0;
5272 check_write = 0;
5274 else if (!NILP (wait_for_cell))
5276 compute_non_process_wait_mask (&Available);
5277 check_delay = 0;
5278 check_write = 0;
5280 else
5282 if (! read_kbd)
5283 compute_non_keyboard_wait_mask (&Available);
5284 else
5285 compute_input_wait_mask (&Available);
5286 compute_write_mask (&Writeok);
5287 check_delay = wait_proc ? 0 : process_output_delay_count;
5288 check_write = true;
5291 /* If frame size has changed or the window is newly mapped,
5292 redisplay now, before we start to wait. There is a race
5293 condition here; if a SIGIO arrives between now and the select
5294 and indicates that a frame is trashed, the select may block
5295 displaying a trashed screen. */
5296 if (frame_garbaged && do_display)
5298 clear_waiting_for_input ();
5299 redisplay_preserve_echo_area (11);
5300 if (read_kbd < 0)
5301 set_waiting_for_input (&timeout);
5304 /* Skip the `select' call if input is available and we're
5305 waiting for keyboard input or a cell change (which can be
5306 triggered by processing X events). In the latter case, set
5307 nfds to 1 to avoid breaking the loop. */
5308 no_avail = 0;
5309 if ((read_kbd || !NILP (wait_for_cell))
5310 && detect_input_pending ())
5312 nfds = read_kbd ? 0 : 1;
5313 no_avail = 1;
5314 FD_ZERO (&Available);
5316 else
5318 /* Set the timeout for adaptive read buffering if any
5319 process has non-zero read_output_skip and non-zero
5320 read_output_delay, and we are not reading output for a
5321 specific process. It is not executed if
5322 Vprocess_adaptive_read_buffering is nil. */
5323 if (process_output_skip && check_delay > 0)
5325 int adaptive_nsecs = timeout.tv_nsec;
5326 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5327 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5328 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5330 proc = chan_process[channel];
5331 if (NILP (proc))
5332 continue;
5333 /* Find minimum non-zero read_output_delay among the
5334 processes with non-zero read_output_skip. */
5335 if (XPROCESS (proc)->read_output_delay > 0)
5337 check_delay--;
5338 if (!XPROCESS (proc)->read_output_skip)
5339 continue;
5340 FD_CLR (channel, &Available);
5341 process_skipped = true;
5342 XPROCESS (proc)->read_output_skip = 0;
5343 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5344 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5347 timeout = make_timespec (0, adaptive_nsecs);
5348 process_output_skip = 0;
5351 /* If we've got some output and haven't limited our timeout
5352 with adaptive read buffering, limit it. */
5353 if (got_some_output > 0 && !process_skipped
5354 && (timeout.tv_sec
5355 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5356 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5359 if (NILP (wait_for_cell) && just_wait_proc >= 0
5360 && timespec_valid_p (timer_delay)
5361 && timespec_cmp (timer_delay, timeout) < 0)
5363 if (!timespec_valid_p (now))
5364 now = current_timespec ();
5365 struct timespec timeout_abs = timespec_add (now, timeout);
5366 if (!timespec_valid_p (got_output_end_time)
5367 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5368 got_output_end_time = timeout_abs;
5369 timeout = timer_delay;
5371 else
5372 got_output_end_time = invalid_timespec ();
5374 /* NOW can become inaccurate if time can pass during pselect. */
5375 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5376 now = invalid_timespec ();
5378 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5379 if (retry_for_async
5380 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5382 timeout.tv_sec = 0;
5383 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5385 #endif
5387 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5388 #if defined HAVE_GLIB && !defined HAVE_NS
5389 nfds = xg_select (max_desc + 1,
5390 &Available, (check_write ? &Writeok : 0),
5391 NULL, &timeout, NULL);
5392 #elif defined HAVE_NS
5393 /* And NS builds call thread_select in ns_select. */
5394 nfds = ns_select (max_desc + 1,
5395 &Available, (check_write ? &Writeok : 0),
5396 NULL, &timeout, NULL);
5397 #else /* !HAVE_GLIB */
5398 nfds = thread_select (pselect, max_desc + 1,
5399 &Available,
5400 (check_write ? &Writeok : 0),
5401 NULL, &timeout, NULL);
5402 #endif /* !HAVE_GLIB */
5404 #ifdef HAVE_GNUTLS
5405 /* GnuTLS buffers data internally. In lowat mode it leaves
5406 some data in the TCP buffers so that select works, but
5407 with custom pull/push functions we need to check if some
5408 data is available in the buffers manually. */
5409 if (nfds == 0)
5411 fd_set tls_available;
5412 int set = 0;
5414 FD_ZERO (&tls_available);
5415 if (! wait_proc)
5417 /* We're not waiting on a specific process, so loop
5418 through all the channels and check for data.
5419 This is a workaround needed for some versions of
5420 the gnutls library -- 2.12.14 has been confirmed
5421 to need it. See
5422 http://comments.gmane.org/gmane.emacs.devel/145074 */
5423 for (channel = 0; channel < FD_SETSIZE; ++channel)
5424 if (! NILP (chan_process[channel]))
5426 struct Lisp_Process *p =
5427 XPROCESS (chan_process[channel]);
5428 if (p && p->gnutls_p && p->gnutls_state
5429 && ((emacs_gnutls_record_check_pending
5430 (p->gnutls_state))
5431 > 0))
5433 nfds++;
5434 eassert (p->infd == channel);
5435 FD_SET (p->infd, &tls_available);
5436 set++;
5440 else
5442 /* Check this specific channel. */
5443 if (wait_proc->gnutls_p /* Check for valid process. */
5444 && wait_proc->gnutls_state
5445 /* Do we have pending data? */
5446 && ((emacs_gnutls_record_check_pending
5447 (wait_proc->gnutls_state))
5448 > 0))
5450 nfds = 1;
5451 eassert (0 <= wait_proc->infd);
5452 /* Set to Available. */
5453 FD_SET (wait_proc->infd, &tls_available);
5454 set++;
5457 if (set)
5458 Available = tls_available;
5460 #endif
5463 xerrno = errno;
5465 /* Make C-g and alarm signals set flags again. */
5466 clear_waiting_for_input ();
5468 /* If we woke up due to SIGWINCH, actually change size now. */
5469 do_pending_window_change (0);
5471 if (nfds == 0)
5473 /* Exit the main loop if we've passed the requested timeout,
5474 or have read some bytes from our wait_proc (either directly
5475 in this call or indirectly through timers / process filters),
5476 or aren't skipping processes and got some output and
5477 haven't lowered our timeout due to timers or SIGIO and
5478 have waited a long amount of time due to repeated
5479 timers. */
5480 struct timespec huge_timespec
5481 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_HZ);
5482 struct timespec cmp_time = huge_timespec;
5483 if (wait < TIMEOUT
5484 || (wait_proc
5485 && wait_proc->nbytes_read != prev_wait_proc_nbytes_read))
5486 break;
5487 if (wait == TIMEOUT)
5488 cmp_time = end_time;
5489 if (!process_skipped && got_some_output > 0
5490 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5492 if (!timespec_valid_p (got_output_end_time))
5493 break;
5494 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5495 cmp_time = got_output_end_time;
5497 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5499 now = current_timespec ();
5500 if (timespec_cmp (cmp_time, now) <= 0)
5501 break;
5505 if (nfds < 0)
5507 if (xerrno == EINTR)
5508 no_avail = 1;
5509 else if (xerrno == EBADF)
5510 emacs_abort ();
5511 else
5512 report_file_errno ("Failed select", Qnil, xerrno);
5515 /* Check for keyboard input. */
5516 /* If there is any, return immediately
5517 to give it higher priority than subprocesses. */
5519 if (read_kbd != 0)
5521 unsigned old_timers_run = timers_run;
5522 struct buffer *old_buffer = current_buffer;
5523 Lisp_Object old_window = selected_window;
5524 bool leave = false;
5526 if (detect_input_pending_run_timers (do_display))
5528 swallow_events (do_display);
5529 if (detect_input_pending_run_timers (do_display))
5530 leave = true;
5533 /* If a timer has run, this might have changed buffers
5534 an alike. Make read_key_sequence aware of that. */
5535 if (timers_run != old_timers_run
5536 && waiting_for_user_input_p == -1
5537 && (old_buffer != current_buffer
5538 || !EQ (old_window, selected_window)))
5539 record_asynch_buffer_change ();
5541 if (leave)
5542 break;
5545 /* If there is unread keyboard input, also return. */
5546 if (read_kbd != 0
5547 && requeued_events_pending_p ())
5548 break;
5550 /* If we are not checking for keyboard input now,
5551 do process events (but don't run any timers).
5552 This is so that X events will be processed.
5553 Otherwise they may have to wait until polling takes place.
5554 That would causes delays in pasting selections, for example.
5556 (We used to do this only if wait_for_cell.) */
5557 if (read_kbd == 0 && detect_input_pending ())
5559 swallow_events (do_display);
5560 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5561 if (detect_input_pending ())
5562 break;
5563 #endif
5566 /* Exit now if the cell we're waiting for became non-nil. */
5567 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5568 break;
5570 #ifdef USABLE_SIGIO
5571 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5572 go read it. This can happen with X on BSD after logging out.
5573 In that case, there really is no input and no SIGIO,
5574 but select says there is input. */
5576 if (read_kbd && interrupt_input
5577 && keyboard_bit_set (&Available) && ! noninteractive)
5578 handle_input_available_signal (SIGIO);
5579 #endif
5581 /* If checking input just got us a size-change event from X,
5582 obey it now if we should. */
5583 if (read_kbd || ! NILP (wait_for_cell))
5584 do_pending_window_change (0);
5586 /* Check for data from a process. */
5587 if (no_avail || nfds == 0)
5588 continue;
5590 for (channel = 0; channel <= max_desc; ++channel)
5592 struct fd_callback_data *d = &fd_callback_info[channel];
5593 if (d->func
5594 && ((d->flags & FOR_READ
5595 && FD_ISSET (channel, &Available))
5596 || ((d->flags & FOR_WRITE)
5597 && FD_ISSET (channel, &Writeok))))
5598 d->func (channel, d->data);
5601 for (channel = 0; channel <= max_desc; channel++)
5603 if (FD_ISSET (channel, &Available)
5604 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5605 == PROCESS_FD))
5607 int nread;
5609 /* If waiting for this channel, arrange to return as
5610 soon as no more input to be processed. No more
5611 waiting. */
5612 proc = chan_process[channel];
5613 if (NILP (proc))
5614 continue;
5616 /* If this is a server stream socket, accept connection. */
5617 if (EQ (XPROCESS (proc)->status, Qlisten))
5619 server_accept_connection (proc, channel);
5620 continue;
5623 /* Read data from the process, starting with our
5624 buffered-ahead character if we have one. */
5626 nread = read_process_output (proc, channel);
5627 if ((!wait_proc || wait_proc == XPROCESS (proc))
5628 && got_some_output < nread)
5629 got_some_output = nread;
5630 if (nread > 0)
5632 /* Vacuum up any leftovers without waiting. */
5633 if (wait_proc == XPROCESS (proc))
5634 wait = MINIMUM;
5635 /* Since read_process_output can run a filter,
5636 which can call accept-process-output,
5637 don't try to read from any other processes
5638 before doing the select again. */
5639 FD_ZERO (&Available);
5641 if (do_display)
5642 redisplay_preserve_echo_area (12);
5644 else if (nread == -1 && would_block (errno))
5646 #ifdef HAVE_PTYS
5647 /* On some OSs with ptys, when the process on one end of
5648 a pty exits, the other end gets an error reading with
5649 errno = EIO instead of getting an EOF (0 bytes read).
5650 Therefore, if we get an error reading and errno =
5651 EIO, just continue, because the child process has
5652 exited and should clean itself up soon (e.g. when we
5653 get a SIGCHLD). */
5654 else if (nread == -1 && errno == EIO)
5656 struct Lisp_Process *p = XPROCESS (proc);
5658 /* Clear the descriptor now, so we only raise the
5659 signal once. */
5660 delete_read_fd (channel);
5662 if (p->pid == -2)
5664 /* If the EIO occurs on a pty, the SIGCHLD handler's
5665 waitpid call will not find the process object to
5666 delete. Do it here. */
5667 p->tick = ++process_tick;
5668 pset_status (p, Qfailed);
5671 #endif /* HAVE_PTYS */
5672 /* If we can detect process termination, don't consider the
5673 process gone just because its pipe is closed. */
5674 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5675 && !PIPECONN_P (proc))
5677 else if (nread == 0 && PIPECONN_P (proc))
5679 /* Preserve status of processes already terminated. */
5680 XPROCESS (proc)->tick = ++process_tick;
5681 deactivate_process (proc);
5682 if (EQ (XPROCESS (proc)->status, Qrun))
5683 pset_status (XPROCESS (proc),
5684 list2 (Qexit, make_fixnum (0)));
5686 else
5688 /* Preserve status of processes already terminated. */
5689 XPROCESS (proc)->tick = ++process_tick;
5690 deactivate_process (proc);
5691 if (XPROCESS (proc)->raw_status_new)
5692 update_status (XPROCESS (proc));
5693 if (EQ (XPROCESS (proc)->status, Qrun))
5694 pset_status (XPROCESS (proc),
5695 list2 (Qexit, make_fixnum (256)));
5698 if (FD_ISSET (channel, &Writeok)
5699 && (fd_callback_info[channel].flags
5700 & NON_BLOCKING_CONNECT_FD) != 0)
5702 struct Lisp_Process *p;
5704 delete_write_fd (channel);
5706 proc = chan_process[channel];
5707 if (NILP (proc))
5708 continue;
5710 p = XPROCESS (proc);
5712 #ifndef WINDOWSNT
5714 socklen_t xlen = sizeof (xerrno);
5715 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5716 xerrno = errno;
5718 #else
5719 /* On MS-Windows, getsockopt clears the error for the
5720 entire process, which may not be the right thing; see
5721 w32.c. Use getpeername instead. */
5723 struct sockaddr pname;
5724 socklen_t pnamelen = sizeof (pname);
5726 /* If connection failed, getpeername will fail. */
5727 xerrno = 0;
5728 if (getpeername (channel, &pname, &pnamelen) < 0)
5730 /* Obtain connect failure code through error slippage. */
5731 char dummy;
5732 xerrno = errno;
5733 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5734 xerrno = errno;
5737 #endif
5738 if (xerrno)
5740 Lisp_Object addrinfos
5741 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5742 if (!NILP (addrinfos))
5743 XSETCDR (p->status, XCDR (addrinfos));
5744 else
5746 p->tick = ++process_tick;
5747 pset_status (p, list2 (Qfailed, make_fixnum (xerrno)));
5749 deactivate_process (proc);
5750 if (!NILP (addrinfos))
5751 connect_network_socket (proc, addrinfos, Qnil);
5753 else
5755 #ifdef HAVE_GNUTLS
5756 /* If we have an incompletely set up TLS connection,
5757 then defer the sentinel signaling until
5758 later. */
5759 if (NILP (p->gnutls_boot_parameters)
5760 && !p->gnutls_p)
5761 #endif
5763 pset_status (p, Qrun);
5764 /* Execute the sentinel here. If we had relied on
5765 status_notify to do it later, it will read input
5766 from the process before calling the sentinel. */
5767 exec_sentinel (proc, build_string ("open\n"));
5770 if (0 <= p->infd && !EQ (p->filter, Qt)
5771 && !EQ (p->command, Qt))
5772 add_process_read_fd (p->infd);
5775 } /* End for each file descriptor. */
5776 } /* End while exit conditions not met. */
5778 unbind_to (count, Qnil);
5780 /* If calling from keyboard input, do not quit
5781 since we want to return C-g as an input character.
5782 Otherwise, do pending quit if requested. */
5783 if (read_kbd >= 0)
5785 /* Prevent input_pending from remaining set if we quit. */
5786 clear_input_pending ();
5787 maybe_quit ();
5790 /* Timers and/or process filters that we have run could have themselves called
5791 `accept-process-output' (and by that indirectly this function), thus
5792 possibly reading some (or all) output of wait_proc without us noticing it.
5793 This could potentially lead to an endless wait (dealt with earlier in the
5794 function) and/or a wrong return value (dealt with here). */
5795 if (wait_proc && wait_proc->nbytes_read != prev_wait_proc_nbytes_read)
5796 got_some_output = min (INT_MAX, (wait_proc->nbytes_read
5797 - prev_wait_proc_nbytes_read));
5799 return got_some_output;
5802 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5804 static Lisp_Object
5805 read_process_output_call (Lisp_Object fun_and_args)
5807 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5810 static Lisp_Object
5811 read_process_output_error_handler (Lisp_Object error_val)
5813 cmd_error_internal (error_val, "error in process filter: ");
5814 Vinhibit_quit = Qt;
5815 update_echo_area ();
5816 Fsleep_for (make_fixnum (2), Qnil);
5817 return Qt;
5820 static void
5821 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5822 ssize_t nbytes,
5823 struct coding_system *coding);
5825 /* Read pending output from the process channel,
5826 starting with our buffered-ahead character if we have one.
5827 Yield number of decoded characters read.
5829 This function reads at most 4096 characters.
5830 If you want to read all available subprocess output,
5831 you must call it repeatedly until it returns zero.
5833 The characters read are decoded according to PROC's coding-system
5834 for decoding. */
5836 static int
5837 read_process_output (Lisp_Object proc, int channel)
5839 ssize_t nbytes;
5840 struct Lisp_Process *p = XPROCESS (proc);
5841 struct coding_system *coding = proc_decode_coding_system[channel];
5842 int carryover = p->decoding_carryover;
5843 enum { readmax = 4096 };
5844 ptrdiff_t count = SPECPDL_INDEX ();
5845 Lisp_Object odeactivate;
5846 char chars[sizeof coding->carryover + readmax];
5848 if (carryover)
5849 /* See the comment above. */
5850 memcpy (chars, SDATA (p->decoding_buf), carryover);
5852 #ifdef DATAGRAM_SOCKETS
5853 /* We have a working select, so proc_buffered_char is always -1. */
5854 if (DATAGRAM_CHAN_P (channel))
5856 socklen_t len = datagram_address[channel].len;
5857 nbytes = recvfrom (channel, chars + carryover, readmax,
5858 0, datagram_address[channel].sa, &len);
5860 else
5861 #endif
5863 bool buffered = proc_buffered_char[channel] >= 0;
5864 if (buffered)
5866 chars[carryover] = proc_buffered_char[channel];
5867 proc_buffered_char[channel] = -1;
5869 #ifdef HAVE_GNUTLS
5870 if (p->gnutls_p && p->gnutls_state)
5871 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5872 readmax - buffered);
5873 else
5874 #endif
5875 nbytes = emacs_read (channel, chars + carryover + buffered,
5876 readmax - buffered);
5877 if (nbytes > 0 && p->adaptive_read_buffering)
5879 int delay = p->read_output_delay;
5880 if (nbytes < 256)
5882 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5884 if (delay == 0)
5885 process_output_delay_count++;
5886 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5889 else if (delay > 0 && nbytes == readmax - buffered)
5891 delay -= READ_OUTPUT_DELAY_INCREMENT;
5892 if (delay == 0)
5893 process_output_delay_count--;
5895 p->read_output_delay = delay;
5896 if (delay)
5898 p->read_output_skip = 1;
5899 process_output_skip = 1;
5902 nbytes += buffered;
5903 nbytes += buffered && nbytes <= 0;
5906 p->decoding_carryover = 0;
5908 /* At this point, NBYTES holds number of bytes just received
5909 (including the one in proc_buffered_char[channel]). */
5910 if (nbytes <= 0)
5912 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5913 return nbytes;
5914 coding->mode |= CODING_MODE_LAST_BLOCK;
5917 /* Ignore carryover, it's been added by a previous iteration already. */
5918 p->nbytes_read += nbytes;
5920 /* Now set NBYTES how many bytes we must decode. */
5921 nbytes += carryover;
5923 odeactivate = Vdeactivate_mark;
5924 /* There's no good reason to let process filters change the current
5925 buffer, and many callers of accept-process-output, sit-for, and
5926 friends don't expect current-buffer to be changed from under them. */
5927 record_unwind_current_buffer ();
5929 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5931 /* Handling the process output should not deactivate the mark. */
5932 Vdeactivate_mark = odeactivate;
5934 unbind_to (count, Qnil);
5935 return nbytes;
5938 static void
5939 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5940 ssize_t nbytes,
5941 struct coding_system *coding)
5943 Lisp_Object outstream = p->filter;
5944 Lisp_Object text;
5945 bool outer_running_asynch_code = running_asynch_code;
5946 int waiting = waiting_for_user_input_p;
5948 #if 0
5949 Lisp_Object obuffer, okeymap;
5950 XSETBUFFER (obuffer, current_buffer);
5951 okeymap = BVAR (current_buffer, keymap);
5952 #endif
5954 /* We inhibit quit here instead of just catching it so that
5955 hitting ^G when a filter happens to be running won't screw
5956 it up. */
5957 specbind (Qinhibit_quit, Qt);
5958 specbind (Qlast_nonmenu_event, Qt);
5960 /* In case we get recursively called,
5961 and we already saved the match data nonrecursively,
5962 save the same match data in safely recursive fashion. */
5963 if (outer_running_asynch_code)
5965 Lisp_Object tem;
5966 /* Don't clobber the CURRENT match data, either! */
5967 tem = Fmatch_data (Qnil, Qnil, Qnil);
5968 restore_search_regs ();
5969 record_unwind_save_match_data ();
5970 Fset_match_data (tem, Qt);
5973 /* For speed, if a search happens within this code,
5974 save the match data in a special nonrecursive fashion. */
5975 running_asynch_code = 1;
5977 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5978 text = coding->dst_object;
5979 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5980 /* A new coding system might be found. */
5981 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5983 pset_decode_coding_system (p, Vlast_coding_system_used);
5985 /* Don't call setup_coding_system for
5986 proc_decode_coding_system[channel] here. It is done in
5987 detect_coding called via decode_coding above. */
5989 /* If a coding system for encoding is not yet decided, we set
5990 it as the same as coding-system for decoding.
5992 But, before doing that we must check if
5993 proc_encode_coding_system[p->outfd] surely points to a
5994 valid memory because p->outfd will be changed once EOF is
5995 sent to the process. */
5996 if (NILP (p->encode_coding_system) && p->outfd >= 0
5997 && proc_encode_coding_system[p->outfd])
5999 pset_encode_coding_system
6000 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
6001 setup_coding_system (p->encode_coding_system,
6002 proc_encode_coding_system[p->outfd]);
6006 if (coding->carryover_bytes > 0)
6008 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
6009 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
6010 memcpy (SDATA (p->decoding_buf), coding->carryover,
6011 coding->carryover_bytes);
6012 p->decoding_carryover = coding->carryover_bytes;
6014 if (SBYTES (text) > 0)
6015 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6016 sometimes it's simply wrong to wrap (e.g. when called from
6017 accept-process-output). */
6018 internal_condition_case_1 (read_process_output_call,
6019 list3 (outstream, make_lisp_proc (p), text),
6020 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6021 read_process_output_error_handler);
6023 /* If we saved the match data nonrecursively, restore it now. */
6024 restore_search_regs ();
6025 running_asynch_code = outer_running_asynch_code;
6027 /* Restore waiting_for_user_input_p as it was
6028 when we were called, in case the filter clobbered it. */
6029 waiting_for_user_input_p = waiting;
6031 #if 0 /* Call record_asynch_buffer_change unconditionally,
6032 because we might have changed minor modes or other things
6033 that affect key bindings. */
6034 if (! EQ (Fcurrent_buffer (), obuffer)
6035 || ! EQ (current_buffer->keymap, okeymap))
6036 #endif
6037 /* But do it only if the caller is actually going to read events.
6038 Otherwise there's no need to make him wake up, and it could
6039 cause trouble (for example it would make sit_for return). */
6040 if (waiting_for_user_input_p == -1)
6041 record_asynch_buffer_change ();
6044 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
6045 Sinternal_default_process_filter, 2, 2, 0,
6046 doc: /* Function used as default process filter.
6047 This inserts the process's output into its buffer, if there is one.
6048 Otherwise it discards the output. */)
6049 (Lisp_Object proc, Lisp_Object text)
6051 struct Lisp_Process *p;
6052 ptrdiff_t opoint;
6054 CHECK_PROCESS (proc);
6055 p = XPROCESS (proc);
6056 CHECK_STRING (text);
6058 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6060 Lisp_Object old_read_only;
6061 ptrdiff_t old_begv, old_zv;
6062 ptrdiff_t old_begv_byte, old_zv_byte;
6063 ptrdiff_t before, before_byte;
6064 ptrdiff_t opoint_byte;
6065 struct buffer *b;
6067 Fset_buffer (p->buffer);
6068 opoint = PT;
6069 opoint_byte = PT_BYTE;
6070 old_read_only = BVAR (current_buffer, read_only);
6071 old_begv = BEGV;
6072 old_zv = ZV;
6073 old_begv_byte = BEGV_BYTE;
6074 old_zv_byte = ZV_BYTE;
6076 bset_read_only (current_buffer, Qnil);
6078 /* Insert new output into buffer at the current end-of-output
6079 marker, thus preserving logical ordering of input and output. */
6080 if (XMARKER (p->mark)->buffer)
6081 set_point_from_marker (p->mark);
6082 else
6083 SET_PT_BOTH (ZV, ZV_BYTE);
6084 before = PT;
6085 before_byte = PT_BYTE;
6087 /* If the output marker is outside of the visible region, save
6088 the restriction and widen. */
6089 if (! (BEGV <= PT && PT <= ZV))
6090 Fwiden ();
6092 /* Adjust the multibyteness of TEXT to that of the buffer. */
6093 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6094 != ! STRING_MULTIBYTE (text))
6095 text = (STRING_MULTIBYTE (text)
6096 ? Fstring_as_unibyte (text)
6097 : Fstring_to_multibyte (text));
6098 /* Insert before markers in case we are inserting where
6099 the buffer's mark is, and the user's next command is Meta-y. */
6100 insert_from_string_before_markers (text, 0, 0,
6101 SCHARS (text), SBYTES (text), 0);
6103 /* Make sure the process marker's position is valid when the
6104 process buffer is changed in the signal_after_change above.
6105 W3 is known to do that. */
6106 if (BUFFERP (p->buffer)
6107 && (b = XBUFFER (p->buffer), b != current_buffer))
6108 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6109 else
6110 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6112 update_mode_lines = 23;
6114 /* Make sure opoint and the old restrictions
6115 float ahead of any new text just as point would. */
6116 if (opoint >= before)
6118 opoint += PT - before;
6119 opoint_byte += PT_BYTE - before_byte;
6121 if (old_begv > before)
6123 old_begv += PT - before;
6124 old_begv_byte += PT_BYTE - before_byte;
6126 if (old_zv >= before)
6128 old_zv += PT - before;
6129 old_zv_byte += PT_BYTE - before_byte;
6132 /* If the restriction isn't what it should be, set it. */
6133 if (old_begv != BEGV || old_zv != ZV)
6134 Fnarrow_to_region (make_fixnum (old_begv), make_fixnum (old_zv));
6136 bset_read_only (current_buffer, old_read_only);
6137 SET_PT_BOTH (opoint, opoint_byte);
6139 return Qnil;
6142 /* Sending data to subprocess. */
6144 /* In send_process, when a write fails temporarily,
6145 wait_reading_process_output is called. It may execute user code,
6146 e.g. timers, that attempts to write new data to the same process.
6147 We must ensure that data is sent in the right order, and not
6148 interspersed half-completed with other writes (Bug#10815). This is
6149 handled by the write_queue element of struct process. It is a list
6150 with each entry having the form
6152 (string . (offset . length))
6154 where STRING is a lisp string, OFFSET is the offset into the
6155 string's byte sequence from which we should begin to send, and
6156 LENGTH is the number of bytes left to send. */
6158 /* Create a new entry in write_queue.
6159 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6160 BUF is a pointer to the string sequence of the input_obj or a C
6161 string in case of Qt or Qnil. */
6163 static void
6164 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6165 const char *buf, ptrdiff_t len, bool front)
6167 ptrdiff_t offset;
6168 Lisp_Object entry, obj;
6170 if (STRINGP (input_obj))
6172 offset = buf - SSDATA (input_obj);
6173 obj = input_obj;
6175 else
6177 offset = 0;
6178 obj = make_unibyte_string (buf, len);
6181 entry = Fcons (obj, Fcons (make_fixnum (offset), make_fixnum (len)));
6183 if (front)
6184 pset_write_queue (p, Fcons (entry, p->write_queue));
6185 else
6186 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6189 /* Remove the first element in the write_queue of process P, put its
6190 contents in OBJ, BUF and LEN, and return true. If the
6191 write_queue is empty, return false. */
6193 static bool
6194 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6195 const char **buf, ptrdiff_t *len)
6197 Lisp_Object entry, offset_length;
6198 ptrdiff_t offset;
6200 if (NILP (p->write_queue))
6201 return 0;
6203 entry = XCAR (p->write_queue);
6204 pset_write_queue (p, XCDR (p->write_queue));
6206 *obj = XCAR (entry);
6207 offset_length = XCDR (entry);
6209 *len = XFIXNUM (XCDR (offset_length));
6210 offset = XFIXNUM (XCAR (offset_length));
6211 *buf = SSDATA (*obj) + offset;
6213 return 1;
6216 /* Send some data to process PROC.
6217 BUF is the beginning of the data; LEN is the number of characters.
6218 OBJECT is the Lisp object that the data comes from. If OBJECT is
6219 nil or t, it means that the data comes from C string.
6221 If OBJECT is not nil, the data is encoded by PROC's coding-system
6222 for encoding before it is sent.
6224 This function can evaluate Lisp code and can garbage collect. */
6226 static void
6227 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6228 Lisp_Object object)
6230 struct Lisp_Process *p = XPROCESS (proc);
6231 ssize_t rv;
6232 struct coding_system *coding;
6234 if (NETCONN_P (proc))
6236 wait_while_connecting (proc);
6237 wait_for_tls_negotiation (proc);
6240 if (p->raw_status_new)
6241 update_status (p);
6242 if (! EQ (p->status, Qrun))
6243 error ("Process %s not running", SDATA (p->name));
6244 if (p->outfd < 0)
6245 error ("Output file descriptor of %s is closed", SDATA (p->name));
6247 coding = proc_encode_coding_system[p->outfd];
6248 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6250 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6251 || (BUFFERP (object)
6252 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6253 || EQ (object, Qt))
6255 pset_encode_coding_system
6256 (p, complement_process_encoding_system (p->encode_coding_system));
6257 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6259 /* The coding system for encoding was changed to raw-text
6260 because we sent a unibyte text previously. Now we are
6261 sending a multibyte text, thus we must encode it by the
6262 original coding system specified for the current process.
6264 Another reason we come here is that the coding system
6265 was just complemented and a new one was returned by
6266 complement_process_encoding_system. */
6267 setup_coding_system (p->encode_coding_system, coding);
6268 Vlast_coding_system_used = p->encode_coding_system;
6270 coding->src_multibyte = 1;
6272 else
6274 coding->src_multibyte = 0;
6275 /* For sending a unibyte text, character code conversion should
6276 not take place but EOL conversion should. So, setup raw-text
6277 or one of the subsidiary if we have not yet done it. */
6278 if (CODING_REQUIRE_ENCODING (coding))
6280 if (CODING_REQUIRE_FLUSHING (coding))
6282 /* But, before changing the coding, we must flush out data. */
6283 coding->mode |= CODING_MODE_LAST_BLOCK;
6284 send_process (proc, "", 0, Qt);
6285 coding->mode &= CODING_MODE_LAST_BLOCK;
6287 setup_coding_system (raw_text_coding_system
6288 (Vlast_coding_system_used),
6289 coding);
6290 coding->src_multibyte = 0;
6293 coding->dst_multibyte = 0;
6295 if (CODING_REQUIRE_ENCODING (coding))
6297 coding->dst_object = Qt;
6298 if (BUFFERP (object))
6300 ptrdiff_t from_byte, from, to;
6301 ptrdiff_t save_pt, save_pt_byte;
6302 struct buffer *cur = current_buffer;
6304 set_buffer_internal (XBUFFER (object));
6305 save_pt = PT, save_pt_byte = PT_BYTE;
6307 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6308 from = BYTE_TO_CHAR (from_byte);
6309 to = BYTE_TO_CHAR (from_byte + len);
6310 TEMP_SET_PT_BOTH (from, from_byte);
6311 encode_coding_object (coding, object, from, from_byte,
6312 to, from_byte + len, Qt);
6313 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6314 set_buffer_internal (cur);
6316 else if (STRINGP (object))
6318 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6319 SBYTES (object), Qt);
6321 else
6323 coding->dst_object = make_unibyte_string (buf, len);
6324 coding->produced = len;
6327 len = coding->produced;
6328 object = coding->dst_object;
6329 buf = SSDATA (object);
6332 /* If there is already data in the write_queue, put the new data
6333 in the back of queue. Otherwise, ignore it. */
6334 if (!NILP (p->write_queue))
6335 write_queue_push (p, object, buf, len, 0);
6337 do /* while !NILP (p->write_queue) */
6339 ptrdiff_t cur_len = -1;
6340 const char *cur_buf;
6341 Lisp_Object cur_object;
6343 /* If write_queue is empty, ignore it. */
6344 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6346 cur_len = len;
6347 cur_buf = buf;
6348 cur_object = object;
6351 while (cur_len > 0)
6353 /* Send this batch, using one or more write calls. */
6354 ptrdiff_t written = 0;
6355 int outfd = p->outfd;
6356 #ifdef DATAGRAM_SOCKETS
6357 if (DATAGRAM_CHAN_P (outfd))
6359 rv = sendto (outfd, cur_buf, cur_len,
6360 0, datagram_address[outfd].sa,
6361 datagram_address[outfd].len);
6362 if (rv >= 0)
6363 written = rv;
6364 else if (errno == EMSGSIZE)
6365 report_file_error ("Sending datagram", proc);
6367 else
6368 #endif
6370 #ifdef HAVE_GNUTLS
6371 if (p->gnutls_p && p->gnutls_state)
6372 written = emacs_gnutls_write (p, cur_buf, cur_len);
6373 else
6374 #endif
6375 written = emacs_write_sig (outfd, cur_buf, cur_len);
6376 rv = (written ? 0 : -1);
6377 if (p->read_output_delay > 0
6378 && p->adaptive_read_buffering == 1)
6380 p->read_output_delay = 0;
6381 process_output_delay_count--;
6382 p->read_output_skip = 0;
6386 if (rv < 0)
6388 if (would_block (errno))
6389 /* Buffer is full. Wait, accepting input;
6390 that may allow the program
6391 to finish doing output and read more. */
6393 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6394 /* A gross hack to work around a bug in FreeBSD.
6395 In the following sequence, read(2) returns
6396 bogus data:
6398 write(2) 1022 bytes
6399 write(2) 954 bytes, get EAGAIN
6400 read(2) 1024 bytes in process_read_output
6401 read(2) 11 bytes in process_read_output
6403 That is, read(2) returns more bytes than have
6404 ever been written successfully. The 1033 bytes
6405 read are the 1022 bytes written successfully
6406 after processing (for example with CRs added if
6407 the terminal is set up that way which it is
6408 here). The same bytes will be seen again in a
6409 later read(2), without the CRs. */
6411 if (errno == EAGAIN)
6413 int flags = FWRITE;
6414 ioctl (p->outfd, TIOCFLUSH, &flags);
6416 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6418 /* Put what we should have written in write_queue. */
6419 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6420 wait_reading_process_output (0, 20 * 1000 * 1000,
6421 0, 0, Qnil, NULL, 0);
6422 /* Reread queue, to see what is left. */
6423 break;
6425 else if (errno == EPIPE)
6427 p->raw_status_new = 0;
6428 pset_status (p, list2 (Qexit, make_fixnum (256)));
6429 p->tick = ++process_tick;
6430 deactivate_process (proc);
6431 error ("process %s no longer connected to pipe; closed it",
6432 SDATA (p->name));
6434 else
6435 /* This is a real error. */
6436 report_file_error ("Writing to process", proc);
6438 cur_buf += written;
6439 cur_len -= written;
6442 while (!NILP (p->write_queue));
6445 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6446 3, 3, 0,
6447 doc: /* Send current contents of region as input to PROCESS.
6448 PROCESS may be a process, a buffer, the name of a process or buffer, or
6449 nil, indicating the current buffer's process.
6450 Called from program, takes three arguments, PROCESS, START and END.
6451 If the region is more than 500 characters long,
6452 it is sent in several bunches. This may happen even for shorter regions.
6453 Output from processes can arrive in between bunches.
6455 If PROCESS is a non-blocking network process that hasn't been fully
6456 set up yet, this function will block until socket setup has completed. */)
6457 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6459 Lisp_Object proc = get_process (process);
6460 ptrdiff_t start_byte, end_byte;
6462 validate_region (&start, &end);
6464 start_byte = CHAR_TO_BYTE (XFIXNUM (start));
6465 end_byte = CHAR_TO_BYTE (XFIXNUM (end));
6467 if (XFIXNUM (start) < GPT && XFIXNUM (end) > GPT)
6468 move_gap_both (XFIXNUM (start), start_byte);
6470 if (NETCONN_P (proc))
6471 wait_while_connecting (proc);
6473 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6474 end_byte - start_byte, Fcurrent_buffer ());
6476 return Qnil;
6479 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6480 2, 2, 0,
6481 doc: /* Send PROCESS the contents of STRING as input.
6482 PROCESS may be a process, a buffer, the name of a process or buffer, or
6483 nil, indicating the current buffer's process.
6484 If STRING is more than 500 characters long,
6485 it is sent in several bunches. This may happen even for shorter strings.
6486 Output from processes can arrive in between bunches.
6488 If PROCESS is a non-blocking network process that hasn't been fully
6489 set up yet, this function will block until socket setup has completed. */)
6490 (Lisp_Object process, Lisp_Object string)
6492 CHECK_STRING (string);
6493 Lisp_Object proc = get_process (process);
6494 send_process (proc, SSDATA (string),
6495 SBYTES (string), string);
6496 return Qnil;
6499 /* Return the foreground process group for the tty/pty that
6500 the process P uses. */
6501 static pid_t
6502 emacs_get_tty_pgrp (struct Lisp_Process *p)
6504 pid_t gid = -1;
6506 #ifdef TIOCGPGRP
6507 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6509 int fd;
6510 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6511 master side. Try the slave side. */
6512 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6514 if (fd != -1)
6516 ioctl (fd, TIOCGPGRP, &gid);
6517 emacs_close (fd);
6520 #endif /* defined (TIOCGPGRP ) */
6522 return gid;
6525 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6526 Sprocess_running_child_p, 0, 1, 0,
6527 doc: /* Return non-nil if PROCESS has given the terminal to a
6528 child. If the operating system does not make it possible to find out,
6529 return t. If we can find out, return the numeric ID of the foreground
6530 process group. */)
6531 (Lisp_Object process)
6533 /* Initialize in case ioctl doesn't exist or gives an error,
6534 in a way that will cause returning t. */
6535 Lisp_Object proc = get_process (process);
6536 struct Lisp_Process *p = XPROCESS (proc);
6538 if (!EQ (p->type, Qreal))
6539 error ("Process %s is not a subprocess",
6540 SDATA (p->name));
6541 if (p->infd < 0)
6542 error ("Process %s is not active",
6543 SDATA (p->name));
6545 pid_t gid = emacs_get_tty_pgrp (p);
6547 if (gid == p->pid)
6548 return Qnil;
6549 if (gid != -1)
6550 return make_fixnum (gid);
6551 return Qt;
6554 /* Send a signal number SIGNO to PROCESS.
6555 If CURRENT_GROUP is t, that means send to the process group
6556 that currently owns the terminal being used to communicate with PROCESS.
6557 This is used for various commands in shell mode.
6558 If CURRENT_GROUP is lambda, that means send to the process group
6559 that currently owns the terminal, but only if it is NOT the shell itself.
6561 If NOMSG is false, insert signal-announcements into process's buffers
6562 right away.
6564 If we can, we try to signal PROCESS by sending control characters
6565 down the pty. This allows us to signal inferiors who have changed
6566 their uid, for which kill would return an EPERM error. */
6568 static void
6569 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6570 bool nomsg)
6572 Lisp_Object proc;
6573 struct Lisp_Process *p;
6574 pid_t gid;
6575 bool no_pgrp = 0;
6577 proc = get_process (process);
6578 p = XPROCESS (proc);
6580 if (!EQ (p->type, Qreal))
6581 error ("Process %s is not a subprocess",
6582 SDATA (p->name));
6583 if (p->infd < 0)
6584 error ("Process %s is not active",
6585 SDATA (p->name));
6587 if (!p->pty_flag)
6588 current_group = Qnil;
6590 /* If we are using pgrps, get a pgrp number and make it negative. */
6591 if (NILP (current_group))
6592 /* Send the signal to the shell's process group. */
6593 gid = p->pid;
6594 else
6596 #ifdef SIGNALS_VIA_CHARACTERS
6597 /* If possible, send signals to the entire pgrp
6598 by sending an input character to it. */
6600 struct termios t;
6601 cc_t *sig_char = NULL;
6603 tcgetattr (p->infd, &t);
6605 switch (signo)
6607 case SIGINT:
6608 sig_char = &t.c_cc[VINTR];
6609 break;
6611 case SIGQUIT:
6612 sig_char = &t.c_cc[VQUIT];
6613 break;
6615 case SIGTSTP:
6616 #ifdef VSWTCH
6617 sig_char = &t.c_cc[VSWTCH];
6618 #else
6619 sig_char = &t.c_cc[VSUSP];
6620 #endif
6621 break;
6624 if (sig_char && *sig_char != CDISABLE)
6626 send_process (proc, (char *) sig_char, 1, Qnil);
6627 return;
6629 /* If we can't send the signal with a character,
6630 fall through and send it another way. */
6632 /* The code above may fall through if it can't
6633 handle the signal. */
6634 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6636 #ifdef TIOCGPGRP
6637 /* Get the current pgrp using the tty itself, if we have that.
6638 Otherwise, use the pty to get the pgrp.
6639 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6640 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6641 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6642 His patch indicates that if TIOCGPGRP returns an error, then
6643 we should just assume that p->pid is also the process group id. */
6645 gid = emacs_get_tty_pgrp (p);
6647 if (gid == -1)
6648 /* If we can't get the information, assume
6649 the shell owns the tty. */
6650 gid = p->pid;
6652 /* It is not clear whether anything really can set GID to -1.
6653 Perhaps on some system one of those ioctls can or could do so.
6654 Or perhaps this is vestigial. */
6655 if (gid == -1)
6656 no_pgrp = 1;
6657 #else /* ! defined (TIOCGPGRP) */
6658 /* Can't select pgrps on this system, so we know that
6659 the child itself heads the pgrp. */
6660 gid = p->pid;
6661 #endif /* ! defined (TIOCGPGRP) */
6663 /* If current_group is lambda, and the shell owns the terminal,
6664 don't send any signal. */
6665 if (EQ (current_group, Qlambda) && gid == p->pid)
6666 return;
6669 #ifdef SIGCONT
6670 if (signo == SIGCONT)
6672 p->raw_status_new = 0;
6673 pset_status (p, Qrun);
6674 p->tick = ++process_tick;
6675 if (!nomsg)
6677 status_notify (NULL, NULL);
6678 redisplay_preserve_echo_area (13);
6681 #endif
6683 #ifdef TIOCSIGSEND
6684 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6685 We don't know whether the bug is fixed in later HP-UX versions. */
6686 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6687 return;
6688 #endif
6690 /* If we don't have process groups, send the signal to the immediate
6691 subprocess. That isn't really right, but it's better than any
6692 obvious alternative. */
6693 pid_t pid = no_pgrp ? gid : - gid;
6695 /* Do not kill an already-reaped process, as that could kill an
6696 innocent bystander that happens to have the same process ID. */
6697 sigset_t oldset;
6698 block_child_signal (&oldset);
6699 if (p->alive)
6700 kill (pid, signo);
6701 unblock_child_signal (&oldset);
6704 DEFUN ("internal-default-interrupt-process",
6705 Finternal_default_interrupt_process,
6706 Sinternal_default_interrupt_process, 0, 2, 0,
6707 doc: /* Default function to interrupt process PROCESS.
6708 It shall be the last element in list `interrupt-process-functions'.
6709 See function `interrupt-process' for more details on usage. */)
6710 (Lisp_Object process, Lisp_Object current_group)
6712 process_send_signal (process, SIGINT, current_group, 0);
6713 return process;
6716 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6717 doc: /* Interrupt process PROCESS.
6718 PROCESS may be a process, a buffer, or the name of a process or buffer.
6719 No arg or nil means current buffer's process.
6720 Second arg CURRENT-GROUP non-nil means send signal to
6721 the current process-group of the process's controlling terminal
6722 rather than to the process's own process group.
6723 If the process is a shell, this means interrupt current subjob
6724 rather than the shell.
6726 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6727 don't send the signal.
6729 This function calls the functions of `interrupt-process-functions' in
6730 the order of the list, until one of them returns non-`nil'. */)
6731 (Lisp_Object process, Lisp_Object current_group)
6733 return CALLN (Frun_hook_with_args_until_success, Qinterrupt_process_functions,
6734 process, current_group);
6737 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6738 doc: /* Kill process PROCESS. May be process or name of one.
6739 See function `interrupt-process' for more details on usage. */)
6740 (Lisp_Object process, Lisp_Object current_group)
6742 process_send_signal (process, SIGKILL, current_group, 0);
6743 return process;
6746 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6747 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6748 See function `interrupt-process' for more details on usage. */)
6749 (Lisp_Object process, Lisp_Object current_group)
6751 process_send_signal (process, SIGQUIT, current_group, 0);
6752 return process;
6755 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6756 doc: /* Stop process PROCESS. May be process or name of one.
6757 See function `interrupt-process' for more details on usage.
6758 If PROCESS is a network or serial or pipe connection, inhibit handling
6759 of incoming traffic. */)
6760 (Lisp_Object process, Lisp_Object current_group)
6762 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6763 || PIPECONN_P (process)))
6765 struct Lisp_Process *p;
6767 p = XPROCESS (process);
6768 if (NILP (p->command)
6769 && p->infd >= 0)
6770 delete_read_fd (p->infd);
6771 pset_command (p, Qt);
6772 return process;
6774 #ifndef SIGTSTP
6775 error ("No SIGTSTP support");
6776 #else
6777 process_send_signal (process, SIGTSTP, current_group, 0);
6778 #endif
6779 return process;
6782 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6783 doc: /* Continue process PROCESS. May be process or name of one.
6784 See function `interrupt-process' for more details on usage.
6785 If PROCESS is a network or serial process, resume handling of incoming
6786 traffic. */)
6787 (Lisp_Object process, Lisp_Object current_group)
6789 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6790 || PIPECONN_P (process)))
6792 struct Lisp_Process *p;
6794 p = XPROCESS (process);
6795 if (EQ (p->command, Qt)
6796 && p->infd >= 0
6797 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6799 add_process_read_fd (p->infd);
6800 #ifdef WINDOWSNT
6801 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6802 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6803 #else /* not WINDOWSNT */
6804 tcflush (p->infd, TCIFLUSH);
6805 #endif /* not WINDOWSNT */
6807 pset_command (p, Qnil);
6808 return process;
6810 #ifdef SIGCONT
6811 process_send_signal (process, SIGCONT, current_group, 0);
6812 #else
6813 error ("No SIGCONT support");
6814 #endif
6815 return process;
6818 /* Return the integer value of the signal whose abbreviation is ABBR,
6819 or a negative number if there is no such signal. */
6820 static int
6821 abbr_to_signal (char const *name)
6823 int i, signo;
6824 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6826 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6827 name += 3;
6829 for (i = 0; i < sizeof sigbuf; i++)
6831 sigbuf[i] = c_toupper (name[i]);
6832 if (! sigbuf[i])
6833 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6836 return -1;
6839 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6840 2, 2, "sProcess (name or number): \nnSignal code: ",
6841 doc: /* Send PROCESS the signal with code SIGCODE.
6842 PROCESS may also be a number specifying the process id of the
6843 process to signal; in this case, the process need not be a child of
6844 this Emacs.
6845 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6846 (Lisp_Object process, Lisp_Object sigcode)
6848 pid_t pid;
6849 int signo;
6851 if (STRINGP (process))
6853 Lisp_Object tem = Fget_process (process);
6854 if (NILP (tem))
6855 tem = string_to_number (SSDATA (process), 10, 0);
6856 process = tem;
6858 else if (!NUMBERP (process))
6859 process = get_process (process);
6861 if (NILP (process))
6862 return process;
6864 if (NUMBERP (process))
6865 CONS_TO_INTEGER (process, pid_t, pid);
6866 else
6868 CHECK_PROCESS (process);
6869 pid = XPROCESS (process)->pid;
6870 if (pid <= 0)
6871 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6874 if (FIXNUMP (sigcode))
6876 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6877 signo = XFIXNUM (sigcode);
6879 else
6881 char *name;
6883 CHECK_SYMBOL (sigcode);
6884 name = SSDATA (SYMBOL_NAME (sigcode));
6886 signo = abbr_to_signal (name);
6887 if (signo < 0)
6888 error ("Undefined signal name %s", name);
6891 return make_fixnum (kill (pid, signo));
6894 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6895 doc: /* Make PROCESS see end-of-file in its input.
6896 EOF comes after any text already sent to it.
6897 PROCESS may be a process, a buffer, the name of a process or buffer, or
6898 nil, indicating the current buffer's process.
6899 If PROCESS is a network connection, or is a process communicating
6900 through a pipe (as opposed to a pty), then you cannot send any more
6901 text to PROCESS after you call this function.
6902 If PROCESS is a serial process, wait until all output written to the
6903 process has been transmitted to the serial port. */)
6904 (Lisp_Object process)
6906 Lisp_Object proc;
6907 struct coding_system *coding = NULL;
6908 int outfd;
6910 proc = get_process (process);
6912 if (NETCONN_P (proc))
6913 wait_while_connecting (proc);
6915 if (DATAGRAM_CONN_P (proc))
6916 return process;
6919 outfd = XPROCESS (proc)->outfd;
6920 if (outfd >= 0)
6921 coding = proc_encode_coding_system[outfd];
6923 /* Make sure the process is really alive. */
6924 if (XPROCESS (proc)->raw_status_new)
6925 update_status (XPROCESS (proc));
6926 if (! EQ (XPROCESS (proc)->status, Qrun))
6927 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6929 if (coding && CODING_REQUIRE_FLUSHING (coding))
6931 coding->mode |= CODING_MODE_LAST_BLOCK;
6932 send_process (proc, "", 0, Qnil);
6935 if (XPROCESS (proc)->pty_flag)
6936 send_process (proc, "\004", 1, Qnil);
6937 else if (EQ (XPROCESS (proc)->type, Qserial))
6939 #ifndef WINDOWSNT
6940 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6941 report_file_error ("Failed tcdrain", Qnil);
6942 #endif /* not WINDOWSNT */
6943 /* Do nothing on Windows because writes are blocking. */
6945 else
6947 struct Lisp_Process *p = XPROCESS (proc);
6948 int old_outfd = p->outfd;
6949 int new_outfd;
6951 #ifdef HAVE_SHUTDOWN
6952 /* If this is a network connection, or socketpair is used
6953 for communication with the subprocess, call shutdown to cause EOF.
6954 (In some old system, shutdown to socketpair doesn't work.
6955 Then we just can't win.) */
6956 if (0 <= old_outfd
6957 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6958 shutdown (old_outfd, 1);
6959 #endif
6960 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6961 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6962 if (new_outfd < 0)
6963 report_file_error ("Opening null device", Qnil);
6964 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6965 p->outfd = new_outfd;
6967 if (!proc_encode_coding_system[new_outfd])
6968 proc_encode_coding_system[new_outfd]
6969 = xmalloc (sizeof (struct coding_system));
6970 if (old_outfd >= 0)
6972 *proc_encode_coding_system[new_outfd]
6973 = *proc_encode_coding_system[old_outfd];
6974 memset (proc_encode_coding_system[old_outfd], 0,
6975 sizeof (struct coding_system));
6977 else
6978 setup_coding_system (p->encode_coding_system,
6979 proc_encode_coding_system[new_outfd]);
6981 return process;
6984 /* The main Emacs thread records child processes in three places:
6986 - Vprocess_alist, for asynchronous subprocesses, which are child
6987 processes visible to Lisp.
6989 - deleted_pid_list, for child processes invisible to Lisp,
6990 typically because of delete-process. These are recorded so that
6991 the processes can be reaped when they exit, so that the operating
6992 system's process table is not cluttered by zombies.
6994 - the local variable PID in Fcall_process, call_process_cleanup and
6995 call_process_kill, for synchronous subprocesses.
6996 record_unwind_protect is used to make sure this process is not
6997 forgotten: if the user interrupts call-process and the child
6998 process refuses to exit immediately even with two C-g's,
6999 call_process_kill adds PID's contents to deleted_pid_list before
7000 returning.
7002 The main Emacs thread invokes waitpid only on child processes that
7003 it creates and that have not been reaped. This avoid races on
7004 platforms such as GTK, where other threads create their own
7005 subprocesses which the main thread should not reap. For example,
7006 if the main thread attempted to reap an already-reaped child, it
7007 might inadvertently reap a GTK-created process that happened to
7008 have the same process ID. */
7010 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7011 its own SIGCHLD handling. On POSIXish systems, glib needs this to
7012 keep track of its own children. GNUstep is similar. */
7014 static void dummy_handler (int sig) {}
7015 static signal_handler_t volatile lib_child_handler;
7017 /* Handle a SIGCHLD signal by looking for known child processes of
7018 Emacs whose status have changed. For each one found, record its
7019 new status.
7021 All we do is change the status; we do not run sentinels or print
7022 notifications. That is saved for the next time keyboard input is
7023 done, in order to avoid timing errors.
7025 ** WARNING: this can be called during garbage collection.
7026 Therefore, it must not be fooled by the presence of mark bits in
7027 Lisp objects.
7029 ** USG WARNING: Although it is not obvious from the documentation
7030 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7031 signal() before executing at least one wait(), otherwise the
7032 handler will be called again, resulting in an infinite loop. The
7033 relevant portion of the documentation reads "SIGCLD signals will be
7034 queued and the signal-catching function will be continually
7035 reentered until the queue is empty". Invoking signal() causes the
7036 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7037 Inc.
7039 ** Malloc WARNING: This should never call malloc either directly or
7040 indirectly; if it does, that is a bug. */
7042 static void
7043 handle_child_signal (int sig)
7045 Lisp_Object tail, proc;
7047 /* Find the process that signaled us, and record its status. */
7049 /* The process can have been deleted by Fdelete_process, or have
7050 been started asynchronously by Fcall_process. */
7051 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
7053 bool all_pids_are_fixnums
7054 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
7055 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
7056 Lisp_Object head = XCAR (tail);
7057 Lisp_Object xpid;
7058 if (! CONSP (head))
7059 continue;
7060 xpid = XCAR (head);
7061 if (all_pids_are_fixnums ? FIXNUMP (xpid) : INTEGERP (xpid))
7063 intmax_t deleted_pid;
7064 bool ok = integer_to_intmax (xpid, &deleted_pid);
7065 eassert (ok);
7066 if (child_status_changed (deleted_pid, 0, 0))
7068 if (STRINGP (XCDR (head)))
7069 unlink (SSDATA (XCDR (head)));
7070 XSETCAR (tail, Qnil);
7075 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7076 FOR_EACH_PROCESS (tail, proc)
7078 struct Lisp_Process *p = XPROCESS (proc);
7079 int status;
7081 if (p->alive
7082 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7084 /* Change the status of the process that was found. */
7085 p->tick = ++process_tick;
7086 p->raw_status = status;
7087 p->raw_status_new = 1;
7089 /* If process has terminated, stop waiting for its output. */
7090 if (WIFSIGNALED (status) || WIFEXITED (status))
7092 bool clear_desc_flag = 0;
7093 p->alive = 0;
7094 if (p->infd >= 0)
7095 clear_desc_flag = 1;
7097 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7098 if (clear_desc_flag)
7099 delete_read_fd (p->infd);
7104 lib_child_handler (sig);
7105 #ifdef NS_IMPL_GNUSTEP
7106 /* NSTask in GNUstep sets its child handler each time it is called.
7107 So we must re-set ours. */
7108 catch_child_signal ();
7109 #endif
7112 static void
7113 deliver_child_signal (int sig)
7115 deliver_process_signal (sig, handle_child_signal);
7119 static Lisp_Object
7120 exec_sentinel_error_handler (Lisp_Object error_val)
7122 /* Make sure error_val is a cons cell, as all the rest of error
7123 handling expects that, and will barf otherwise. */
7124 if (!CONSP (error_val))
7125 error_val = Fcons (Qerror, error_val);
7126 cmd_error_internal (error_val, "error in process sentinel: ");
7127 Vinhibit_quit = Qt;
7128 update_echo_area ();
7129 Fsleep_for (make_fixnum (2), Qnil);
7130 return Qt;
7133 static void
7134 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7136 Lisp_Object sentinel, odeactivate;
7137 struct Lisp_Process *p = XPROCESS (proc);
7138 ptrdiff_t count = SPECPDL_INDEX ();
7139 bool outer_running_asynch_code = running_asynch_code;
7140 int waiting = waiting_for_user_input_p;
7142 if (inhibit_sentinels)
7143 return;
7145 odeactivate = Vdeactivate_mark;
7146 #if 0
7147 Lisp_Object obuffer, okeymap;
7148 XSETBUFFER (obuffer, current_buffer);
7149 okeymap = BVAR (current_buffer, keymap);
7150 #endif
7152 /* There's no good reason to let sentinels change the current
7153 buffer, and many callers of accept-process-output, sit-for, and
7154 friends don't expect current-buffer to be changed from under them. */
7155 record_unwind_current_buffer ();
7157 sentinel = p->sentinel;
7159 /* Inhibit quit so that random quits don't screw up a running filter. */
7160 specbind (Qinhibit_quit, Qt);
7161 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7163 /* In case we get recursively called,
7164 and we already saved the match data nonrecursively,
7165 save the same match data in safely recursive fashion. */
7166 if (outer_running_asynch_code)
7168 Lisp_Object tem;
7169 tem = Fmatch_data (Qnil, Qnil, Qnil);
7170 restore_search_regs ();
7171 record_unwind_save_match_data ();
7172 Fset_match_data (tem, Qt);
7175 /* For speed, if a search happens within this code,
7176 save the match data in a special nonrecursive fashion. */
7177 running_asynch_code = 1;
7179 internal_condition_case_1 (read_process_output_call,
7180 list3 (sentinel, proc, reason),
7181 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7182 exec_sentinel_error_handler);
7184 /* If we saved the match data nonrecursively, restore it now. */
7185 restore_search_regs ();
7186 running_asynch_code = outer_running_asynch_code;
7188 Vdeactivate_mark = odeactivate;
7190 /* Restore waiting_for_user_input_p as it was
7191 when we were called, in case the filter clobbered it. */
7192 waiting_for_user_input_p = waiting;
7194 #if 0
7195 if (! EQ (Fcurrent_buffer (), obuffer)
7196 || ! EQ (current_buffer->keymap, okeymap))
7197 #endif
7198 /* But do it only if the caller is actually going to read events.
7199 Otherwise there's no need to make him wake up, and it could
7200 cause trouble (for example it would make sit_for return). */
7201 if (waiting_for_user_input_p == -1)
7202 record_asynch_buffer_change ();
7204 unbind_to (count, Qnil);
7207 /* Report all recent events of a change in process status
7208 (either run the sentinel or output a message).
7209 This is usually done while Emacs is waiting for keyboard input
7210 but can be done at other times.
7212 Return positive if any input was received from WAIT_PROC (or from
7213 any process if WAIT_PROC is null), zero if input was attempted but
7214 none received, and negative if we didn't even try. */
7216 static int
7217 status_notify (struct Lisp_Process *deleting_process,
7218 struct Lisp_Process *wait_proc)
7220 Lisp_Object proc;
7221 Lisp_Object tail, msg;
7222 int got_some_output = -1;
7224 tail = Qnil;
7225 msg = Qnil;
7227 /* Set this now, so that if new processes are created by sentinels
7228 that we run, we get called again to handle their status changes. */
7229 update_tick = process_tick;
7231 FOR_EACH_PROCESS (tail, proc)
7233 Lisp_Object symbol;
7234 register struct Lisp_Process *p = XPROCESS (proc);
7236 if (p->tick != p->update_tick)
7238 p->update_tick = p->tick;
7240 /* If process is still active, read any output that remains. */
7241 while (! EQ (p->filter, Qt)
7242 && ! connecting_status (p->status)
7243 && ! EQ (p->status, Qlisten)
7244 /* Network or serial process not stopped: */
7245 && ! EQ (p->command, Qt)
7246 && p->infd >= 0
7247 && p != deleting_process)
7249 int nread = read_process_output (proc, p->infd);
7250 if ((!wait_proc || wait_proc == XPROCESS (proc))
7251 && got_some_output < nread)
7252 got_some_output = nread;
7253 if (nread <= 0)
7254 break;
7257 /* Get the text to use for the message. */
7258 if (p->raw_status_new)
7259 update_status (p);
7260 msg = status_message (p);
7262 /* If process is terminated, deactivate it or delete it. */
7263 symbol = p->status;
7264 if (CONSP (p->status))
7265 symbol = XCAR (p->status);
7267 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7268 || EQ (symbol, Qclosed))
7270 if (delete_exited_processes)
7271 remove_process (proc);
7272 else
7273 deactivate_process (proc);
7276 /* The actions above may have further incremented p->tick.
7277 So set p->update_tick again so that an error in the sentinel will
7278 not cause this code to be run again. */
7279 p->update_tick = p->tick;
7280 /* Now output the message suitably. */
7281 exec_sentinel (proc, msg);
7282 if (BUFFERP (p->buffer))
7283 /* In case it uses %s in mode-line-format. */
7284 bset_update_mode_line (XBUFFER (p->buffer));
7286 } /* end for */
7288 return got_some_output;
7291 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7292 Sinternal_default_process_sentinel, 2, 2, 0,
7293 doc: /* Function used as default sentinel for processes.
7294 This inserts a status message into the process's buffer, if there is one. */)
7295 (Lisp_Object proc, Lisp_Object msg)
7297 Lisp_Object buffer, symbol;
7298 struct Lisp_Process *p;
7299 CHECK_PROCESS (proc);
7300 p = XPROCESS (proc);
7301 buffer = p->buffer;
7302 symbol = p->status;
7303 if (CONSP (symbol))
7304 symbol = XCAR (symbol);
7306 if (!EQ (symbol, Qrun) && !NILP (buffer))
7308 Lisp_Object tem;
7309 struct buffer *old = current_buffer;
7310 ptrdiff_t opoint, opoint_byte;
7311 ptrdiff_t before, before_byte;
7313 /* Avoid error if buffer is deleted
7314 (probably that's why the process is dead, too). */
7315 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7316 return Qnil;
7317 Fset_buffer (buffer);
7319 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7320 msg = (code_convert_string_norecord
7321 (msg, Vlocale_coding_system, 1));
7323 opoint = PT;
7324 opoint_byte = PT_BYTE;
7325 /* Insert new output into buffer
7326 at the current end-of-output marker,
7327 thus preserving logical ordering of input and output. */
7328 if (XMARKER (p->mark)->buffer)
7329 Fgoto_char (p->mark);
7330 else
7331 SET_PT_BOTH (ZV, ZV_BYTE);
7333 before = PT;
7334 before_byte = PT_BYTE;
7336 tem = BVAR (current_buffer, read_only);
7337 bset_read_only (current_buffer, Qnil);
7338 insert_string ("\nProcess ");
7339 { /* FIXME: temporary kludge. */
7340 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7341 insert_string (" ");
7342 Finsert (1, &msg);
7343 bset_read_only (current_buffer, tem);
7344 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7346 if (opoint >= before)
7347 SET_PT_BOTH (opoint + (PT - before),
7348 opoint_byte + (PT_BYTE - before_byte));
7349 else
7350 SET_PT_BOTH (opoint, opoint_byte);
7352 set_buffer_internal (old);
7354 return Qnil;
7358 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7359 Sset_process_coding_system, 1, 3, 0,
7360 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7361 DECODING will be used to decode subprocess output and ENCODING to
7362 encode subprocess input. */)
7363 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7365 CHECK_PROCESS (process);
7367 struct Lisp_Process *p = XPROCESS (process);
7369 Fcheck_coding_system (decoding);
7370 Fcheck_coding_system (encoding);
7371 encoding = coding_inherit_eol_type (encoding, Qnil);
7372 pset_decode_coding_system (p, decoding);
7373 pset_encode_coding_system (p, encoding);
7375 /* If the sockets haven't been set up yet, the final setup part of
7376 this will be called asynchronously. */
7377 if (p->infd < 0 || p->outfd < 0)
7378 return Qnil;
7380 setup_process_coding_systems (process);
7382 return Qnil;
7385 DEFUN ("process-coding-system",
7386 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7387 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7388 (register Lisp_Object process)
7390 CHECK_PROCESS (process);
7391 return Fcons (XPROCESS (process)->decode_coding_system,
7392 XPROCESS (process)->encode_coding_system);
7395 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7396 Sset_process_filter_multibyte, 2, 2, 0,
7397 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7398 If FLAG is non-nil, the filter is given multibyte strings.
7399 If FLAG is nil, the filter is given unibyte strings. In this case,
7400 all character code conversion except for end-of-line conversion is
7401 suppressed. */)
7402 (Lisp_Object process, Lisp_Object flag)
7404 CHECK_PROCESS (process);
7406 struct Lisp_Process *p = XPROCESS (process);
7407 if (NILP (flag))
7408 pset_decode_coding_system
7409 (p, raw_text_coding_system (p->decode_coding_system));
7411 /* If the sockets haven't been set up yet, the final setup part of
7412 this will be called asynchronously. */
7413 if (p->infd < 0 || p->outfd < 0)
7414 return Qnil;
7416 setup_process_coding_systems (process);
7418 return Qnil;
7421 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7422 Sprocess_filter_multibyte_p, 1, 1, 0,
7423 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7424 (Lisp_Object process)
7426 CHECK_PROCESS (process);
7427 struct Lisp_Process *p = XPROCESS (process);
7428 if (p->infd < 0)
7429 return Qnil;
7430 struct coding_system *coding = proc_decode_coding_system[p->infd];
7431 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7437 # ifdef HAVE_GPM
7439 void
7440 add_gpm_wait_descriptor (int desc)
7442 add_keyboard_wait_descriptor (desc);
7445 void
7446 delete_gpm_wait_descriptor (int desc)
7448 delete_keyboard_wait_descriptor (desc);
7451 # endif
7453 # ifdef USABLE_SIGIO
7455 /* Return true if *MASK has a bit set
7456 that corresponds to one of the keyboard input descriptors. */
7458 static bool
7459 keyboard_bit_set (fd_set *mask)
7461 int fd;
7463 for (fd = 0; fd <= max_desc; fd++)
7464 if (FD_ISSET (fd, mask)
7465 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7466 == (FOR_READ | KEYBOARD_FD)))
7467 return 1;
7469 return 0;
7471 # endif
7473 #else /* not subprocesses */
7475 /* This is referenced in thread.c:run_thread (which is never actually
7476 called, since threads are not enabled for this configuration. */
7477 void
7478 update_processes_for_thread_death (Lisp_Object dying_thread)
7482 /* Defined in msdos.c. */
7483 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7484 struct timespec *, void *);
7486 /* Implementation of wait_reading_process_output, assuming that there
7487 are no subprocesses. Used only by the MS-DOS build.
7489 Wait for timeout to elapse and/or keyboard input to be available.
7491 TIME_LIMIT is:
7492 timeout in seconds
7493 If negative, gobble data immediately available but don't wait for any.
7495 NSECS is:
7496 an additional duration to wait, measured in nanoseconds
7497 If TIME_LIMIT is zero, then:
7498 If NSECS == 0, there is no limit.
7499 If NSECS > 0, the timeout consists of NSECS only.
7500 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7502 READ_KBD is:
7503 0 to ignore keyboard input, or
7504 1 to return when input is available, or
7505 -1 means caller will actually read the input, so don't throw to
7506 the quit handler.
7508 see full version for other parameters. We know that wait_proc will
7509 always be NULL, since `subprocesses' isn't defined.
7511 DO_DISPLAY means redisplay should be done to show subprocess
7512 output that arrives.
7514 Return -1 signifying we got no output and did not try. */
7517 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7518 bool do_display,
7519 Lisp_Object wait_for_cell,
7520 struct Lisp_Process *wait_proc, int just_wait_proc)
7522 register int nfds;
7523 struct timespec end_time, timeout;
7524 enum { MINIMUM = -1, TIMEOUT, FOREVER } wait;
7526 if (TYPE_MAXIMUM (time_t) < time_limit)
7527 time_limit = TYPE_MAXIMUM (time_t);
7529 if (time_limit < 0 || nsecs < 0)
7530 wait = MINIMUM;
7531 else if (time_limit > 0 || nsecs > 0)
7533 wait = TIMEOUT;
7534 end_time = timespec_add (current_timespec (),
7535 make_timespec (time_limit, nsecs));
7537 else
7538 wait = FOREVER;
7540 /* Turn off periodic alarms (in case they are in use)
7541 and then turn off any other atimers,
7542 because the select emulator uses alarms. */
7543 stop_polling ();
7544 turn_on_atimers (0);
7546 while (1)
7548 bool timeout_reduced_for_timers = false;
7549 fd_set waitchannels;
7550 int xerrno;
7552 /* If calling from keyboard input, do not quit
7553 since we want to return C-g as an input character.
7554 Otherwise, do pending quit if requested. */
7555 if (read_kbd >= 0)
7556 maybe_quit ();
7558 /* Exit now if the cell we're waiting for became non-nil. */
7559 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7560 break;
7562 /* Compute time from now till when time limit is up. */
7563 /* Exit if already run out. */
7564 if (wait == TIMEOUT)
7566 struct timespec now = current_timespec ();
7567 if (timespec_cmp (end_time, now) <= 0)
7568 break;
7569 timeout = timespec_sub (end_time, now);
7571 else
7572 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7574 /* If our caller will not immediately handle keyboard events,
7575 run timer events directly.
7576 (Callers that will immediately read keyboard events
7577 call timer_delay on their own.) */
7578 if (NILP (wait_for_cell))
7580 struct timespec timer_delay;
7584 unsigned old_timers_run = timers_run;
7585 timer_delay = timer_check ();
7586 if (timers_run != old_timers_run && do_display)
7587 /* We must retry, since a timer may have requeued itself
7588 and that could alter the time delay. */
7589 redisplay_preserve_echo_area (14);
7590 else
7591 break;
7593 while (!detect_input_pending ());
7595 /* If there is unread keyboard input, also return. */
7596 if (read_kbd != 0
7597 && requeued_events_pending_p ())
7598 break;
7600 if (timespec_valid_p (timer_delay))
7602 if (timespec_cmp (timer_delay, timeout) < 0)
7604 timeout = timer_delay;
7605 timeout_reduced_for_timers = true;
7610 /* Cause C-g and alarm signals to take immediate action,
7611 and cause input available signals to zero out timeout. */
7612 if (read_kbd < 0)
7613 set_waiting_for_input (&timeout);
7615 /* If a frame has been newly mapped and needs updating,
7616 reprocess its display stuff. */
7617 if (frame_garbaged && do_display)
7619 clear_waiting_for_input ();
7620 redisplay_preserve_echo_area (15);
7621 if (read_kbd < 0)
7622 set_waiting_for_input (&timeout);
7625 /* Wait till there is something to do. */
7626 FD_ZERO (&waitchannels);
7627 if (read_kbd && detect_input_pending ())
7628 nfds = 0;
7629 else
7631 if (read_kbd || !NILP (wait_for_cell))
7632 FD_SET (0, &waitchannels);
7633 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7636 xerrno = errno;
7638 /* Make C-g and alarm signals set flags again. */
7639 clear_waiting_for_input ();
7641 /* If we woke up due to SIGWINCH, actually change size now. */
7642 do_pending_window_change (0);
7644 if (wait < FOREVER && nfds == 0 && ! timeout_reduced_for_timers)
7645 /* We waited the full specified time, so return now. */
7646 break;
7648 if (nfds == -1)
7650 /* If the system call was interrupted, then go around the
7651 loop again. */
7652 if (xerrno == EINTR)
7653 FD_ZERO (&waitchannels);
7654 else
7655 report_file_errno ("Failed select", Qnil, xerrno);
7658 /* Check for keyboard input. */
7660 if (read_kbd
7661 && detect_input_pending_run_timers (do_display))
7663 swallow_events (do_display);
7664 if (detect_input_pending_run_timers (do_display))
7665 break;
7668 /* If there is unread keyboard input, also return. */
7669 if (read_kbd
7670 && requeued_events_pending_p ())
7671 break;
7673 /* If wait_for_cell. check for keyboard input
7674 but don't run any timers.
7675 ??? (It seems wrong to me to check for keyboard
7676 input at all when wait_for_cell, but the code
7677 has been this way since July 1994.
7678 Try changing this after version 19.31.) */
7679 if (! NILP (wait_for_cell)
7680 && detect_input_pending ())
7682 swallow_events (do_display);
7683 if (detect_input_pending ())
7684 break;
7687 /* Exit now if the cell we're waiting for became non-nil. */
7688 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7689 break;
7692 start_polling ();
7694 return -1;
7697 #endif /* not subprocesses */
7699 /* The following functions are needed even if async subprocesses are
7700 not supported. Some of them are no-op stubs in that case. */
7702 #ifdef HAVE_TIMERFD
7704 /* Add FD, which is a descriptor returned by timerfd_create,
7705 to the set of non-keyboard input descriptors. */
7707 void
7708 add_timer_wait_descriptor (int fd)
7710 add_read_fd (fd, timerfd_callback, NULL);
7711 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7714 #endif /* HAVE_TIMERFD */
7716 /* If program file NAME starts with /: for quoting a magic
7717 name, remove that, preserving the multibyteness of NAME. */
7719 Lisp_Object
7720 remove_slash_colon (Lisp_Object name)
7722 return
7723 (SREF (name, 0) == '/' && SREF (name, 1) == ':'
7724 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7725 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7726 : name);
7729 /* Add DESC to the set of keyboard input descriptors. */
7731 void
7732 add_keyboard_wait_descriptor (int desc)
7734 #ifdef subprocesses /* Actually means "not MSDOS". */
7735 eassert (desc >= 0 && desc < FD_SETSIZE);
7736 fd_callback_info[desc].flags &= ~PROCESS_FD;
7737 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7738 if (desc > max_desc)
7739 max_desc = desc;
7740 #endif
7743 /* From now on, do not expect DESC to give keyboard input. */
7745 void
7746 delete_keyboard_wait_descriptor (int desc)
7748 #ifdef subprocesses
7749 eassert (desc >= 0 && desc < FD_SETSIZE);
7751 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7753 if (desc == max_desc)
7754 recompute_max_desc ();
7755 #endif
7758 /* Setup coding systems of PROCESS. */
7760 void
7761 setup_process_coding_systems (Lisp_Object process)
7763 #ifdef subprocesses
7764 struct Lisp_Process *p = XPROCESS (process);
7765 int inch = p->infd;
7766 int outch = p->outfd;
7767 Lisp_Object coding_system;
7769 if (inch < 0 || outch < 0)
7770 return;
7772 if (!proc_decode_coding_system[inch])
7773 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7774 coding_system = p->decode_coding_system;
7775 if (EQ (p->filter, Qinternal_default_process_filter)
7776 && BUFFERP (p->buffer))
7778 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7779 coding_system = raw_text_coding_system (coding_system);
7781 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7783 if (!proc_encode_coding_system[outch])
7784 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7785 setup_coding_system (p->encode_coding_system,
7786 proc_encode_coding_system[outch]);
7787 #endif
7790 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7791 doc: /* Return the (or a) live process associated with BUFFER.
7792 BUFFER may be a buffer or the name of one.
7793 Return nil if all processes associated with BUFFER have been
7794 deleted or killed. */)
7795 (register Lisp_Object buffer)
7797 #ifdef subprocesses
7798 register Lisp_Object buf, tail, proc;
7800 if (NILP (buffer)) return Qnil;
7801 buf = Fget_buffer (buffer);
7802 if (NILP (buf)) return Qnil;
7804 FOR_EACH_PROCESS (tail, proc)
7805 if (EQ (XPROCESS (proc)->buffer, buf))
7806 return proc;
7807 #endif /* subprocesses */
7808 return Qnil;
7811 DEFUN ("process-inherit-coding-system-flag",
7812 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7813 1, 1, 0,
7814 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7815 If this flag is t, `buffer-file-coding-system' of the buffer
7816 associated with PROCESS will inherit the coding system used to decode
7817 the process output. */)
7818 (register Lisp_Object process)
7820 #ifdef subprocesses
7821 CHECK_PROCESS (process);
7822 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7823 #else
7824 /* Ignore the argument and return the value of
7825 inherit-process-coding-system. */
7826 return inherit_process_coding_system ? Qt : Qnil;
7827 #endif
7830 /* Kill all processes associated with `buffer'.
7831 If `buffer' is nil, kill all processes. */
7833 void
7834 kill_buffer_processes (Lisp_Object buffer)
7836 #ifdef subprocesses
7837 Lisp_Object tail, proc;
7839 FOR_EACH_PROCESS (tail, proc)
7840 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7842 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7843 Fdelete_process (proc);
7844 else if (XPROCESS (proc)->infd >= 0)
7845 process_send_signal (proc, SIGHUP, Qnil, 1);
7847 #else /* subprocesses */
7848 /* Since we have no subprocesses, this does nothing. */
7849 #endif /* subprocesses */
7852 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7853 Swaiting_for_user_input_p, 0, 0, 0,
7854 doc: /* Return non-nil if Emacs is waiting for input from the user.
7855 This is intended for use by asynchronous process output filters and sentinels. */)
7856 (void)
7858 #ifdef subprocesses
7859 return (waiting_for_user_input_p ? Qt : Qnil);
7860 #else
7861 return Qnil;
7862 #endif
7865 /* Stop reading input from keyboard sources. */
7867 void
7868 hold_keyboard_input (void)
7870 kbd_is_on_hold = 1;
7873 /* Resume reading input from keyboard sources. */
7875 void
7876 unhold_keyboard_input (void)
7878 kbd_is_on_hold = 0;
7881 /* Return true if keyboard input is on hold, zero otherwise. */
7883 bool
7884 kbd_on_hold_p (void)
7886 return kbd_is_on_hold;
7890 /* Enumeration of and access to system processes a-la ps(1). */
7892 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7893 0, 0, 0,
7894 doc: /* Return a list of numerical process IDs of all running processes.
7895 If this functionality is unsupported, return nil.
7897 See `process-attributes' for getting attributes of a process given its ID. */)
7898 (void)
7900 return list_system_processes ();
7903 DEFUN ("process-attributes", Fprocess_attributes,
7904 Sprocess_attributes, 1, 1, 0,
7905 doc: /* Return attributes of the process given by its PID, a number.
7907 Value is an alist where each element is a cons cell of the form
7909 (KEY . VALUE)
7911 If this functionality is unsupported, the value is nil.
7913 See `list-system-processes' for getting a list of all process IDs.
7915 The KEYs of the attributes that this function may return are listed
7916 below, together with the type of the associated VALUE (in parentheses).
7917 Not all platforms support all of these attributes; unsupported
7918 attributes will not appear in the returned alist.
7919 Unless explicitly indicated otherwise, numbers can have either
7920 integer or floating point values.
7922 euid -- Effective user User ID of the process (number)
7923 user -- User name corresponding to euid (string)
7924 egid -- Effective user Group ID of the process (number)
7925 group -- Group name corresponding to egid (string)
7926 comm -- Command name (executable name only) (string)
7927 state -- Process state code, such as "S", "R", or "T" (string)
7928 ppid -- Parent process ID (number)
7929 pgrp -- Process group ID (number)
7930 sess -- Session ID, i.e. process ID of session leader (number)
7931 ttname -- Controlling tty name (string)
7932 tpgid -- ID of foreground process group on the process's tty (number)
7933 minflt -- number of minor page faults (number)
7934 majflt -- number of major page faults (number)
7935 cminflt -- cumulative number of minor page faults (number)
7936 cmajflt -- cumulative number of major page faults (number)
7937 utime -- user time used by the process, in (current-time) format,
7938 which is a list of integers (HIGH LOW USEC PSEC)
7939 stime -- system time used by the process (current-time)
7940 time -- sum of utime and stime (current-time)
7941 cutime -- user time used by the process and its children (current-time)
7942 cstime -- system time used by the process and its children (current-time)
7943 ctime -- sum of cutime and cstime (current-time)
7944 pri -- priority of the process (number)
7945 nice -- nice value of the process (number)
7946 thcount -- process thread count (number)
7947 start -- time the process started (current-time)
7948 vsize -- virtual memory size of the process in KB's (number)
7949 rss -- resident set size of the process in KB's (number)
7950 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7951 pcpu -- percents of CPU time used by the process (floating-point number)
7952 pmem -- percents of total physical memory used by process's resident set
7953 (floating-point number)
7954 args -- command line which invoked the process (string). */)
7955 ( Lisp_Object pid)
7957 return system_process_attributes (pid);
7960 #ifdef subprocesses
7961 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7962 Invoke this after init_process_emacs, and after glib and/or GNUstep
7963 futz with the SIGCHLD handler, but before Emacs forks any children.
7964 This function's caller should block SIGCHLD. */
7966 void
7967 catch_child_signal (void)
7969 struct sigaction action, old_action;
7970 sigset_t oldset;
7971 emacs_sigaction_init (&action, deliver_child_signal);
7972 block_child_signal (&oldset);
7973 sigaction (SIGCHLD, &action, &old_action);
7974 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7975 || ! (old_action.sa_flags & SA_SIGINFO));
7977 if (old_action.sa_handler != deliver_child_signal)
7978 lib_child_handler
7979 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7980 ? dummy_handler
7981 : old_action.sa_handler);
7982 unblock_child_signal (&oldset);
7984 #endif /* subprocesses */
7986 /* Limit the number of open files to the value it had at startup. */
7988 void
7989 restore_nofile_limit (void)
7991 #ifdef HAVE_SETRLIMIT
7992 if (FD_SETSIZE < nofile_limit.rlim_cur)
7993 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7994 #endif
7998 /* This is not called "init_process" because that is the name of a
7999 Mach system call, so it would cause problems on Darwin systems. */
8000 void
8001 init_process_emacs (int sockfd)
8003 #ifdef subprocesses
8004 int i;
8006 inhibit_sentinels = 0;
8008 #ifndef CANNOT_DUMP
8009 if (! noninteractive || initialized)
8010 #endif
8012 #if defined HAVE_GLIB && !defined WINDOWSNT
8013 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8014 this should always fail, but is enough to initialize glib's
8015 private SIGCHLD handler, allowing catch_child_signal to copy
8016 it into lib_child_handler. */
8017 g_source_unref (g_child_watch_source_new (getpid ()));
8018 #endif
8019 catch_child_signal ();
8022 #ifdef HAVE_SETRLIMIT
8023 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8024 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
8025 nofile_limit.rlim_cur = 0;
8026 else if (FD_SETSIZE < nofile_limit.rlim_cur)
8028 struct rlimit rlim = nofile_limit;
8029 rlim.rlim_cur = FD_SETSIZE;
8030 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
8031 nofile_limit.rlim_cur = 0;
8033 #endif
8035 external_sock_fd = sockfd;
8036 Lisp_Object sockname = Qnil;
8037 # if HAVE_GETSOCKNAME
8038 if (0 <= sockfd)
8040 union u_sockaddr sa;
8041 socklen_t salen = sizeof sa;
8042 if (getsockname (sockfd, &sa.sa, &salen) == 0)
8043 sockname = conv_sockaddr_to_lisp (&sa.sa, salen);
8045 # endif
8046 Vinternal__daemon_sockname = sockname;
8048 max_desc = -1;
8049 memset (fd_callback_info, 0, sizeof (fd_callback_info));
8051 num_pending_connects = 0;
8053 process_output_delay_count = 0;
8054 process_output_skip = 0;
8056 /* Don't do this, it caused infinite select loops. The display
8057 method should call add_keyboard_wait_descriptor on stdin if it
8058 needs that. */
8059 #if 0
8060 FD_SET (0, &input_wait_mask);
8061 #endif
8063 Vprocess_alist = Qnil;
8064 deleted_pid_list = Qnil;
8065 for (i = 0; i < FD_SETSIZE; i++)
8067 chan_process[i] = Qnil;
8068 proc_buffered_char[i] = -1;
8070 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
8071 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
8072 #ifdef DATAGRAM_SOCKETS
8073 memset (datagram_address, 0, sizeof datagram_address);
8074 #endif
8076 #if defined (DARWIN_OS)
8077 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8078 processes. As such, we only change the default value. */
8079 if (initialized)
8081 char const *release = (STRINGP (Voperating_system_release)
8082 ? SSDATA (Voperating_system_release)
8083 : 0);
8084 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
8085 Vprocess_connection_type = Qnil;
8088 #endif
8089 #endif /* subprocesses */
8090 kbd_is_on_hold = 0;
8093 void
8094 syms_of_process (void)
8096 #ifdef subprocesses
8098 DEFSYM (Qprocessp, "processp");
8099 DEFSYM (Qrun, "run");
8100 DEFSYM (Qstop, "stop");
8101 DEFSYM (Qsignal, "signal");
8103 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8104 here again. */
8106 DEFSYM (Qopen, "open");
8107 DEFSYM (Qclosed, "closed");
8108 DEFSYM (Qconnect, "connect");
8109 DEFSYM (Qfailed, "failed");
8110 DEFSYM (Qlisten, "listen");
8111 DEFSYM (Qlocal, "local");
8112 DEFSYM (Qipv4, "ipv4");
8113 #ifdef AF_INET6
8114 DEFSYM (Qipv6, "ipv6");
8115 #endif
8116 DEFSYM (Qdatagram, "datagram");
8117 DEFSYM (Qseqpacket, "seqpacket");
8119 DEFSYM (QCport, ":port");
8120 DEFSYM (QCspeed, ":speed");
8121 DEFSYM (QCprocess, ":process");
8123 DEFSYM (QCbytesize, ":bytesize");
8124 DEFSYM (QCstopbits, ":stopbits");
8125 DEFSYM (QCparity, ":parity");
8126 DEFSYM (Qodd, "odd");
8127 DEFSYM (Qeven, "even");
8128 DEFSYM (QCflowcontrol, ":flowcontrol");
8129 DEFSYM (Qhw, "hw");
8130 DEFSYM (Qsw, "sw");
8131 DEFSYM (QCsummary, ":summary");
8133 DEFSYM (Qreal, "real");
8134 DEFSYM (Qnetwork, "network");
8135 DEFSYM (Qserial, "serial");
8136 DEFSYM (QCbuffer, ":buffer");
8137 DEFSYM (QChost, ":host");
8138 DEFSYM (QCservice, ":service");
8139 DEFSYM (QClocal, ":local");
8140 DEFSYM (QCremote, ":remote");
8141 DEFSYM (QCcoding, ":coding");
8142 DEFSYM (QCserver, ":server");
8143 DEFSYM (QCnowait, ":nowait");
8144 DEFSYM (QCsentinel, ":sentinel");
8145 DEFSYM (QCuse_external_socket, ":use-external-socket");
8146 DEFSYM (QCtls_parameters, ":tls-parameters");
8147 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8148 DEFSYM (QClog, ":log");
8149 DEFSYM (QCnoquery, ":noquery");
8150 DEFSYM (QCstop, ":stop");
8151 DEFSYM (QCplist, ":plist");
8152 DEFSYM (QCcommand, ":command");
8153 DEFSYM (QCconnection_type, ":connection-type");
8154 DEFSYM (QCstderr, ":stderr");
8155 DEFSYM (Qpty, "pty");
8156 DEFSYM (Qpipe, "pipe");
8158 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8160 staticpro (&Vprocess_alist);
8161 staticpro (&deleted_pid_list);
8163 #endif /* subprocesses */
8165 DEFSYM (QCname, ":name");
8166 DEFSYM (QCtype, ":type");
8168 DEFSYM (Qeuid, "euid");
8169 DEFSYM (Qegid, "egid");
8170 DEFSYM (Quser, "user");
8171 DEFSYM (Qgroup, "group");
8172 DEFSYM (Qcomm, "comm");
8173 DEFSYM (Qstate, "state");
8174 DEFSYM (Qppid, "ppid");
8175 DEFSYM (Qpgrp, "pgrp");
8176 DEFSYM (Qsess, "sess");
8177 DEFSYM (Qttname, "ttname");
8178 DEFSYM (Qtpgid, "tpgid");
8179 DEFSYM (Qminflt, "minflt");
8180 DEFSYM (Qmajflt, "majflt");
8181 DEFSYM (Qcminflt, "cminflt");
8182 DEFSYM (Qcmajflt, "cmajflt");
8183 DEFSYM (Qutime, "utime");
8184 DEFSYM (Qstime, "stime");
8185 DEFSYM (Qtime, "time");
8186 DEFSYM (Qcutime, "cutime");
8187 DEFSYM (Qcstime, "cstime");
8188 DEFSYM (Qctime, "ctime");
8189 #ifdef subprocesses
8190 DEFSYM (Qinternal_default_process_sentinel,
8191 "internal-default-process-sentinel");
8192 DEFSYM (Qinternal_default_process_filter,
8193 "internal-default-process-filter");
8194 #endif
8195 DEFSYM (Qpri, "pri");
8196 DEFSYM (Qnice, "nice");
8197 DEFSYM (Qthcount, "thcount");
8198 DEFSYM (Qstart, "start");
8199 DEFSYM (Qvsize, "vsize");
8200 DEFSYM (Qrss, "rss");
8201 DEFSYM (Qetime, "etime");
8202 DEFSYM (Qpcpu, "pcpu");
8203 DEFSYM (Qpmem, "pmem");
8204 DEFSYM (Qargs, "args");
8206 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8207 doc: /* Non-nil means delete processes immediately when they exit.
8208 A value of nil means don't delete them until `list-processes' is run. */);
8210 delete_exited_processes = 1;
8212 #ifdef subprocesses
8213 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8214 doc: /* Control type of device used to communicate with subprocesses.
8215 Values are nil to use a pipe, or t or `pty' to use a pty.
8216 The value has no effect if the system has no ptys or if all ptys are busy:
8217 then a pipe is used in any case.
8218 The value takes effect when `start-process' is called. */);
8219 Vprocess_connection_type = Qt;
8221 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8222 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8223 On some systems, when Emacs reads the output from a subprocess, the output data
8224 is read in very small blocks, potentially resulting in very poor performance.
8225 This behavior can be remedied to some extent by setting this variable to a
8226 non-nil value, as it will automatically delay reading from such processes, to
8227 allow them to produce more output before Emacs tries to read it.
8228 If the value is t, the delay is reset after each write to the process; any other
8229 non-nil value means that the delay is not reset on write.
8230 The variable takes effect when `start-process' is called. */);
8231 Vprocess_adaptive_read_buffering = Qt;
8233 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions,
8234 doc: /* List of functions to be called for `interrupt-process'.
8235 The arguments of the functions are the same as for `interrupt-process'.
8236 These functions are called in the order of the list, until one of them
8237 returns non-`nil'. */);
8238 Vinterrupt_process_functions = list1 (Qinternal_default_interrupt_process);
8240 DEFVAR_LISP ("internal--daemon-sockname", Vinternal__daemon_sockname,
8241 doc: /* Name of external socket passed to Emacs, or nil if none. */);
8242 Vinternal__daemon_sockname = Qnil;
8244 DEFSYM (Qinternal_default_interrupt_process,
8245 "internal-default-interrupt-process");
8246 DEFSYM (Qinterrupt_process_functions, "interrupt-process-functions");
8248 defsubr (&Sprocessp);
8249 defsubr (&Sget_process);
8250 defsubr (&Sdelete_process);
8251 defsubr (&Sprocess_status);
8252 defsubr (&Sprocess_exit_status);
8253 defsubr (&Sprocess_id);
8254 defsubr (&Sprocess_name);
8255 defsubr (&Sprocess_tty_name);
8256 defsubr (&Sprocess_command);
8257 defsubr (&Sset_process_buffer);
8258 defsubr (&Sprocess_buffer);
8259 defsubr (&Sprocess_mark);
8260 defsubr (&Sset_process_filter);
8261 defsubr (&Sprocess_filter);
8262 defsubr (&Sset_process_sentinel);
8263 defsubr (&Sprocess_sentinel);
8264 defsubr (&Sset_process_thread);
8265 defsubr (&Sprocess_thread);
8266 defsubr (&Sset_process_window_size);
8267 defsubr (&Sset_process_inherit_coding_system_flag);
8268 defsubr (&Sset_process_query_on_exit_flag);
8269 defsubr (&Sprocess_query_on_exit_flag);
8270 defsubr (&Sprocess_contact);
8271 defsubr (&Sprocess_plist);
8272 defsubr (&Sset_process_plist);
8273 defsubr (&Sprocess_list);
8274 defsubr (&Smake_process);
8275 defsubr (&Smake_pipe_process);
8276 defsubr (&Sserial_process_configure);
8277 defsubr (&Smake_serial_process);
8278 defsubr (&Sset_network_process_option);
8279 defsubr (&Smake_network_process);
8280 defsubr (&Sformat_network_address);
8281 defsubr (&Snetwork_interface_list);
8282 defsubr (&Snetwork_interface_info);
8283 #ifdef DATAGRAM_SOCKETS
8284 defsubr (&Sprocess_datagram_address);
8285 defsubr (&Sset_process_datagram_address);
8286 #endif
8287 defsubr (&Saccept_process_output);
8288 defsubr (&Sprocess_send_region);
8289 defsubr (&Sprocess_send_string);
8290 defsubr (&Sinternal_default_interrupt_process);
8291 defsubr (&Sinterrupt_process);
8292 defsubr (&Skill_process);
8293 defsubr (&Squit_process);
8294 defsubr (&Sstop_process);
8295 defsubr (&Scontinue_process);
8296 defsubr (&Sprocess_running_child_p);
8297 defsubr (&Sprocess_send_eof);
8298 defsubr (&Ssignal_process);
8299 defsubr (&Swaiting_for_user_input_p);
8300 defsubr (&Sprocess_type);
8301 defsubr (&Sinternal_default_process_sentinel);
8302 defsubr (&Sinternal_default_process_filter);
8303 defsubr (&Sset_process_coding_system);
8304 defsubr (&Sprocess_coding_system);
8305 defsubr (&Sset_process_filter_multibyte);
8306 defsubr (&Sprocess_filter_multibyte_p);
8309 Lisp_Object subfeatures = Qnil;
8310 const struct socket_options *sopt;
8312 #define ADD_SUBFEATURE(key, val) \
8313 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8315 ADD_SUBFEATURE (QCnowait, Qt);
8316 #ifdef DATAGRAM_SOCKETS
8317 ADD_SUBFEATURE (QCtype, Qdatagram);
8318 #endif
8319 #ifdef HAVE_SEQPACKET
8320 ADD_SUBFEATURE (QCtype, Qseqpacket);
8321 #endif
8322 #ifdef HAVE_LOCAL_SOCKETS
8323 ADD_SUBFEATURE (QCfamily, Qlocal);
8324 #endif
8325 ADD_SUBFEATURE (QCfamily, Qipv4);
8326 #ifdef AF_INET6
8327 ADD_SUBFEATURE (QCfamily, Qipv6);
8328 #endif
8329 #ifdef HAVE_GETSOCKNAME
8330 ADD_SUBFEATURE (QCservice, Qt);
8331 #endif
8332 ADD_SUBFEATURE (QCserver, Qt);
8334 for (sopt = socket_options; sopt->name; sopt++)
8335 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8337 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8340 #endif /* subprocesses */
8342 defsubr (&Sget_buffer_process);
8343 defsubr (&Sprocess_inherit_coding_system_flag);
8344 defsubr (&Slist_system_processes);
8345 defsubr (&Sprocess_attributes);