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