; * lisp/textmodes/flyspell.el (flyspell-auto-correct-word): Fix a typo.
[emacs.git] / src / process.c
blobbccc3ac3992c349e97146485fea7bbd0e9a5d310
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 #ifdef subprocesses
165 #ifndef SOCK_CLOEXEC
166 # define SOCK_CLOEXEC 0
167 #endif
168 #ifndef SOCK_NONBLOCK
169 # define SOCK_NONBLOCK 0
170 #endif
172 /* True if ERRNUM represents an error where the system call would
173 block if a blocking variant were used. */
174 static bool
175 would_block (int errnum)
177 #ifdef EWOULDBLOCK
178 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
179 return true;
180 #endif
181 return errnum == EAGAIN;
184 #ifndef HAVE_ACCEPT4
186 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
188 static int
189 close_on_exec (int fd)
191 if (0 <= fd)
192 fcntl (fd, F_SETFD, FD_CLOEXEC);
193 return fd;
196 # undef accept4
197 # define accept4(sockfd, addr, addrlen, flags) \
198 process_accept4 (sockfd, addr, addrlen, flags)
199 static int
200 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
202 return close_on_exec (accept (sockfd, addr, addrlen));
205 static int
206 process_socket (int domain, int type, int protocol)
208 return close_on_exec (socket (domain, type, protocol));
210 # undef socket
211 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
212 #endif
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
218 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
219 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
221 /* Number of events of change of status of a process. */
222 static EMACS_INT process_tick;
223 /* Number of events for which the user or sentinel has been notified. */
224 static EMACS_INT update_tick;
226 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
227 this system. We need to read full packets, so we need a
228 "non-destructive" select. So we require either native select,
229 or emulation of select using FIONREAD. */
231 #ifndef BROKEN_DATAGRAM_SOCKETS
232 # if defined HAVE_SELECT || defined USABLE_FIONREAD
233 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
234 # define DATAGRAM_SOCKETS
235 # endif
236 # endif
237 #endif
239 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
240 # define HAVE_SEQPACKET
241 #endif
243 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
244 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
245 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
247 /* Number of processes which have a non-zero read_output_delay,
248 and therefore might be delayed for adaptive read buffering. */
250 static int process_output_delay_count;
252 /* True if any process has non-nil read_output_skip. */
254 static bool process_output_skip;
256 static void start_process_unwind (Lisp_Object);
257 static void create_process (Lisp_Object, char **, Lisp_Object);
258 #ifdef USABLE_SIGIO
259 static bool keyboard_bit_set (fd_set *);
260 #endif
261 static void deactivate_process (Lisp_Object);
262 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
263 static int read_process_output (Lisp_Object, int);
264 static void create_pty (Lisp_Object);
265 static void exec_sentinel (Lisp_Object, Lisp_Object);
267 /* Number of bits set in connect_wait_mask. */
268 static int num_pending_connects;
270 /* The largest descriptor currently in use; -1 if none. */
271 static int max_desc;
273 /* Set the external socket descriptor for Emacs to use when
274 `make-network-process' is called with a non-nil
275 `:use-external-socket' option. The value should be either -1, or
276 the file descriptor of a socket that is already bound. */
277 static int external_sock_fd;
279 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
280 static Lisp_Object chan_process[FD_SETSIZE];
281 static void wait_for_socket_fds (Lisp_Object, char const *);
283 /* Alist of elements (NAME . PROCESS). */
284 static Lisp_Object Vprocess_alist;
286 /* Buffered-ahead input char from process, indexed by channel.
287 -1 means empty (no char is buffered).
288 Used on sys V where the only way to tell if there is any
289 output from the process is to read at least one char.
290 Always -1 on systems that support FIONREAD. */
292 static int proc_buffered_char[FD_SETSIZE];
294 /* Table of `struct coding-system' for each process. */
295 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
296 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
298 #ifdef DATAGRAM_SOCKETS
299 /* Table of `partner address' for datagram sockets. */
300 static struct sockaddr_and_len {
301 struct sockaddr *sa;
302 ptrdiff_t len;
303 } datagram_address[FD_SETSIZE];
304 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
305 #define DATAGRAM_CONN_P(proc) \
306 (PROCESSP (proc) && \
307 XPROCESS (proc)->infd >= 0 && \
308 datagram_address[XPROCESS (proc)->infd].sa != 0)
309 #else
310 #define DATAGRAM_CONN_P(proc) (0)
311 #endif
313 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
314 a `for' loop which iterates over processes from Vprocess_alist. */
316 #define FOR_EACH_PROCESS(list_var, proc_var) \
317 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
319 /* These setters are used only in this file, so they can be private. */
320 static void
321 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
323 p->buffer = val;
325 static void
326 pset_command (struct Lisp_Process *p, Lisp_Object val)
328 p->command = val;
330 static void
331 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
333 p->decode_coding_system = val;
335 static void
336 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
338 p->decoding_buf = val;
340 static void
341 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
343 p->encode_coding_system = val;
345 static void
346 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
348 p->encoding_buf = val;
350 static void
351 pset_filter (struct Lisp_Process *p, Lisp_Object val)
353 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
355 static void
356 pset_log (struct Lisp_Process *p, Lisp_Object val)
358 p->log = val;
360 static void
361 pset_mark (struct Lisp_Process *p, Lisp_Object val)
363 p->mark = val;
365 static void
366 pset_thread (struct Lisp_Process *p, Lisp_Object val)
368 p->thread = val;
370 static void
371 pset_name (struct Lisp_Process *p, Lisp_Object val)
373 p->name = val;
375 static void
376 pset_plist (struct Lisp_Process *p, Lisp_Object val)
378 p->plist = val;
380 static void
381 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
383 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
385 static void
386 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
388 p->tty_name = val;
390 static void
391 pset_type (struct Lisp_Process *p, Lisp_Object val)
393 p->type = val;
395 static void
396 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
398 p->write_queue = val;
400 static void
401 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
403 p->stderrproc = val;
407 static Lisp_Object
408 make_lisp_proc (struct Lisp_Process *p)
410 return make_lisp_ptr (p, Lisp_Vectorlike);
413 enum fd_bits
415 /* Read from file descriptor. */
416 FOR_READ = 1,
417 /* Write to file descriptor. */
418 FOR_WRITE = 2,
419 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
420 set. */
421 KEYBOARD_FD = 4,
422 /* This descriptor refers to a process. */
423 PROCESS_FD = 8,
424 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
425 NON_BLOCKING_CONNECT_FD = 16
428 static struct fd_callback_data
430 fd_callback func;
431 void *data;
432 /* Flags from enum fd_bits. */
433 int flags;
434 /* If this fd is locked to a certain thread, this points to it.
435 Otherwise, this is NULL. If an fd is locked to a thread, then
436 only that thread is permitted to wait on it. */
437 struct thread_state *thread;
438 /* If this fd is currently being selected on by a thread, this
439 points to the thread. Otherwise it is NULL. */
440 struct thread_state *waiting_thread;
441 } fd_callback_info[FD_SETSIZE];
444 /* Add a file descriptor FD to be monitored for when read is possible.
445 When read is possible, call FUNC with argument DATA. */
447 void
448 add_read_fd (int fd, fd_callback func, void *data)
450 add_keyboard_wait_descriptor (fd);
452 fd_callback_info[fd].func = func;
453 fd_callback_info[fd].data = data;
456 static void
457 add_non_keyboard_read_fd (int fd)
459 eassert (fd >= 0 && fd < FD_SETSIZE);
460 eassert (fd_callback_info[fd].func == NULL);
462 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
463 fd_callback_info[fd].flags |= FOR_READ;
464 if (fd > max_desc)
465 max_desc = fd;
468 static void
469 add_process_read_fd (int fd)
471 add_non_keyboard_read_fd (fd);
472 fd_callback_info[fd].flags |= PROCESS_FD;
475 /* Stop monitoring file descriptor FD for when read is possible. */
477 void
478 delete_read_fd (int fd)
480 delete_keyboard_wait_descriptor (fd);
482 if (fd_callback_info[fd].flags == 0)
484 fd_callback_info[fd].func = 0;
485 fd_callback_info[fd].data = 0;
489 /* Add a file descriptor FD to be monitored for when write is possible.
490 When write is possible, call FUNC with argument DATA. */
492 void
493 add_write_fd (int fd, fd_callback func, void *data)
495 eassert (fd >= 0 && fd < FD_SETSIZE);
497 fd_callback_info[fd].func = func;
498 fd_callback_info[fd].data = data;
499 fd_callback_info[fd].flags |= FOR_WRITE;
500 if (fd > max_desc)
501 max_desc = fd;
504 static void
505 add_non_blocking_write_fd (int fd)
507 eassert (fd >= 0 && fd < FD_SETSIZE);
508 eassert (fd_callback_info[fd].func == NULL);
510 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
511 if (fd > max_desc)
512 max_desc = fd;
513 ++num_pending_connects;
516 static void
517 recompute_max_desc (void)
519 int fd;
521 for (fd = max_desc; fd >= 0; --fd)
523 if (fd_callback_info[fd].flags != 0)
525 max_desc = fd;
526 break;
531 /* Stop monitoring file descriptor FD for when write is possible. */
533 void
534 delete_write_fd (int fd)
536 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
538 if (--num_pending_connects < 0)
539 emacs_abort ();
541 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
542 if (fd_callback_info[fd].flags == 0)
544 fd_callback_info[fd].func = 0;
545 fd_callback_info[fd].data = 0;
547 if (fd == max_desc)
548 recompute_max_desc ();
552 static void
553 compute_input_wait_mask (fd_set *mask)
555 int fd;
557 FD_ZERO (mask);
558 for (fd = 0; fd <= max_desc; ++fd)
560 if (fd_callback_info[fd].thread != NULL
561 && fd_callback_info[fd].thread != current_thread)
562 continue;
563 if (fd_callback_info[fd].waiting_thread != NULL
564 && fd_callback_info[fd].waiting_thread != current_thread)
565 continue;
566 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
568 FD_SET (fd, mask);
569 fd_callback_info[fd].waiting_thread = current_thread;
574 static void
575 compute_non_process_wait_mask (fd_set *mask)
577 int fd;
579 FD_ZERO (mask);
580 for (fd = 0; fd <= max_desc; ++fd)
582 if (fd_callback_info[fd].thread != NULL
583 && fd_callback_info[fd].thread != current_thread)
584 continue;
585 if (fd_callback_info[fd].waiting_thread != NULL
586 && fd_callback_info[fd].waiting_thread != current_thread)
587 continue;
588 if ((fd_callback_info[fd].flags & FOR_READ) != 0
589 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
591 FD_SET (fd, mask);
592 fd_callback_info[fd].waiting_thread = current_thread;
597 static void
598 compute_non_keyboard_wait_mask (fd_set *mask)
600 int fd;
602 FD_ZERO (mask);
603 for (fd = 0; fd <= max_desc; ++fd)
605 if (fd_callback_info[fd].thread != NULL
606 && fd_callback_info[fd].thread != current_thread)
607 continue;
608 if (fd_callback_info[fd].waiting_thread != NULL
609 && fd_callback_info[fd].waiting_thread != current_thread)
610 continue;
611 if ((fd_callback_info[fd].flags & FOR_READ) != 0
612 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
614 FD_SET (fd, mask);
615 fd_callback_info[fd].waiting_thread = current_thread;
620 static void
621 compute_write_mask (fd_set *mask)
623 int fd;
625 FD_ZERO (mask);
626 for (fd = 0; fd <= max_desc; ++fd)
628 if (fd_callback_info[fd].thread != NULL
629 && fd_callback_info[fd].thread != current_thread)
630 continue;
631 if (fd_callback_info[fd].waiting_thread != NULL
632 && fd_callback_info[fd].waiting_thread != current_thread)
633 continue;
634 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
636 FD_SET (fd, mask);
637 fd_callback_info[fd].waiting_thread = current_thread;
642 static void
643 clear_waiting_thread_info (void)
645 int fd;
647 for (fd = 0; fd <= max_desc; ++fd)
649 if (fd_callback_info[fd].waiting_thread == current_thread)
650 fd_callback_info[fd].waiting_thread = NULL;
655 /* Compute the Lisp form of the process status, p->status, from
656 the numeric status that was returned by `wait'. */
658 static Lisp_Object status_convert (int);
660 static void
661 update_status (struct Lisp_Process *p)
663 eassert (p->raw_status_new);
664 pset_status (p, status_convert (p->raw_status));
665 p->raw_status_new = 0;
668 /* Convert a process status word in Unix format to
669 the list that we use internally. */
671 static Lisp_Object
672 status_convert (int w)
674 if (WIFSTOPPED (w))
675 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
676 else if (WIFEXITED (w))
677 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
678 WCOREDUMP (w) ? Qt : Qnil));
679 else if (WIFSIGNALED (w))
680 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
681 WCOREDUMP (w) ? Qt : Qnil));
682 else
683 return Qrun;
686 /* True if STATUS is that of a process attempting connection. */
688 static bool
689 connecting_status (Lisp_Object status)
691 return CONSP (status) && EQ (XCAR (status), Qconnect);
694 /* Given a status-list, extract the three pieces of information
695 and store them individually through the three pointers. */
697 static void
698 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
699 bool *coredump)
701 Lisp_Object tem;
703 if (connecting_status (l))
704 l = XCAR (l);
706 if (SYMBOLP (l))
708 *symbol = l;
709 *code = make_number (0);
710 *coredump = 0;
712 else
714 *symbol = XCAR (l);
715 tem = XCDR (l);
716 *code = XCAR (tem);
717 tem = XCDR (tem);
718 *coredump = !NILP (tem);
722 /* Return a string describing a process status list. */
724 static Lisp_Object
725 status_message (struct Lisp_Process *p)
727 Lisp_Object status = p->status;
728 Lisp_Object symbol, code;
729 bool coredump;
730 Lisp_Object string;
732 decode_status (status, &symbol, &code, &coredump);
734 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
736 char const *signame;
737 synchronize_system_messages_locale ();
738 signame = strsignal (XFASTINT (code));
739 if (signame == 0)
740 string = build_string ("unknown");
741 else
743 int c1, c2;
745 string = build_unibyte_string (signame);
746 if (! NILP (Vlocale_coding_system))
747 string = (code_convert_string_norecord
748 (string, Vlocale_coding_system, 0));
749 c1 = STRING_CHAR (SDATA (string));
750 c2 = downcase (c1);
751 if (c1 != c2)
752 Faset (string, make_number (0), make_number (c2));
754 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
755 return concat2 (string, suffix);
757 else if (EQ (symbol, Qexit))
759 if (NETCONN1_P (p))
760 return build_string (XFASTINT (code) == 0
761 ? "deleted\n"
762 : "connection broken by remote peer\n");
763 if (XFASTINT (code) == 0)
764 return build_string ("finished\n");
765 AUTO_STRING (prefix, "exited abnormally with code ");
766 string = Fnumber_to_string (code);
767 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
768 return concat3 (prefix, string, suffix);
770 else if (EQ (symbol, Qfailed))
772 AUTO_STRING (format, "failed with code %s\n");
773 return CALLN (Fformat, format, code);
775 else
776 return Fcopy_sequence (Fsymbol_name (symbol));
779 enum { PTY_NAME_SIZE = 24 };
781 /* Open an available pty, returning a file descriptor.
782 Store into PTY_NAME the file name of the terminal corresponding to the pty.
783 Return -1 on failure. */
785 static int
786 allocate_pty (char pty_name[PTY_NAME_SIZE])
788 #ifdef HAVE_PTYS
789 int fd;
791 #ifdef PTY_ITERATION
792 PTY_ITERATION
793 #else
794 register int c, i;
795 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
796 for (i = 0; i < 16; i++)
797 #endif
799 #ifdef PTY_NAME_SPRINTF
800 PTY_NAME_SPRINTF
801 #else
802 sprintf (pty_name, "/dev/pty%c%x", c, i);
803 #endif /* no PTY_NAME_SPRINTF */
805 #ifdef PTY_OPEN
806 PTY_OPEN;
807 #else /* no PTY_OPEN */
808 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
809 #endif /* no PTY_OPEN */
811 if (fd >= 0)
813 #ifdef PTY_TTY_NAME_SPRINTF
814 PTY_TTY_NAME_SPRINTF
815 #else
816 sprintf (pty_name, "/dev/tty%c%x", c, i);
817 #endif /* no PTY_TTY_NAME_SPRINTF */
819 /* Set FD's close-on-exec flag. This is needed even if
820 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
821 doesn't require support for that combination.
822 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
823 doesn't work if the close-on-exec flag is set (Bug#20555).
824 Multithreaded platforms where posix_openpt ignores
825 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
826 have a race condition between the PTY_OPEN and here. */
827 fcntl (fd, F_SETFD, FD_CLOEXEC);
829 /* Check to make certain that both sides are available.
830 This avoids a nasty yet stupid bug in rlogins. */
831 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
833 emacs_close (fd);
834 continue;
836 setup_pty (fd);
837 return fd;
840 #endif /* HAVE_PTYS */
841 return -1;
844 /* Allocate basically initialized process. */
846 static struct Lisp_Process *
847 allocate_process (void)
849 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
852 static Lisp_Object
853 make_process (Lisp_Object name)
855 struct Lisp_Process *p = allocate_process ();
856 /* Initialize Lisp data. Note that allocate_process initializes all
857 Lisp data to nil, so do it only for slots which should not be nil. */
858 pset_status (p, Qrun);
859 pset_mark (p, Fmake_marker ());
860 pset_thread (p, Fcurrent_thread ());
862 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
863 non-Lisp data, so do it only for slots which should not be zero. */
864 p->infd = -1;
865 p->outfd = -1;
866 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
867 p->open_fd[i] = -1;
869 #ifdef HAVE_GNUTLS
870 verify (GNUTLS_STAGE_EMPTY == 0);
871 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
872 eassert (NILP (p->gnutls_boot_parameters));
873 #endif
875 /* If name is already in use, modify it until it is unused. */
877 Lisp_Object name1 = name;
878 for (printmax_t i = 1; ; i++)
880 Lisp_Object tem = Fget_process (name1);
881 if (NILP (tem))
882 break;
883 char const suffix_fmt[] = "<%"pMd">";
884 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
885 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
886 name1 = concat2 (name, lsuffix);
888 name = name1;
889 pset_name (p, name);
890 pset_sentinel (p, Qinternal_default_process_sentinel);
891 pset_filter (p, Qinternal_default_process_filter);
892 Lisp_Object val;
893 XSETPROCESS (val, p);
894 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
895 return val;
898 static void
899 remove_process (register Lisp_Object proc)
901 register Lisp_Object pair;
903 pair = Frassq (proc, Vprocess_alist);
904 Vprocess_alist = Fdelq (pair, Vprocess_alist);
906 deactivate_process (proc);
909 void
910 update_processes_for_thread_death (Lisp_Object dying_thread)
912 Lisp_Object pair;
914 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
916 Lisp_Object process = XCDR (XCAR (pair));
917 if (EQ (XPROCESS (process)->thread, dying_thread))
919 struct Lisp_Process *proc = XPROCESS (process);
921 pset_thread (proc, Qnil);
922 if (proc->infd >= 0)
923 fd_callback_info[proc->infd].thread = NULL;
924 if (proc->outfd >= 0)
925 fd_callback_info[proc->outfd].thread = NULL;
930 #ifdef HAVE_GETADDRINFO_A
931 static void
932 free_dns_request (Lisp_Object proc)
934 struct Lisp_Process *p = XPROCESS (proc);
936 if (p->dns_request->ar_result)
937 freeaddrinfo (p->dns_request->ar_result);
938 xfree (p->dns_request);
939 p->dns_request = NULL;
941 #endif
944 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
945 doc: /* Return t if OBJECT is a process. */)
946 (Lisp_Object object)
948 return PROCESSP (object) ? Qt : Qnil;
951 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
952 doc: /* Return the process named NAME, or nil if there is none. */)
953 (register Lisp_Object name)
955 if (PROCESSP (name))
956 return name;
957 CHECK_STRING (name);
958 return Fcdr (Fassoc (name, Vprocess_alist, Qnil));
961 /* This is how commands for the user decode process arguments. It
962 accepts a process, a process name, a buffer, a buffer name, or nil.
963 Buffers denote the first process in the buffer, and nil denotes the
964 current buffer. */
966 static Lisp_Object
967 get_process (register Lisp_Object name)
969 register Lisp_Object proc, obj;
970 if (STRINGP (name))
972 obj = Fget_process (name);
973 if (NILP (obj))
974 obj = Fget_buffer (name);
975 if (NILP (obj))
976 error ("Process %s does not exist", SDATA (name));
978 else if (NILP (name))
979 obj = Fcurrent_buffer ();
980 else
981 obj = name;
983 /* Now obj should be either a buffer object or a process object. */
984 if (BUFFERP (obj))
986 if (NILP (BVAR (XBUFFER (obj), name)))
987 error ("Attempt to get process for a dead buffer");
988 proc = Fget_buffer_process (obj);
989 if (NILP (proc))
990 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
992 else
994 CHECK_PROCESS (obj);
995 proc = obj;
997 return proc;
1001 /* Fdelete_process promises to immediately forget about the process, but in
1002 reality, Emacs needs to remember those processes until they have been
1003 treated by the SIGCHLD handler and waitpid has been invoked on them;
1004 otherwise they might fill up the kernel's process table.
1006 Some processes created by call-process are also put onto this list.
1008 Members of this list are (process-ID . filename) pairs. The
1009 process-ID is a number; the filename, if a string, is a file that
1010 needs to be removed after the process exits. */
1011 static Lisp_Object deleted_pid_list;
1013 void
1014 record_deleted_pid (pid_t pid, Lisp_Object filename)
1016 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1017 /* GC treated elements set to nil. */
1018 Fdelq (Qnil, deleted_pid_list));
1022 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1023 doc: /* Delete PROCESS: kill it and forget about it immediately.
1024 PROCESS may be a process, a buffer, the name of a process or buffer, or
1025 nil, indicating the current buffer's process. */)
1026 (register Lisp_Object process)
1028 register struct Lisp_Process *p;
1030 process = get_process (process);
1031 p = XPROCESS (process);
1033 #ifdef HAVE_GETADDRINFO_A
1034 if (p->dns_request)
1036 /* Cancel the request. Unless shutting down, wait until
1037 completion. Free the request if completely canceled. */
1039 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
1040 if (!canceled && !inhibit_sentinels)
1042 struct gaicb const *req = p->dns_request;
1043 while (gai_suspend (&req, 1, NULL) != 0)
1044 continue;
1045 canceled = true;
1047 if (canceled)
1048 free_dns_request (process);
1050 #endif
1052 p->raw_status_new = 0;
1053 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1055 pset_status (p, list2 (Qexit, make_number (0)));
1056 p->tick = ++process_tick;
1057 status_notify (p, NULL);
1058 redisplay_preserve_echo_area (13);
1060 else
1062 if (p->alive)
1063 record_kill_process (p, Qnil);
1065 if (p->infd >= 0)
1067 /* Update P's status, since record_kill_process will make the
1068 SIGCHLD handler update deleted_pid_list, not *P. */
1069 Lisp_Object symbol;
1070 if (p->raw_status_new)
1071 update_status (p);
1072 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1073 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1074 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1076 p->tick = ++process_tick;
1077 status_notify (p, NULL);
1078 redisplay_preserve_echo_area (13);
1081 remove_process (process);
1082 return Qnil;
1085 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1086 doc: /* Return the status of PROCESS.
1087 The returned value is one of the following symbols:
1088 run -- for a process that is running.
1089 stop -- for a process stopped but continuable.
1090 exit -- for a process that has exited.
1091 signal -- for a process that has got a fatal signal.
1092 open -- for a network stream connection that is open.
1093 listen -- for a network stream server that is listening.
1094 closed -- for a network stream connection that is closed.
1095 connect -- when waiting for a non-blocking connection to complete.
1096 failed -- when a non-blocking connection has failed.
1097 nil -- if arg is a process name and no such process exists.
1098 PROCESS may be a process, a buffer, the name of a process, or
1099 nil, indicating the current buffer's process. */)
1100 (register Lisp_Object process)
1102 register struct Lisp_Process *p;
1103 register Lisp_Object status;
1105 if (STRINGP (process))
1106 process = Fget_process (process);
1107 else
1108 process = get_process (process);
1110 if (NILP (process))
1111 return process;
1113 p = XPROCESS (process);
1114 if (p->raw_status_new)
1115 update_status (p);
1116 status = p->status;
1117 if (CONSP (status))
1118 status = XCAR (status);
1119 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1121 if (EQ (status, Qexit))
1122 status = Qclosed;
1123 else if (EQ (p->command, Qt))
1124 status = Qstop;
1125 else if (EQ (status, Qrun))
1126 status = Qopen;
1128 return status;
1131 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1132 1, 1, 0,
1133 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1134 If PROCESS has not yet exited or died, return 0. */)
1135 (register Lisp_Object process)
1137 CHECK_PROCESS (process);
1138 if (XPROCESS (process)->raw_status_new)
1139 update_status (XPROCESS (process));
1140 if (CONSP (XPROCESS (process)->status))
1141 return XCAR (XCDR (XPROCESS (process)->status));
1142 return make_number (0);
1145 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1146 doc: /* Return the process id of PROCESS.
1147 This is the pid of the external process which PROCESS uses or talks to.
1148 For a network, serial, and pipe connections, this value is nil. */)
1149 (register Lisp_Object process)
1151 pid_t pid;
1153 CHECK_PROCESS (process);
1154 pid = XPROCESS (process)->pid;
1155 return (pid ? make_fixnum_or_float (pid) : Qnil);
1158 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1159 doc: /* Return the name of PROCESS, as a string.
1160 This is the name of the program invoked in PROCESS,
1161 possibly modified to make it unique among process names. */)
1162 (register Lisp_Object process)
1164 CHECK_PROCESS (process);
1165 return XPROCESS (process)->name;
1168 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1169 doc: /* Return the command that was executed to start PROCESS.
1170 This is a list of strings, the first string being the program executed
1171 and the rest of the strings being the arguments given to it.
1172 For a network or serial or pipe connection, this is nil (process is running)
1173 or t (process is stopped). */)
1174 (register Lisp_Object process)
1176 CHECK_PROCESS (process);
1177 return XPROCESS (process)->command;
1180 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1181 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1182 This is the terminal that the process itself reads and writes on,
1183 not the name of the pty that Emacs uses to talk with that terminal. */)
1184 (register Lisp_Object process)
1186 CHECK_PROCESS (process);
1187 return XPROCESS (process)->tty_name;
1190 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1191 2, 2, 0,
1192 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1193 Return BUFFER. */)
1194 (register Lisp_Object process, Lisp_Object buffer)
1196 struct Lisp_Process *p;
1198 CHECK_PROCESS (process);
1199 if (!NILP (buffer))
1200 CHECK_BUFFER (buffer);
1201 p = XPROCESS (process);
1202 pset_buffer (p, buffer);
1203 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1204 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1205 setup_process_coding_systems (process);
1206 return buffer;
1209 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1210 1, 1, 0,
1211 doc: /* Return the buffer PROCESS is associated with.
1212 The default process filter inserts output from PROCESS into this buffer. */)
1213 (register Lisp_Object process)
1215 CHECK_PROCESS (process);
1216 return XPROCESS (process)->buffer;
1219 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1220 1, 1, 0,
1221 doc: /* Return the marker for the end of the last output from PROCESS. */)
1222 (register Lisp_Object process)
1224 CHECK_PROCESS (process);
1225 return XPROCESS (process)->mark;
1228 static void
1229 set_process_filter_masks (struct Lisp_Process *p)
1231 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1232 delete_read_fd (p->infd);
1233 else if (EQ (p->filter, Qt)
1234 /* Network or serial process not stopped: */
1235 && !EQ (p->command, Qt))
1236 add_process_read_fd (p->infd);
1239 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1240 2, 2, 0,
1241 doc: /* Give PROCESS the filter function FILTER; nil means default.
1242 A value of t means stop accepting output from the process.
1244 When a process has a non-default filter, its buffer is not used for output.
1245 Instead, each time it does output, the entire string of output is
1246 passed to the filter.
1248 The filter gets two arguments: the process and the string of output.
1249 The string argument is normally a multibyte string, except:
1250 - if the process's input coding system is no-conversion or raw-text,
1251 it is a unibyte string (the non-converted input), or else
1252 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1253 string (the result of converting the decoded input multibyte
1254 string to unibyte with `string-make-unibyte'). */)
1255 (Lisp_Object process, Lisp_Object filter)
1257 CHECK_PROCESS (process);
1258 struct Lisp_Process *p = XPROCESS (process);
1260 /* Don't signal an error if the process's input file descriptor
1261 is closed. This could make debugging Lisp more difficult,
1262 for example when doing something like
1264 (setq process (start-process ...))
1265 (debug)
1266 (set-process-filter process ...) */
1268 if (NILP (filter))
1269 filter = Qinternal_default_process_filter;
1271 pset_filter (p, filter);
1273 if (p->infd >= 0)
1274 set_process_filter_masks (p);
1276 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1277 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1278 setup_process_coding_systems (process);
1279 return filter;
1282 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1283 1, 1, 0,
1284 doc: /* Return the filter function of PROCESS.
1285 See `set-process-filter' for more info on filter functions. */)
1286 (register Lisp_Object process)
1288 CHECK_PROCESS (process);
1289 return XPROCESS (process)->filter;
1292 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1293 2, 2, 0,
1294 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1295 The sentinel is called as a function when the process changes state.
1296 It gets two arguments: the process, and a string describing the change. */)
1297 (register Lisp_Object process, Lisp_Object sentinel)
1299 struct Lisp_Process *p;
1301 CHECK_PROCESS (process);
1302 p = XPROCESS (process);
1304 if (NILP (sentinel))
1305 sentinel = Qinternal_default_process_sentinel;
1307 pset_sentinel (p, sentinel);
1308 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1309 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1310 return sentinel;
1313 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1314 1, 1, 0,
1315 doc: /* Return the sentinel of PROCESS.
1316 See `set-process-sentinel' for more info on sentinels. */)
1317 (register Lisp_Object process)
1319 CHECK_PROCESS (process);
1320 return XPROCESS (process)->sentinel;
1323 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1324 2, 2, 0,
1325 doc: /* Set the locking thread of PROCESS to be THREAD.
1326 If THREAD is nil, the process is unlocked. */)
1327 (Lisp_Object process, Lisp_Object thread)
1329 struct Lisp_Process *proc;
1330 struct thread_state *tstate;
1332 CHECK_PROCESS (process);
1333 if (NILP (thread))
1334 tstate = NULL;
1335 else
1337 CHECK_THREAD (thread);
1338 tstate = XTHREAD (thread);
1341 proc = XPROCESS (process);
1342 pset_thread (proc, thread);
1343 if (proc->infd >= 0)
1344 fd_callback_info[proc->infd].thread = tstate;
1345 if (proc->outfd >= 0)
1346 fd_callback_info[proc->outfd].thread = tstate;
1348 return thread;
1351 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1352 1, 1, 0,
1353 doc: /* Ret the locking thread of PROCESS.
1354 If PROCESS is unlocked, this function returns nil. */)
1355 (Lisp_Object process)
1357 CHECK_PROCESS (process);
1358 return XPROCESS (process)->thread;
1361 DEFUN ("set-process-window-size", Fset_process_window_size,
1362 Sset_process_window_size, 3, 3, 0,
1363 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1364 Value is t if PROCESS was successfully told about the window size,
1365 nil otherwise. */)
1366 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1368 CHECK_PROCESS (process);
1370 /* All known platforms store window sizes as 'unsigned short'. */
1371 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1372 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1374 if (NETCONN_P (process)
1375 || XPROCESS (process)->infd < 0
1376 || (set_window_size (XPROCESS (process)->infd,
1377 XINT (height), XINT (width))
1378 < 0))
1379 return Qnil;
1380 else
1381 return Qt;
1384 DEFUN ("set-process-inherit-coding-system-flag",
1385 Fset_process_inherit_coding_system_flag,
1386 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1387 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1388 If the second argument FLAG is non-nil, then the variable
1389 `buffer-file-coding-system' of the buffer associated with PROCESS
1390 will be bound to the value of the coding system used to decode
1391 the process output.
1393 This is useful when the coding system specified for the process buffer
1394 leaves either the character code conversion or the end-of-line conversion
1395 unspecified, or if the coding system used to decode the process output
1396 is more appropriate for saving the process buffer.
1398 Binding the variable `inherit-process-coding-system' to non-nil before
1399 starting the process is an alternative way of setting the inherit flag
1400 for the process which will run.
1402 This function returns FLAG. */)
1403 (register Lisp_Object process, Lisp_Object flag)
1405 CHECK_PROCESS (process);
1406 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1407 return flag;
1410 DEFUN ("set-process-query-on-exit-flag",
1411 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1412 2, 2, 0,
1413 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1414 If the second argument FLAG is non-nil, Emacs will query the user before
1415 exiting or killing a buffer if PROCESS is running. This function
1416 returns FLAG. */)
1417 (register Lisp_Object process, Lisp_Object flag)
1419 CHECK_PROCESS (process);
1420 XPROCESS (process)->kill_without_query = NILP (flag);
1421 return flag;
1424 DEFUN ("process-query-on-exit-flag",
1425 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1426 1, 1, 0,
1427 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1428 (register Lisp_Object process)
1430 CHECK_PROCESS (process);
1431 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1434 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1435 1, 2, 0,
1436 doc: /* Return the contact info of PROCESS; t for a real child.
1437 For a network or serial or pipe connection, the value depends on the
1438 optional KEY arg. If KEY is nil, value is a cons cell of the form
1439 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1440 connection; it is t for a pipe connection. If KEY is t, the complete
1441 contact information for the connection is returned, else the specific
1442 value for the keyword KEY is returned. See `make-network-process',
1443 `make-serial-process', or `make-pipe-process' for the list of keywords.
1444 If PROCESS is a non-blocking network process that hasn't been fully
1445 set up yet, this function will block until socket setup has completed. */)
1446 (Lisp_Object process, Lisp_Object key)
1448 Lisp_Object contact;
1450 CHECK_PROCESS (process);
1451 contact = XPROCESS (process)->childp;
1453 #ifdef DATAGRAM_SOCKETS
1455 if (NETCONN_P (process))
1456 wait_for_socket_fds (process, "process-contact");
1458 if (DATAGRAM_CONN_P (process)
1459 && (EQ (key, Qt) || EQ (key, QCremote)))
1460 contact = Fplist_put (contact, QCremote,
1461 Fprocess_datagram_address (process));
1462 #endif
1464 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1465 || EQ (key, Qt))
1466 return contact;
1467 if (NILP (key) && NETCONN_P (process))
1468 return list2 (Fplist_get (contact, QChost),
1469 Fplist_get (contact, QCservice));
1470 if (NILP (key) && SERIALCONN_P (process))
1471 return list2 (Fplist_get (contact, QCport),
1472 Fplist_get (contact, QCspeed));
1473 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1474 if the pipe process is useful for purposes other than receiving
1475 stderr. */
1476 if (NILP (key) && PIPECONN_P (process))
1477 return Qt;
1478 return Fplist_get (contact, key);
1481 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1482 1, 1, 0,
1483 doc: /* Return the plist of PROCESS. */)
1484 (register Lisp_Object process)
1486 CHECK_PROCESS (process);
1487 return XPROCESS (process)->plist;
1490 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1491 2, 2, 0,
1492 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1493 (Lisp_Object process, Lisp_Object plist)
1495 CHECK_PROCESS (process);
1496 CHECK_LIST (plist);
1498 pset_plist (XPROCESS (process), plist);
1499 return plist;
1502 #if 0 /* Turned off because we don't currently record this info
1503 in the process. Perhaps add it. */
1504 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1505 doc: /* Return the connection type of PROCESS.
1506 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1507 a socket connection. */)
1508 (Lisp_Object process)
1510 return XPROCESS (process)->type;
1512 #endif
1514 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1515 doc: /* Return the connection type of PROCESS.
1516 The value is either the symbol `real', `network', `serial', or `pipe'.
1517 PROCESS may be a process, a buffer, the name of a process or buffer, or
1518 nil, indicating the current buffer's process. */)
1519 (Lisp_Object process)
1521 Lisp_Object proc;
1522 proc = get_process (process);
1523 return XPROCESS (proc)->type;
1526 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1527 1, 2, 0,
1528 doc: /* Convert network ADDRESS from internal format to a string.
1529 A 4 or 5 element vector represents an IPv4 address (with port number).
1530 An 8 or 9 element vector represents an IPv6 address (with port number).
1531 If optional second argument OMIT-PORT is non-nil, don't include a port
1532 number in the string, even when present in ADDRESS.
1533 Return nil if format of ADDRESS is invalid. */)
1534 (Lisp_Object address, Lisp_Object omit_port)
1536 if (NILP (address))
1537 return Qnil;
1539 if (STRINGP (address)) /* AF_LOCAL */
1540 return address;
1542 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1544 register struct Lisp_Vector *p = XVECTOR (address);
1545 ptrdiff_t size = p->header.size;
1546 Lisp_Object args[10];
1547 int nargs, i;
1548 char const *format;
1550 if (size == 4 || (size == 5 && !NILP (omit_port)))
1552 format = "%d.%d.%d.%d";
1553 nargs = 4;
1555 else if (size == 5)
1557 format = "%d.%d.%d.%d:%d";
1558 nargs = 5;
1560 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1562 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1563 nargs = 8;
1565 else if (size == 9)
1567 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1568 nargs = 9;
1570 else
1571 return Qnil;
1573 AUTO_STRING (format_obj, format);
1574 args[0] = format_obj;
1576 for (i = 0; i < nargs; i++)
1578 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1579 return Qnil;
1581 if (nargs <= 5 /* IPv4 */
1582 && i < 4 /* host, not port */
1583 && XINT (p->contents[i]) > 255)
1584 return Qnil;
1586 args[i + 1] = p->contents[i];
1589 return Fformat (nargs + 1, args);
1592 if (CONSP (address))
1594 AUTO_STRING (format, "<Family %d>");
1595 return CALLN (Fformat, format, Fcar (address));
1598 return Qnil;
1601 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1602 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1603 (void)
1605 return Fmapcar (Qcdr, Vprocess_alist);
1608 /* Starting asynchronous inferior processes. */
1610 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1611 doc: /* Start a program in a subprocess. Return the process object for it.
1613 This is similar to `start-process', but arguments are specified as
1614 keyword/argument pairs. The following arguments are defined:
1616 :name NAME -- NAME is name for process. It is modified if necessary
1617 to make it unique.
1619 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1620 with the process. Process output goes at end of that buffer, unless
1621 you specify a filter function to handle the output. BUFFER may be
1622 also nil, meaning that this process is not associated with any buffer.
1624 :command COMMAND -- COMMAND is a list starting with the program file
1625 name, followed by strings to give to the program as arguments.
1627 :coding CODING -- If CODING is a symbol, it specifies the coding
1628 system used for both reading and writing for this process. If CODING
1629 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1630 ENCODING is used for writing.
1632 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1633 the process is running. If BOOL is not given, query before exiting.
1635 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1636 In the stopped state, a process does not accept incoming data, but you
1637 can send outgoing data. The stopped state is cleared by
1638 `continue-process' and set by `stop-process'.
1640 :connection-type TYPE -- TYPE is control type of device used to
1641 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1642 to use a pty, or nil to use the default specified through
1643 `process-connection-type'.
1645 :filter FILTER -- Install FILTER as the process filter.
1647 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1649 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1650 to the standard error of subprocess. Specifying this implies
1651 `:connection-type' is set to `pipe'.
1653 usage: (make-process &rest ARGS) */)
1654 (ptrdiff_t nargs, Lisp_Object *args)
1656 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1657 Lisp_Object xstderr, stderrproc;
1658 ptrdiff_t count = SPECPDL_INDEX ();
1660 if (nargs == 0)
1661 return Qnil;
1663 /* Save arguments for process-contact and clone-process. */
1664 contact = Flist (nargs, args);
1666 buffer = Fplist_get (contact, QCbuffer);
1667 if (!NILP (buffer))
1668 buffer = Fget_buffer_create (buffer);
1670 /* Make sure that the child will be able to chdir to the current
1671 buffer's current directory, or its unhandled equivalent. We
1672 can't just have the child check for an error when it does the
1673 chdir, since it's in a vfork. */
1674 current_dir = encode_current_directory ();
1676 name = Fplist_get (contact, QCname);
1677 CHECK_STRING (name);
1679 command = Fplist_get (contact, QCcommand);
1680 if (CONSP (command))
1681 program = XCAR (command);
1682 else
1683 program = Qnil;
1685 if (!NILP (program))
1686 CHECK_STRING (program);
1688 bool query_on_exit = NILP (Fplist_get (contact, QCnoquery));
1690 stderrproc = Qnil;
1691 xstderr = Fplist_get (contact, QCstderr);
1692 if (PROCESSP (xstderr))
1694 if (!PIPECONN_P (xstderr))
1695 error ("Process is not a pipe process");
1696 stderrproc = xstderr;
1698 else if (!NILP (xstderr))
1700 CHECK_STRING (program);
1701 stderrproc = CALLN (Fmake_pipe_process,
1702 QCname,
1703 concat2 (name, build_string (" stderr")),
1704 QCbuffer,
1705 Fget_buffer_create (xstderr),
1706 QCnoquery,
1707 query_on_exit ? Qnil : Qt);
1710 proc = make_process (name);
1711 record_unwind_protect (start_process_unwind, proc);
1713 pset_childp (XPROCESS (proc), Qt);
1714 eassert (NILP (XPROCESS (proc)->plist));
1715 pset_type (XPROCESS (proc), Qreal);
1716 pset_buffer (XPROCESS (proc), buffer);
1717 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1718 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1719 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1721 if (!query_on_exit)
1722 XPROCESS (proc)->kill_without_query = 1;
1723 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1724 pset_command (XPROCESS (proc), Qt);
1726 tem = Fplist_get (contact, QCconnection_type);
1727 if (EQ (tem, Qpty))
1728 XPROCESS (proc)->pty_flag = true;
1729 else if (EQ (tem, Qpipe))
1730 XPROCESS (proc)->pty_flag = false;
1731 else if (NILP (tem))
1732 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1733 else
1734 report_file_error ("Unknown connection type", tem);
1736 if (!NILP (stderrproc))
1738 pset_stderrproc (XPROCESS (proc), stderrproc);
1740 XPROCESS (proc)->pty_flag = false;
1743 #ifdef HAVE_GNUTLS
1744 /* AKA GNUTLS_INITSTAGE(proc). */
1745 verify (GNUTLS_STAGE_EMPTY == 0);
1746 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1747 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1748 #endif
1750 XPROCESS (proc)->adaptive_read_buffering
1751 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1752 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1754 /* Make the process marker point into the process buffer (if any). */
1755 if (BUFFERP (buffer))
1756 set_marker_both (XPROCESS (proc)->mark, buffer,
1757 BUF_ZV (XBUFFER (buffer)),
1758 BUF_ZV_BYTE (XBUFFER (buffer)));
1760 USE_SAFE_ALLOCA;
1763 /* Decide coding systems for communicating with the process. Here
1764 we don't setup the structure coding_system nor pay attention to
1765 unibyte mode. They are done in create_process. */
1767 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1768 Lisp_Object coding_systems = Qt;
1769 Lisp_Object val, *args2;
1771 tem = Fplist_get (contact, QCcoding);
1772 if (!NILP (tem))
1774 val = tem;
1775 if (CONSP (val))
1776 val = XCAR (val);
1778 else
1779 val = Vcoding_system_for_read;
1780 if (NILP (val))
1782 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1783 Lisp_Object tem2;
1784 SAFE_ALLOCA_LISP (args2, nargs2);
1785 ptrdiff_t i = 0;
1786 args2[i++] = Qstart_process;
1787 args2[i++] = name;
1788 args2[i++] = buffer;
1789 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1790 args2[i++] = XCAR (tem2);
1791 if (!NILP (program))
1792 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1793 if (CONSP (coding_systems))
1794 val = XCAR (coding_systems);
1795 else if (CONSP (Vdefault_process_coding_system))
1796 val = XCAR (Vdefault_process_coding_system);
1798 pset_decode_coding_system (XPROCESS (proc), val);
1800 if (!NILP (tem))
1802 val = tem;
1803 if (CONSP (val))
1804 val = XCDR (val);
1806 else
1807 val = Vcoding_system_for_write;
1808 if (NILP (val))
1810 if (EQ (coding_systems, Qt))
1812 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1813 Lisp_Object tem2;
1814 SAFE_ALLOCA_LISP (args2, nargs2);
1815 ptrdiff_t i = 0;
1816 args2[i++] = Qstart_process;
1817 args2[i++] = name;
1818 args2[i++] = buffer;
1819 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1820 args2[i++] = XCAR (tem2);
1821 if (!NILP (program))
1822 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1824 if (CONSP (coding_systems))
1825 val = XCDR (coding_systems);
1826 else if (CONSP (Vdefault_process_coding_system))
1827 val = XCDR (Vdefault_process_coding_system);
1829 pset_encode_coding_system (XPROCESS (proc), val);
1830 /* Note: At this moment, the above coding system may leave
1831 text-conversion or eol-conversion unspecified. They will be
1832 decided after we read output from the process and decode it by
1833 some coding system, or just before we actually send a text to
1834 the process. */
1838 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1839 eassert (XPROCESS (proc)->decoding_carryover == 0);
1840 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1842 XPROCESS (proc)->inherit_coding_system_flag
1843 = !(NILP (buffer) || !inherit_process_coding_system);
1845 if (!NILP (program))
1847 Lisp_Object program_args = XCDR (command);
1849 /* If program file name is not absolute, search our path for it.
1850 Put the name we will really use in TEM. */
1851 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1852 && !(SCHARS (program) > 1
1853 && IS_DEVICE_SEP (SREF (program, 1))))
1855 tem = Qnil;
1856 openp (Vexec_path, program, Vexec_suffixes, &tem,
1857 make_number (X_OK), false);
1858 if (NILP (tem))
1859 report_file_error ("Searching for program", program);
1860 tem = Fexpand_file_name (tem, Qnil);
1862 else
1864 if (!NILP (Ffile_directory_p (program)))
1865 error ("Specified program for new process is a directory");
1866 tem = program;
1869 /* Remove "/:" from TEM. */
1870 tem = remove_slash_colon (tem);
1872 Lisp_Object arg_encoding = Qnil;
1874 /* Encode the file name and put it in NEW_ARGV.
1875 That's where the child will use it to execute the program. */
1876 tem = list1 (ENCODE_FILE (tem));
1877 ptrdiff_t new_argc = 1;
1879 /* Here we encode arguments by the coding system used for sending
1880 data to the process. We don't support using different coding
1881 systems for encoding arguments and for encoding data sent to the
1882 process. */
1884 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1886 Lisp_Object arg = XCAR (tem2);
1887 CHECK_STRING (arg);
1888 if (STRING_MULTIBYTE (arg))
1890 if (NILP (arg_encoding))
1891 arg_encoding = (complement_process_encoding_system
1892 (XPROCESS (proc)->encode_coding_system));
1893 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1895 tem = Fcons (arg, tem);
1896 new_argc++;
1899 /* Now that everything is encoded we can collect the strings into
1900 NEW_ARGV. */
1901 char **new_argv;
1902 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1903 new_argv[new_argc] = 0;
1905 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1907 new_argv[i] = SSDATA (XCAR (tem));
1908 tem = XCDR (tem);
1911 create_process (proc, new_argv, current_dir);
1913 else
1914 create_pty (proc);
1916 SAFE_FREE ();
1917 return unbind_to (count, proc);
1920 /* If PROC doesn't have its pid set, then an error was signaled and
1921 the process wasn't started successfully, so remove it. */
1922 static void
1923 start_process_unwind (Lisp_Object proc)
1925 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1926 remove_process (proc);
1929 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1931 static void
1932 close_process_fd (int *fd_addr)
1934 int fd = *fd_addr;
1935 if (0 <= fd)
1937 *fd_addr = -1;
1938 emacs_close (fd);
1942 /* Indexes of file descriptors in open_fds. */
1943 enum
1945 /* The pipe from Emacs to its subprocess. */
1946 SUBPROCESS_STDIN,
1947 WRITE_TO_SUBPROCESS,
1949 /* The main pipe from the subprocess to Emacs. */
1950 READ_FROM_SUBPROCESS,
1951 SUBPROCESS_STDOUT,
1953 /* The pipe from the subprocess to Emacs that is closed when the
1954 subprocess execs. */
1955 READ_FROM_EXEC_MONITOR,
1956 EXEC_MONITOR_OUTPUT
1959 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1961 static void
1962 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1964 struct Lisp_Process *p = XPROCESS (process);
1965 int inchannel, outchannel;
1966 pid_t pid;
1967 int vfork_errno;
1968 int forkin, forkout, forkerr = -1;
1969 bool pty_flag = 0;
1970 char pty_name[PTY_NAME_SIZE];
1971 Lisp_Object lisp_pty_name = Qnil;
1972 sigset_t oldset;
1974 inchannel = outchannel = -1;
1976 if (p->pty_flag)
1977 outchannel = inchannel = allocate_pty (pty_name);
1979 if (inchannel >= 0)
1981 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1982 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1983 /* On most USG systems it does not work to open the pty's tty here,
1984 then close it and reopen it in the child. */
1985 /* Don't let this terminal become our controlling terminal
1986 (in case we don't have one). */
1987 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1988 if (forkin < 0)
1989 report_file_error ("Opening pty", Qnil);
1990 p->open_fd[SUBPROCESS_STDIN] = forkin;
1991 #else
1992 forkin = forkout = -1;
1993 #endif /* not USG, or USG_SUBTTY_WORKS */
1994 pty_flag = 1;
1995 lisp_pty_name = build_string (pty_name);
1997 else
1999 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2000 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2001 report_file_error ("Creating pipe", Qnil);
2002 forkin = p->open_fd[SUBPROCESS_STDIN];
2003 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2004 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2005 forkout = p->open_fd[SUBPROCESS_STDOUT];
2007 if (!NILP (p->stderrproc))
2009 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2011 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
2013 /* Close unnecessary file descriptors. */
2014 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
2015 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
2019 #ifndef WINDOWSNT
2020 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
2021 report_file_error ("Creating pipe", Qnil);
2022 #endif
2024 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2025 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2027 /* Record this as an active process, with its channels. */
2028 chan_process[inchannel] = process;
2029 p->infd = inchannel;
2030 p->outfd = outchannel;
2032 /* Previously we recorded the tty descriptor used in the subprocess.
2033 It was only used for getting the foreground tty process, so now
2034 we just reopen the device (see emacs_get_tty_pgrp) as this is
2035 more portable (see USG_SUBTTY_WORKS above). */
2037 p->pty_flag = pty_flag;
2038 pset_status (p, Qrun);
2040 if (!EQ (p->command, Qt))
2041 add_process_read_fd (inchannel);
2043 /* This may signal an error. */
2044 setup_process_coding_systems (process);
2046 block_input ();
2047 block_child_signal (&oldset);
2049 #ifndef WINDOWSNT
2050 /* vfork, and prevent local vars from being clobbered by the vfork. */
2051 Lisp_Object volatile current_dir_volatile = current_dir;
2052 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
2053 char **volatile new_argv_volatile = new_argv;
2054 int volatile forkin_volatile = forkin;
2055 int volatile forkout_volatile = forkout;
2056 int volatile forkerr_volatile = forkerr;
2057 struct Lisp_Process *p_volatile = p;
2059 #ifdef DARWIN_OS
2060 /* Darwin doesn't let us run setsid after a vfork, so use fork when
2061 necessary. Also, reset SIGCHLD handling after a vfork, as
2062 apparently macOS can mistakenly deliver SIGCHLD to the child. */
2063 if (pty_flag)
2064 pid = fork ();
2065 else
2067 pid = vfork ();
2068 if (pid == 0)
2069 signal (SIGCHLD, SIG_DFL);
2071 #else
2072 pid = vfork ();
2073 #endif
2075 current_dir = current_dir_volatile;
2076 lisp_pty_name = lisp_pty_name_volatile;
2077 new_argv = new_argv_volatile;
2078 forkin = forkin_volatile;
2079 forkout = forkout_volatile;
2080 forkerr = forkerr_volatile;
2081 p = p_volatile;
2083 pty_flag = p->pty_flag;
2085 if (pid == 0)
2086 #endif /* not WINDOWSNT */
2088 /* Make the pty be the controlling terminal of the process. */
2089 #ifdef HAVE_PTYS
2090 /* First, disconnect its current controlling terminal. */
2091 if (pty_flag)
2092 setsid ();
2093 /* Make the pty's terminal the controlling terminal. */
2094 if (pty_flag && forkin >= 0)
2096 #ifdef TIOCSCTTY
2097 /* We ignore the return value
2098 because faith@cs.unc.edu says that is necessary on Linux. */
2099 ioctl (forkin, TIOCSCTTY, 0);
2100 #endif
2102 #if defined (LDISC1)
2103 if (pty_flag && forkin >= 0)
2105 struct termios t;
2106 tcgetattr (forkin, &t);
2107 t.c_lflag = LDISC1;
2108 if (tcsetattr (forkin, TCSANOW, &t) < 0)
2109 emacs_perror ("create_process/tcsetattr LDISC1");
2111 #else
2112 #if defined (NTTYDISC) && defined (TIOCSETD)
2113 if (pty_flag && forkin >= 0)
2115 /* Use new line discipline. */
2116 int ldisc = NTTYDISC;
2117 ioctl (forkin, TIOCSETD, &ldisc);
2119 #endif
2120 #endif
2121 #ifdef TIOCNOTTY
2122 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2123 can do TIOCSPGRP only to the process's controlling tty. */
2124 if (pty_flag)
2126 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2127 I can't test it since I don't have 4.3. */
2128 int j = emacs_open (DEV_TTY, O_RDWR, 0);
2129 if (j >= 0)
2131 ioctl (j, TIOCNOTTY, 0);
2132 emacs_close (j);
2135 #endif /* TIOCNOTTY */
2137 #if !defined (DONT_REOPEN_PTY)
2138 /*** There is a suggestion that this ought to be a
2139 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2140 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2141 that system does seem to need this code, even though
2142 both TIOCSCTTY is defined. */
2143 /* Now close the pty (if we had it open) and reopen it.
2144 This makes the pty the controlling terminal of the subprocess. */
2145 if (pty_flag)
2148 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2149 would work? */
2150 if (forkin >= 0)
2151 emacs_close (forkin);
2152 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2154 if (forkin < 0)
2156 emacs_perror (SSDATA (lisp_pty_name));
2157 _exit (EXIT_CANCELED);
2161 #endif /* not DONT_REOPEN_PTY */
2163 #ifdef SETUP_SLAVE_PTY
2164 if (pty_flag)
2166 SETUP_SLAVE_PTY;
2168 #endif /* SETUP_SLAVE_PTY */
2169 #endif /* HAVE_PTYS */
2171 signal (SIGINT, SIG_DFL);
2172 signal (SIGQUIT, SIG_DFL);
2173 #ifdef SIGPROF
2174 signal (SIGPROF, SIG_DFL);
2175 #endif
2177 /* Emacs ignores SIGPIPE, but the child should not. */
2178 signal (SIGPIPE, SIG_DFL);
2180 /* Stop blocking SIGCHLD in the child. */
2181 unblock_child_signal (&oldset);
2183 if (pty_flag)
2184 child_setup_tty (forkout);
2186 if (forkerr < 0)
2187 forkerr = forkout;
2188 #ifdef WINDOWSNT
2189 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2190 #else /* not WINDOWSNT */
2191 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2192 #endif /* not WINDOWSNT */
2195 /* Back in the parent process. */
2197 vfork_errno = errno;
2198 p->pid = pid;
2199 if (pid >= 0)
2200 p->alive = 1;
2202 /* Stop blocking in the parent. */
2203 unblock_child_signal (&oldset);
2204 unblock_input ();
2206 if (pid < 0)
2207 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2208 else
2210 /* vfork succeeded. */
2212 /* Close the pipe ends that the child uses, or the child's pty. */
2213 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2214 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2216 #ifdef WINDOWSNT
2217 register_child (pid, inchannel);
2218 #endif /* WINDOWSNT */
2220 pset_tty_name (p, lisp_pty_name);
2222 #ifndef WINDOWSNT
2223 /* Wait for child_setup to complete in case that vfork is
2224 actually defined as fork. The descriptor
2225 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2226 of a pipe is closed at the child side either by close-on-exec
2227 on successful execve or the _exit call in child_setup. */
2229 char dummy;
2231 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2232 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2233 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2235 #endif
2236 if (!NILP (p->stderrproc))
2238 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2239 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2244 static void
2245 create_pty (Lisp_Object process)
2247 struct Lisp_Process *p = XPROCESS (process);
2248 char pty_name[PTY_NAME_SIZE];
2249 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2251 if (pty_fd >= 0)
2253 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2254 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2255 /* On most USG systems it does not work to open the pty's tty here,
2256 then close it and reopen it in the child. */
2257 /* Don't let this terminal become our controlling terminal
2258 (in case we don't have one). */
2259 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2260 if (forkout < 0)
2261 report_file_error ("Opening pty", Qnil);
2262 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2263 #if defined (DONT_REOPEN_PTY)
2264 /* In the case that vfork is defined as fork, the parent process
2265 (Emacs) may send some data before the child process completes
2266 tty options setup. So we setup tty before forking. */
2267 child_setup_tty (forkout);
2268 #endif /* DONT_REOPEN_PTY */
2269 #endif /* not USG, or USG_SUBTTY_WORKS */
2271 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2273 /* Record this as an active process, with its channels.
2274 As a result, child_setup will close Emacs's side of the pipes. */
2275 chan_process[pty_fd] = process;
2276 p->infd = pty_fd;
2277 p->outfd = pty_fd;
2279 /* Previously we recorded the tty descriptor used in the subprocess.
2280 It was only used for getting the foreground tty process, so now
2281 we just reopen the device (see emacs_get_tty_pgrp) as this is
2282 more portable (see USG_SUBTTY_WORKS above). */
2284 p->pty_flag = 1;
2285 pset_status (p, Qrun);
2286 setup_process_coding_systems (process);
2288 add_process_read_fd (pty_fd);
2290 pset_tty_name (p, build_string (pty_name));
2293 p->pid = -2;
2296 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2297 0, MANY, 0,
2298 doc: /* Create and return a bidirectional pipe process.
2300 In Emacs, pipes are represented by process objects, so input and
2301 output work as for subprocesses, and `delete-process' closes a pipe.
2302 However, a pipe process has no process id, it cannot be signaled,
2303 and the status codes are different from normal processes.
2305 Arguments are specified as keyword/argument pairs. The following
2306 arguments are defined:
2308 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2310 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2311 with the process. Process output goes at the end of that buffer,
2312 unless you specify a filter function to handle the output. If BUFFER
2313 is not given, the value of NAME is used.
2315 :coding CODING -- If CODING is a symbol, it specifies the coding
2316 system used for both reading and writing for this process. If CODING
2317 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2318 ENCODING is used for writing.
2320 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2321 the process is running. If BOOL is not given, query before exiting.
2323 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2324 In the stopped state, a pipe process does not accept incoming data,
2325 but you can send outgoing data. The stopped state is cleared by
2326 `continue-process' and set by `stop-process'.
2328 :filter FILTER -- Install FILTER as the process filter.
2330 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2332 usage: (make-pipe-process &rest ARGS) */)
2333 (ptrdiff_t nargs, Lisp_Object *args)
2335 Lisp_Object proc, contact;
2336 struct Lisp_Process *p;
2337 Lisp_Object name, buffer;
2338 Lisp_Object tem;
2339 ptrdiff_t specpdl_count;
2340 int inchannel, outchannel;
2342 if (nargs == 0)
2343 return Qnil;
2345 contact = Flist (nargs, args);
2347 name = Fplist_get (contact, QCname);
2348 CHECK_STRING (name);
2349 proc = make_process (name);
2350 specpdl_count = SPECPDL_INDEX ();
2351 record_unwind_protect (remove_process, proc);
2352 p = XPROCESS (proc);
2354 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2355 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2356 report_file_error ("Creating pipe", Qnil);
2357 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2358 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2360 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2361 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2363 #ifdef WINDOWSNT
2364 register_aux_fd (inchannel);
2365 #endif
2367 /* Record this as an active process, with its channels. */
2368 chan_process[inchannel] = proc;
2369 p->infd = inchannel;
2370 p->outfd = outchannel;
2372 if (inchannel > max_desc)
2373 max_desc = inchannel;
2375 buffer = Fplist_get (contact, QCbuffer);
2376 if (NILP (buffer))
2377 buffer = name;
2378 buffer = Fget_buffer_create (buffer);
2379 pset_buffer (p, buffer);
2381 pset_childp (p, contact);
2382 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2383 pset_type (p, Qpipe);
2384 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2385 pset_filter (p, Fplist_get (contact, QCfilter));
2386 eassert (NILP (p->log));
2387 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2388 p->kill_without_query = 1;
2389 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2390 pset_command (p, Qt);
2391 eassert (! p->pty_flag);
2393 if (!EQ (p->command, Qt))
2394 add_process_read_fd (inchannel);
2395 p->adaptive_read_buffering
2396 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2397 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2399 /* Make the process marker point into the process buffer (if any). */
2400 if (BUFFERP (buffer))
2401 set_marker_both (p->mark, buffer,
2402 BUF_ZV (XBUFFER (buffer)),
2403 BUF_ZV_BYTE (XBUFFER (buffer)));
2406 /* Setup coding systems for communicating with the network stream. */
2408 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2409 Lisp_Object coding_systems = Qt;
2410 Lisp_Object val;
2412 tem = Fplist_get (contact, QCcoding);
2413 val = Qnil;
2414 if (!NILP (tem))
2416 val = tem;
2417 if (CONSP (val))
2418 val = XCAR (val);
2420 else if (!NILP (Vcoding_system_for_read))
2421 val = Vcoding_system_for_read;
2422 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2423 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2424 /* We dare not decode end-of-line format by setting VAL to
2425 Qraw_text, because the existing Emacs Lisp libraries
2426 assume that they receive bare code including a sequence of
2427 CR LF. */
2428 val = Qnil;
2429 else
2431 if (CONSP (coding_systems))
2432 val = XCAR (coding_systems);
2433 else if (CONSP (Vdefault_process_coding_system))
2434 val = XCAR (Vdefault_process_coding_system);
2435 else
2436 val = Qnil;
2438 pset_decode_coding_system (p, val);
2440 if (!NILP (tem))
2442 val = tem;
2443 if (CONSP (val))
2444 val = XCDR (val);
2446 else if (!NILP (Vcoding_system_for_write))
2447 val = Vcoding_system_for_write;
2448 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2449 val = Qnil;
2450 else
2452 if (CONSP (coding_systems))
2453 val = XCDR (coding_systems);
2454 else if (CONSP (Vdefault_process_coding_system))
2455 val = XCDR (Vdefault_process_coding_system);
2456 else
2457 val = Qnil;
2459 pset_encode_coding_system (p, val);
2461 /* This may signal an error. */
2462 setup_process_coding_systems (proc);
2464 specpdl_ptr = specpdl + specpdl_count;
2466 return proc;
2470 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2471 The address family of sa is not included in the result. */
2473 Lisp_Object
2474 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2476 Lisp_Object address;
2477 ptrdiff_t i;
2478 unsigned char *cp;
2479 struct Lisp_Vector *p;
2481 /* Workaround for a bug in getsockname on BSD: Names bound to
2482 sockets in the UNIX domain are inaccessible; getsockname returns
2483 a zero length name. */
2484 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2485 return empty_unibyte_string;
2487 switch (sa->sa_family)
2489 case AF_INET:
2491 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2492 len = sizeof (sin->sin_addr) + 1;
2493 address = Fmake_vector (make_number (len), Qnil);
2494 p = XVECTOR (address);
2495 p->contents[--len] = make_number (ntohs (sin->sin_port));
2496 cp = (unsigned char *) &sin->sin_addr;
2497 break;
2499 #ifdef AF_INET6
2500 case AF_INET6:
2502 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2503 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2504 len = sizeof (sin6->sin6_addr) / 2 + 1;
2505 address = Fmake_vector (make_number (len), Qnil);
2506 p = XVECTOR (address);
2507 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2508 for (i = 0; i < len; i++)
2509 p->contents[i] = make_number (ntohs (ip6[i]));
2510 return address;
2512 #endif
2513 #ifdef HAVE_LOCAL_SOCKETS
2514 case AF_LOCAL:
2516 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2517 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2518 /* If the first byte is NUL, the name is a Linux abstract
2519 socket name, and the name can contain embedded NULs. If
2520 it's not, we have a NUL-terminated string. Be careful not
2521 to walk past the end of the object looking for the name
2522 terminator, however. */
2523 if (name_length > 0 && sockun->sun_path[0] != '\0')
2525 const char *terminator
2526 = memchr (sockun->sun_path, '\0', name_length);
2528 if (terminator)
2529 name_length = terminator - (const char *) sockun->sun_path;
2532 return make_unibyte_string (sockun->sun_path, name_length);
2534 #endif
2535 default:
2536 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2537 address = Fcons (make_number (sa->sa_family),
2538 Fmake_vector (make_number (len), Qnil));
2539 p = XVECTOR (XCDR (address));
2540 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2541 break;
2544 i = 0;
2545 while (i < len)
2546 p->contents[i++] = make_number (*cp++);
2548 return address;
2551 /* Convert an internal struct addrinfo to a Lisp object. */
2553 static Lisp_Object
2554 conv_addrinfo_to_lisp (struct addrinfo *res)
2556 Lisp_Object protocol = make_number (res->ai_protocol);
2557 eassert (XINT (protocol) == res->ai_protocol);
2558 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2562 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2564 static ptrdiff_t
2565 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2567 struct Lisp_Vector *p;
2569 if (VECTORP (address))
2571 p = XVECTOR (address);
2572 if (p->header.size == 5)
2574 *familyp = AF_INET;
2575 return sizeof (struct sockaddr_in);
2577 #ifdef AF_INET6
2578 else if (p->header.size == 9)
2580 *familyp = AF_INET6;
2581 return sizeof (struct sockaddr_in6);
2583 #endif
2585 #ifdef HAVE_LOCAL_SOCKETS
2586 else if (STRINGP (address))
2588 *familyp = AF_LOCAL;
2589 return sizeof (struct sockaddr_un);
2591 #endif
2592 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2593 && VECTORP (XCDR (address)))
2595 struct sockaddr *sa;
2596 p = XVECTOR (XCDR (address));
2597 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2598 return 0;
2599 *familyp = XINT (XCAR (address));
2600 return p->header.size + sizeof (sa->sa_family);
2602 return 0;
2605 /* Convert an address object (vector or string) to an internal sockaddr.
2607 The address format has been basically validated by
2608 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2609 it could have come from user data. So if FAMILY is not valid,
2610 we return after zeroing *SA. */
2612 static void
2613 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2615 register struct Lisp_Vector *p;
2616 register unsigned char *cp = NULL;
2617 register int i;
2618 EMACS_INT hostport;
2620 memset (sa, 0, len);
2622 if (VECTORP (address))
2624 p = XVECTOR (address);
2625 if (family == AF_INET)
2627 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2628 len = sizeof (sin->sin_addr) + 1;
2629 hostport = XINT (p->contents[--len]);
2630 sin->sin_port = htons (hostport);
2631 cp = (unsigned char *)&sin->sin_addr;
2632 sa->sa_family = family;
2634 #ifdef AF_INET6
2635 else if (family == AF_INET6)
2637 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2638 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2639 len = sizeof (sin6->sin6_addr) / 2 + 1;
2640 hostport = XINT (p->contents[--len]);
2641 sin6->sin6_port = htons (hostport);
2642 for (i = 0; i < len; i++)
2643 if (INTEGERP (p->contents[i]))
2645 int j = XFASTINT (p->contents[i]) & 0xffff;
2646 ip6[i] = ntohs (j);
2648 sa->sa_family = family;
2649 return;
2651 #endif
2652 else
2653 return;
2655 else if (STRINGP (address))
2657 #ifdef HAVE_LOCAL_SOCKETS
2658 if (family == AF_LOCAL)
2660 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2661 cp = SDATA (address);
2662 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2663 sockun->sun_path[i] = *cp++;
2664 sa->sa_family = family;
2666 #endif
2667 return;
2669 else
2671 p = XVECTOR (XCDR (address));
2672 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2675 for (i = 0; i < len; i++)
2676 if (INTEGERP (p->contents[i]))
2677 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2680 #ifdef DATAGRAM_SOCKETS
2681 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2682 1, 1, 0,
2683 doc: /* Get the current datagram address associated with PROCESS.
2684 If PROCESS is a non-blocking network process that hasn't been fully
2685 set up yet, this function will block until socket setup has completed. */)
2686 (Lisp_Object process)
2688 int channel;
2690 CHECK_PROCESS (process);
2692 if (NETCONN_P (process))
2693 wait_for_socket_fds (process, "process-datagram-address");
2695 if (!DATAGRAM_CONN_P (process))
2696 return Qnil;
2698 channel = XPROCESS (process)->infd;
2699 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2700 datagram_address[channel].len);
2703 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2704 2, 2, 0,
2705 doc: /* Set the datagram address for PROCESS to ADDRESS.
2706 Return nil upon error setting address, ADDRESS otherwise.
2708 If PROCESS is a non-blocking network process that hasn't been fully
2709 set up yet, this function will block until socket setup has completed. */)
2710 (Lisp_Object process, Lisp_Object address)
2712 int channel;
2713 int family;
2714 ptrdiff_t len;
2716 CHECK_PROCESS (process);
2718 if (NETCONN_P (process))
2719 wait_for_socket_fds (process, "set-process-datagram-address");
2721 if (!DATAGRAM_CONN_P (process))
2722 return Qnil;
2724 channel = XPROCESS (process)->infd;
2726 len = get_lisp_to_sockaddr_size (address, &family);
2727 if (len == 0 || datagram_address[channel].len != len)
2728 return Qnil;
2729 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2730 return address;
2732 #endif
2735 static const struct socket_options {
2736 /* The name of this option. Should be lowercase version of option
2737 name without SO_ prefix. */
2738 const char *name;
2739 /* Option level SOL_... */
2740 int optlevel;
2741 /* Option number SO_... */
2742 int optnum;
2743 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2744 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2745 } socket_options[] =
2747 #ifdef SO_BINDTODEVICE
2748 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2749 #endif
2750 #ifdef SO_BROADCAST
2751 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2752 #endif
2753 #ifdef SO_DONTROUTE
2754 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2755 #endif
2756 #ifdef SO_KEEPALIVE
2757 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2758 #endif
2759 #ifdef SO_LINGER
2760 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2761 #endif
2762 #ifdef SO_OOBINLINE
2763 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2764 #endif
2765 #ifdef SO_PRIORITY
2766 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2767 #endif
2768 #ifdef SO_REUSEADDR
2769 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2770 #endif
2771 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2774 /* Set option OPT to value VAL on socket S.
2776 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2777 Signals an error if setting a known option fails.
2780 static int
2781 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2783 char *name;
2784 const struct socket_options *sopt;
2785 int ret = 0;
2787 CHECK_SYMBOL (opt);
2789 name = SSDATA (SYMBOL_NAME (opt));
2790 for (sopt = socket_options; sopt->name; sopt++)
2791 if (strcmp (name, sopt->name) == 0)
2792 break;
2794 switch (sopt->opttype)
2796 case SOPT_BOOL:
2798 int optval;
2799 optval = NILP (val) ? 0 : 1;
2800 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2801 &optval, sizeof (optval));
2802 break;
2805 case SOPT_INT:
2807 int optval;
2808 if (TYPE_RANGED_INTEGERP (int, val))
2809 optval = XINT (val);
2810 else
2811 error ("Bad option value for %s", name);
2812 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2813 &optval, sizeof (optval));
2814 break;
2817 #ifdef SO_BINDTODEVICE
2818 case SOPT_IFNAME:
2820 char devname[IFNAMSIZ + 1];
2822 /* This is broken, at least in the Linux 2.4 kernel.
2823 To unbind, the arg must be a zero integer, not the empty string.
2824 This should work on all systems. KFS. 2003-09-23. */
2825 memset (devname, 0, sizeof devname);
2826 if (STRINGP (val))
2828 char *arg = SSDATA (val);
2829 int len = min (strlen (arg), IFNAMSIZ);
2830 memcpy (devname, arg, len);
2832 else if (!NILP (val))
2833 error ("Bad option value for %s", name);
2834 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2835 devname, IFNAMSIZ);
2836 break;
2838 #endif
2840 #ifdef SO_LINGER
2841 case SOPT_LINGER:
2843 struct linger linger;
2845 linger.l_onoff = 1;
2846 linger.l_linger = 0;
2847 if (TYPE_RANGED_INTEGERP (int, val))
2848 linger.l_linger = XINT (val);
2849 else
2850 linger.l_onoff = NILP (val) ? 0 : 1;
2851 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2852 &linger, sizeof (linger));
2853 break;
2855 #endif
2857 default:
2858 return 0;
2861 if (ret < 0)
2863 int setsockopt_errno = errno;
2864 report_file_errno ("Cannot set network option", list2 (opt, val),
2865 setsockopt_errno);
2868 return (1 << sopt->optbit);
2872 DEFUN ("set-network-process-option",
2873 Fset_network_process_option, Sset_network_process_option,
2874 3, 4, 0,
2875 doc: /* For network process PROCESS set option OPTION to value VALUE.
2876 See `make-network-process' for a list of options and values.
2877 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2878 OPTION is not a supported option, return nil instead; otherwise return t.
2880 If PROCESS is a non-blocking network process that hasn't been fully
2881 set up yet, this function will block until socket setup has completed. */)
2882 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2884 int s;
2885 struct Lisp_Process *p;
2887 CHECK_PROCESS (process);
2888 p = XPROCESS (process);
2889 if (!NETCONN1_P (p))
2890 error ("Process is not a network process");
2892 wait_for_socket_fds (process, "set-network-process-option");
2894 s = p->infd;
2895 if (s < 0)
2896 error ("Process is not running");
2898 if (set_socket_option (s, option, value))
2900 pset_childp (p, Fplist_put (p->childp, option, value));
2901 return Qt;
2904 if (NILP (no_error))
2905 error ("Unknown or unsupported option");
2907 return Qnil;
2911 DEFUN ("serial-process-configure",
2912 Fserial_process_configure,
2913 Sserial_process_configure,
2914 0, MANY, 0,
2915 doc: /* Configure speed, bytesize, etc. of a serial process.
2917 Arguments are specified as keyword/argument pairs. Attributes that
2918 are not given are re-initialized from the process's current
2919 configuration (available via the function `process-contact') or set to
2920 reasonable default values. The following arguments are defined:
2922 :process PROCESS
2923 :name NAME
2924 :buffer BUFFER
2925 :port PORT
2926 -- Any of these arguments can be given to identify the process that is
2927 to be configured. If none of these arguments is given, the current
2928 buffer's process is used.
2930 :speed SPEED -- SPEED is the speed of the serial port in bits per
2931 second, also called baud rate. Any value can be given for SPEED, but
2932 most serial ports work only at a few defined values between 1200 and
2933 115200, with 9600 being the most common value. If SPEED is nil, the
2934 serial port is not configured any further, i.e., all other arguments
2935 are ignored. This may be useful for special serial ports such as
2936 Bluetooth-to-serial converters which can only be configured through AT
2937 commands. A value of nil for SPEED can be used only when passed
2938 through `make-serial-process' or `serial-term'.
2940 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2941 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2943 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2944 `odd' (use odd parity), or the symbol `even' (use even parity). If
2945 PARITY is not given, no parity is used.
2947 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2948 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2949 is not given or nil, 1 stopbit is used.
2951 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2952 flowcontrol to be used, which is either nil (don't use flowcontrol),
2953 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2954 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2955 flowcontrol is used.
2957 `serial-process-configure' is called by `make-serial-process' for the
2958 initial configuration of the serial port.
2960 Examples:
2962 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2964 \(serial-process-configure
2965 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2967 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2969 usage: (serial-process-configure &rest ARGS) */)
2970 (ptrdiff_t nargs, Lisp_Object *args)
2972 struct Lisp_Process *p;
2973 Lisp_Object contact = Qnil;
2974 Lisp_Object proc = Qnil;
2976 contact = Flist (nargs, args);
2978 proc = Fplist_get (contact, QCprocess);
2979 if (NILP (proc))
2980 proc = Fplist_get (contact, QCname);
2981 if (NILP (proc))
2982 proc = Fplist_get (contact, QCbuffer);
2983 if (NILP (proc))
2984 proc = Fplist_get (contact, QCport);
2985 proc = get_process (proc);
2986 p = XPROCESS (proc);
2987 if (!EQ (p->type, Qserial))
2988 error ("Not a serial process");
2990 if (NILP (Fplist_get (p->childp, QCspeed)))
2991 return Qnil;
2993 serial_configure (p, contact);
2994 return Qnil;
2997 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2998 0, MANY, 0,
2999 doc: /* Create and return a serial port process.
3001 In Emacs, serial port connections are represented by process objects,
3002 so input and output work as for subprocesses, and `delete-process'
3003 closes a serial port connection. However, a serial process has no
3004 process id, it cannot be signaled, and the status codes are different
3005 from normal processes.
3007 `make-serial-process' creates a process and a buffer, on which you
3008 probably want to use `process-send-string'. Try \\[serial-term] for
3009 an interactive terminal. See below for examples.
3011 Arguments are specified as keyword/argument pairs. The following
3012 arguments are defined:
3014 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3015 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
3016 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3017 the backslashes in strings).
3019 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3020 which this function calls.
3022 :name NAME -- NAME is the name of the process. If NAME is not given,
3023 the value of PORT is used.
3025 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3026 with the process. Process output goes at the end of that buffer,
3027 unless you specify a filter function to handle the output. If BUFFER
3028 is not given, the value of NAME is used.
3030 :coding CODING -- If CODING is a symbol, it specifies the coding
3031 system used for both reading and writing for this process. If CODING
3032 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3033 ENCODING is used for writing.
3035 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3036 the process is running. If BOOL is not given, query before exiting.
3038 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3039 In the stopped state, a serial process does not accept incoming data,
3040 but you can send outgoing data. The stopped state is cleared by
3041 `continue-process' and set by `stop-process'.
3043 :filter FILTER -- Install FILTER as the process filter.
3045 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3047 :plist PLIST -- Install PLIST as the initial plist of the process.
3049 :bytesize
3050 :parity
3051 :stopbits
3052 :flowcontrol
3053 -- This function calls `serial-process-configure' to handle these
3054 arguments.
3056 The original argument list, possibly modified by later configuration,
3057 is available via the function `process-contact'.
3059 Examples:
3061 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3063 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3065 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3067 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3069 usage: (make-serial-process &rest ARGS) */)
3070 (ptrdiff_t nargs, Lisp_Object *args)
3072 int fd = -1;
3073 Lisp_Object proc, contact, port;
3074 struct Lisp_Process *p;
3075 Lisp_Object name, buffer;
3076 Lisp_Object tem, val;
3077 ptrdiff_t specpdl_count;
3079 if (nargs == 0)
3080 return Qnil;
3082 contact = Flist (nargs, args);
3084 port = Fplist_get (contact, QCport);
3085 if (NILP (port))
3086 error ("No port specified");
3087 CHECK_STRING (port);
3089 if (NILP (Fplist_member (contact, QCspeed)))
3090 error (":speed not specified");
3091 if (!NILP (Fplist_get (contact, QCspeed)))
3092 CHECK_NUMBER (Fplist_get (contact, QCspeed));
3094 name = Fplist_get (contact, QCname);
3095 if (NILP (name))
3096 name = port;
3097 CHECK_STRING (name);
3098 proc = make_process (name);
3099 specpdl_count = SPECPDL_INDEX ();
3100 record_unwind_protect (remove_process, proc);
3101 p = XPROCESS (proc);
3103 fd = serial_open (port);
3104 p->open_fd[SUBPROCESS_STDIN] = fd;
3105 p->infd = fd;
3106 p->outfd = fd;
3107 if (fd > max_desc)
3108 max_desc = fd;
3109 chan_process[fd] = proc;
3111 buffer = Fplist_get (contact, QCbuffer);
3112 if (NILP (buffer))
3113 buffer = name;
3114 buffer = Fget_buffer_create (buffer);
3115 pset_buffer (p, buffer);
3117 pset_childp (p, contact);
3118 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3119 pset_type (p, Qserial);
3120 pset_sentinel (p, Fplist_get (contact, QCsentinel));
3121 pset_filter (p, Fplist_get (contact, QCfilter));
3122 eassert (NILP (p->log));
3123 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3124 p->kill_without_query = 1;
3125 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3126 pset_command (p, Qt);
3127 eassert (! p->pty_flag);
3129 if (!EQ (p->command, Qt))
3130 add_process_read_fd (fd);
3132 if (BUFFERP (buffer))
3134 set_marker_both (p->mark, buffer,
3135 BUF_ZV (XBUFFER (buffer)),
3136 BUF_ZV_BYTE (XBUFFER (buffer)));
3139 tem = Fplist_member (contact, QCcoding);
3140 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3141 tem = Qnil;
3143 val = Qnil;
3144 if (!NILP (tem))
3146 val = XCAR (XCDR (tem));
3147 if (CONSP (val))
3148 val = XCAR (val);
3150 else if (!NILP (Vcoding_system_for_read))
3151 val = Vcoding_system_for_read;
3152 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3153 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3154 val = Qnil;
3155 pset_decode_coding_system (p, val);
3157 val = Qnil;
3158 if (!NILP (tem))
3160 val = XCAR (XCDR (tem));
3161 if (CONSP (val))
3162 val = XCDR (val);
3164 else if (!NILP (Vcoding_system_for_write))
3165 val = Vcoding_system_for_write;
3166 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3167 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3168 val = Qnil;
3169 pset_encode_coding_system (p, val);
3171 setup_process_coding_systems (proc);
3172 pset_decoding_buf (p, empty_unibyte_string);
3173 eassert (p->decoding_carryover == 0);
3174 pset_encoding_buf (p, empty_unibyte_string);
3175 p->inherit_coding_system_flag
3176 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3178 Fserial_process_configure (nargs, args);
3180 specpdl_ptr = specpdl + specpdl_count;
3182 return proc;
3185 static void
3186 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
3187 Lisp_Object service, Lisp_Object name)
3189 Lisp_Object tem;
3190 struct Lisp_Process *p = XPROCESS (proc);
3191 Lisp_Object contact = p->childp;
3192 Lisp_Object coding_systems = Qt;
3193 Lisp_Object val;
3195 tem = Fplist_member (contact, QCcoding);
3196 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3197 tem = Qnil; /* No error message (too late!). */
3199 /* Setup coding systems for communicating with the network stream. */
3200 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3202 if (!NILP (tem))
3204 val = XCAR (XCDR (tem));
3205 if (CONSP (val))
3206 val = XCAR (val);
3208 else if (!NILP (Vcoding_system_for_read))
3209 val = Vcoding_system_for_read;
3210 else if ((!NILP (p->buffer)
3211 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3212 || (NILP (p->buffer)
3213 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3214 /* We dare not decode end-of-line format by setting VAL to
3215 Qraw_text, because the existing Emacs Lisp libraries
3216 assume that they receive bare code including a sequence of
3217 CR LF. */
3218 val = Qnil;
3219 else
3221 if (NILP (host) || NILP (service))
3222 coding_systems = Qnil;
3223 else
3224 coding_systems = CALLN (Ffind_operation_coding_system,
3225 Qopen_network_stream, name, p->buffer,
3226 host, service);
3227 if (CONSP (coding_systems))
3228 val = XCAR (coding_systems);
3229 else if (CONSP (Vdefault_process_coding_system))
3230 val = XCAR (Vdefault_process_coding_system);
3231 else
3232 val = Qnil;
3234 pset_decode_coding_system (p, val);
3236 if (!NILP (tem))
3238 val = XCAR (XCDR (tem));
3239 if (CONSP (val))
3240 val = XCDR (val);
3242 else if (!NILP (Vcoding_system_for_write))
3243 val = Vcoding_system_for_write;
3244 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3245 val = Qnil;
3246 else
3248 if (EQ (coding_systems, Qt))
3250 if (NILP (host) || NILP (service))
3251 coding_systems = Qnil;
3252 else
3253 coding_systems = CALLN (Ffind_operation_coding_system,
3254 Qopen_network_stream, name, p->buffer,
3255 host, service);
3257 if (CONSP (coding_systems))
3258 val = XCDR (coding_systems);
3259 else if (CONSP (Vdefault_process_coding_system))
3260 val = XCDR (Vdefault_process_coding_system);
3261 else
3262 val = Qnil;
3264 pset_encode_coding_system (p, val);
3266 pset_decoding_buf (p, empty_unibyte_string);
3267 p->decoding_carryover = 0;
3268 pset_encoding_buf (p, empty_unibyte_string);
3270 p->inherit_coding_system_flag
3271 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3274 #ifdef HAVE_GNUTLS
3275 static void
3276 finish_after_tls_connection (Lisp_Object proc)
3278 struct Lisp_Process *p = XPROCESS (proc);
3279 Lisp_Object contact = p->childp;
3280 Lisp_Object result = Qt;
3282 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3283 result = call3 (Qnsm_verify_connection,
3284 proc,
3285 Fplist_get (contact, QChost),
3286 Fplist_get (contact, QCservice));
3288 if (NILP (result))
3290 pset_status (p, list2 (Qfailed,
3291 build_string ("The Network Security Manager stopped the connections")));
3292 deactivate_process (proc);
3294 else if (p->outfd < 0)
3296 /* The counterparty may have closed the connection (especially
3297 if the NSM prompt above take a long time), so recheck the file
3298 descriptor here. */
3299 pset_status (p, Qfailed);
3300 deactivate_process (proc);
3302 else if ((fd_callback_info[p->outfd].flags & NON_BLOCKING_CONNECT_FD) == 0)
3304 /* If we cleared the connection wait mask before we did the TLS
3305 setup, then we have to say that the process is finally "open"
3306 here. */
3307 pset_status (p, Qrun);
3308 /* Execute the sentinel here. If we had relied on status_notify
3309 to do it later, it will read input from the process before
3310 calling the sentinel. */
3311 exec_sentinel (proc, build_string ("open\n"));
3314 #endif
3316 static void
3317 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3318 Lisp_Object use_external_socket_p)
3320 ptrdiff_t count = SPECPDL_INDEX ();
3321 int s = -1, outch, inch;
3322 int xerrno = 0;
3323 int family;
3324 struct sockaddr *sa = NULL;
3325 int ret;
3326 ptrdiff_t addrlen;
3327 struct Lisp_Process *p = XPROCESS (proc);
3328 Lisp_Object contact = p->childp;
3329 int optbits = 0;
3330 int socket_to_use = -1;
3332 if (!NILP (use_external_socket_p))
3334 socket_to_use = external_sock_fd;
3336 /* Ensure we don't consume the external socket twice. */
3337 external_sock_fd = -1;
3340 /* Do this in case we never enter the while-loop below. */
3341 s = -1;
3343 while (!NILP (addrinfos))
3345 Lisp_Object addrinfo = XCAR (addrinfos);
3346 addrinfos = XCDR (addrinfos);
3347 int protocol = XINT (XCAR (addrinfo));
3348 Lisp_Object ip_address = XCDR (addrinfo);
3350 #ifdef WINDOWSNT
3351 retry_connect:
3352 #endif
3354 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3355 if (sa)
3356 free (sa);
3357 sa = xmalloc (addrlen);
3358 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3360 s = socket_to_use;
3361 if (s < 0)
3363 int socktype = p->socktype | SOCK_CLOEXEC;
3364 if (p->is_non_blocking_client)
3365 socktype |= SOCK_NONBLOCK;
3366 s = socket (family, socktype, protocol);
3367 if (s < 0)
3369 xerrno = errno;
3370 continue;
3374 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3376 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3377 if (ret < 0)
3379 xerrno = errno;
3380 emacs_close (s);
3381 s = -1;
3382 if (0 <= socket_to_use)
3383 break;
3384 continue;
3388 #ifdef DATAGRAM_SOCKETS
3389 if (!p->is_server && p->socktype == SOCK_DGRAM)
3390 break;
3391 #endif /* DATAGRAM_SOCKETS */
3393 /* Make us close S if quit. */
3394 record_unwind_protect_int (close_file_unwind, s);
3396 /* Parse network options in the arg list. We simply ignore anything
3397 which isn't a known option (including other keywords). An error
3398 is signaled if setting a known option fails. */
3400 Lisp_Object params = contact, key, val;
3402 while (!NILP (params))
3404 key = XCAR (params);
3405 params = XCDR (params);
3406 val = XCAR (params);
3407 params = XCDR (params);
3408 optbits |= set_socket_option (s, key, val);
3412 if (p->is_server)
3414 /* Configure as a server socket. */
3416 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3417 explicit :reuseaddr key to override this. */
3418 #ifdef HAVE_LOCAL_SOCKETS
3419 if (family != AF_LOCAL)
3420 #endif
3421 if (!(optbits & (1 << OPIX_REUSEADDR)))
3423 int optval = 1;
3424 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3425 report_file_error ("Cannot set reuse option on server socket", Qnil);
3428 /* If passed a socket descriptor, it should be already bound. */
3429 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3430 report_file_error ("Cannot bind server socket", Qnil);
3432 #ifdef HAVE_GETSOCKNAME
3433 if (p->port == 0
3434 #ifdef HAVE_LOCAL_SOCKETS
3435 && family != AF_LOCAL
3436 #endif
3439 struct sockaddr_in sa1;
3440 socklen_t len1 = sizeof (sa1);
3441 #ifdef AF_INET6
3442 /* The code below assumes the port is at the same offset
3443 and of the same width in both IPv4 and IPv6
3444 structures, but the standards don't guarantee that,
3445 so verify it here. */
3446 struct sockaddr_in6 sa6;
3447 verify ((offsetof (struct sockaddr_in, sin_port)
3448 == offsetof (struct sockaddr_in6, sin6_port))
3449 && sizeof (sa1.sin_port) == sizeof (sa6.sin6_port));
3450 #endif
3451 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3452 if (getsockname (s, psa1, &len1) == 0)
3454 Lisp_Object service = make_number (ntohs (sa1.sin_port));
3455 contact = Fplist_put (contact, QCservice, service);
3456 /* Save the port number so that we can stash it in
3457 the process object later. */
3458 DECLARE_POINTER_ALIAS (psa, struct sockaddr_in, sa);
3459 psa->sin_port = sa1.sin_port;
3462 #endif
3464 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3465 report_file_error ("Cannot listen on server socket", Qnil);
3467 break;
3470 maybe_quit ();
3472 ret = connect (s, sa, addrlen);
3473 xerrno = errno;
3475 if (ret == 0 || xerrno == EISCONN)
3477 /* The unwind-protect will be discarded afterwards. */
3478 break;
3481 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3482 break;
3484 #ifndef WINDOWSNT
3485 if (xerrno == EINTR)
3487 /* Unlike most other syscalls connect() cannot be called
3488 again. (That would return EALREADY.) The proper way to
3489 wait for completion is pselect(). */
3490 int sc;
3491 socklen_t len;
3492 fd_set fdset;
3493 retry_select:
3494 FD_ZERO (&fdset);
3495 FD_SET (s, &fdset);
3496 maybe_quit ();
3497 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3498 if (sc == -1)
3500 if (errno == EINTR)
3501 goto retry_select;
3502 else
3503 report_file_error ("Failed select", Qnil);
3505 eassert (sc > 0);
3507 len = sizeof xerrno;
3508 eassert (FD_ISSET (s, &fdset));
3509 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3510 report_file_error ("Failed getsockopt", Qnil);
3511 if (xerrno == 0)
3512 break;
3513 if (NILP (addrinfos))
3514 report_file_errno ("Failed connect", Qnil, xerrno);
3516 #endif /* !WINDOWSNT */
3518 /* Discard the unwind protect closing S. */
3519 specpdl_ptr = specpdl + count;
3520 emacs_close (s);
3521 s = -1;
3522 if (0 <= socket_to_use)
3523 break;
3525 #ifdef WINDOWSNT
3526 if (xerrno == EINTR)
3527 goto retry_connect;
3528 #endif
3531 if (s >= 0)
3533 #ifdef DATAGRAM_SOCKETS
3534 if (p->socktype == SOCK_DGRAM)
3536 if (datagram_address[s].sa)
3537 emacs_abort ();
3539 datagram_address[s].sa = xmalloc (addrlen);
3540 datagram_address[s].len = addrlen;
3541 if (p->is_server)
3543 Lisp_Object remote;
3544 memset (datagram_address[s].sa, 0, addrlen);
3545 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3547 int rfamily;
3548 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3549 if (rlen != 0 && rfamily == family
3550 && rlen == addrlen)
3551 conv_lisp_to_sockaddr (rfamily, remote,
3552 datagram_address[s].sa, rlen);
3555 else
3556 memcpy (datagram_address[s].sa, sa, addrlen);
3558 #endif
3560 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3561 conv_sockaddr_to_lisp (sa, addrlen));
3562 #ifdef HAVE_GETSOCKNAME
3563 if (!p->is_server)
3565 struct sockaddr_storage sa1;
3566 socklen_t len1 = sizeof (sa1);
3567 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3568 if (getsockname (s, psa1, &len1) == 0)
3569 contact = Fplist_put (contact, QClocal,
3570 conv_sockaddr_to_lisp (psa1, len1));
3572 #endif
3575 if (s < 0)
3577 /* If non-blocking got this far - and failed - assume non-blocking is
3578 not supported after all. This is probably a wrong assumption, but
3579 the normal blocking calls to open-network-stream handles this error
3580 better. */
3581 if (p->is_non_blocking_client)
3582 return;
3584 report_file_errno ((p->is_server
3585 ? "make server process failed"
3586 : "make client process failed"),
3587 contact, xerrno);
3590 inch = s;
3591 outch = s;
3593 chan_process[inch] = proc;
3595 fcntl (inch, F_SETFL, O_NONBLOCK);
3597 p = XPROCESS (proc);
3598 p->open_fd[SUBPROCESS_STDIN] = inch;
3599 p->infd = inch;
3600 p->outfd = outch;
3602 /* Discard the unwind protect for closing S, if any. */
3603 specpdl_ptr = specpdl + count;
3605 if (p->is_server && p->socktype != SOCK_DGRAM)
3606 pset_status (p, Qlisten);
3608 /* Make the process marker point into the process buffer (if any). */
3609 if (BUFFERP (p->buffer))
3610 set_marker_both (p->mark, p->buffer,
3611 BUF_ZV (XBUFFER (p->buffer)),
3612 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3614 if (p->is_non_blocking_client)
3616 /* We may get here if connect did succeed immediately. However,
3617 in that case, we still need to signal this like a non-blocking
3618 connection. */
3619 if (! (connecting_status (p->status)
3620 && EQ (XCDR (p->status), addrinfos)))
3621 pset_status (p, Fcons (Qconnect, addrinfos));
3622 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3623 add_non_blocking_write_fd (inch);
3625 else
3626 /* A server may have a client filter setting of Qt, but it must
3627 still listen for incoming connects unless it is stopped. */
3628 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3629 || (EQ (p->status, Qlisten) && NILP (p->command)))
3630 add_process_read_fd (inch);
3632 if (inch > max_desc)
3633 max_desc = inch;
3635 /* Set up the masks based on the process filter. */
3636 set_process_filter_masks (p);
3638 setup_process_coding_systems (proc);
3640 #ifdef HAVE_GNUTLS
3641 /* Continue the asynchronous connection. */
3642 if (!NILP (p->gnutls_boot_parameters))
3644 Lisp_Object boot, params = p->gnutls_boot_parameters;
3646 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3647 p->gnutls_boot_parameters = Qnil;
3649 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3650 /* Run sentinels, etc. */
3651 finish_after_tls_connection (proc);
3652 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3654 deactivate_process (proc);
3655 if (NILP (boot))
3656 pset_status (p, list2 (Qfailed,
3657 build_string ("TLS negotiation failed")));
3658 else
3659 pset_status (p, list2 (Qfailed, boot));
3662 #endif
3666 /* Create a network stream/datagram client/server process. Treated
3667 exactly like a normal process when reading and writing. Primary
3668 differences are in status display and process deletion. A network
3669 connection has no PID; you cannot signal it. All you can do is
3670 stop/continue it and deactivate/close it via delete-process. */
3672 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3673 0, MANY, 0,
3674 doc: /* Create and return a network server or client process.
3676 In Emacs, network connections are represented by process objects, so
3677 input and output work as for subprocesses and `delete-process' closes
3678 a network connection. However, a network process has no process id,
3679 it cannot be signaled, and the status codes are different from normal
3680 processes.
3682 Arguments are specified as keyword/argument pairs. The following
3683 arguments are defined:
3685 :name NAME -- NAME is name for process. It is modified if necessary
3686 to make it unique.
3688 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3689 with the process. Process output goes at end of that buffer, unless
3690 you specify a filter function to handle the output. BUFFER may be
3691 also nil, meaning that this process is not associated with any buffer.
3693 :host HOST -- HOST is name of the host to connect to, or its IP
3694 address. The symbol `local' specifies the local host. If specified
3695 for a server process, it must be a valid name or address for the local
3696 host, and only clients connecting to that address will be accepted.
3698 :service SERVICE -- SERVICE is name of the service desired, or an
3699 integer specifying a port number to connect to. If SERVICE is t,
3700 a random port number is selected for the server. A port number can
3701 be specified as an integer string, e.g., "80", as well as an integer.
3703 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3704 stream type connection, `datagram' creates a datagram type connection,
3705 `seqpacket' creates a reliable datagram connection.
3707 :family FAMILY -- FAMILY is the address (and protocol) family for the
3708 service specified by HOST and SERVICE. The default (nil) is to use
3709 whatever address family (IPv4 or IPv6) that is defined for the host
3710 and port number specified by HOST and SERVICE. Other address families
3711 supported are:
3712 local -- for a local (i.e. UNIX) address specified by SERVICE.
3713 ipv4 -- use IPv4 address family only.
3714 ipv6 -- use IPv6 address family only.
3716 :local ADDRESS -- ADDRESS is the local address used for the connection.
3717 This parameter is ignored when opening a client process. When specified
3718 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3720 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3721 connection. This parameter is ignored when opening a stream server
3722 process. For a datagram server process, it specifies the initial
3723 setting of the remote datagram address. When specified for a client
3724 process, the FAMILY, HOST, and SERVICE args are ignored.
3726 The format of ADDRESS depends on the address family:
3727 - An IPv4 address is represented as a vector of integers [A B C D P]
3728 corresponding to numeric IP address A.B.C.D and port number P.
3729 - A local address is represented as a string with the address in the
3730 local address space.
3731 - An "unsupported family" address is represented by a cons (F . AV)
3732 where F is the family number and AV is a vector containing the socket
3733 address data with one element per address data byte. Do not rely on
3734 this format in portable code, as it may depend on implementation
3735 defined constants, data sizes, and data structure alignment.
3737 :coding CODING -- If CODING is a symbol, it specifies the coding
3738 system used for both reading and writing for this process. If CODING
3739 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3740 ENCODING is used for writing.
3742 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3743 process, return without waiting for the connection to complete;
3744 instead, the sentinel function will be called with second arg matching
3745 "open" (if successful) or "failed" when the connect completes.
3746 Default is to use a blocking connect (i.e. wait) for stream type
3747 connections.
3749 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3750 running when Emacs is exited.
3752 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3753 In the stopped state, a server process does not accept new
3754 connections, and a client process does not handle incoming traffic.
3755 The stopped state is cleared by `continue-process' and set by
3756 `stop-process'.
3758 :filter FILTER -- Install FILTER as the process filter.
3760 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3761 process filter are multibyte, otherwise they are unibyte.
3762 If this keyword is not specified, the strings are multibyte if
3763 the default value of `enable-multibyte-characters' is non-nil.
3765 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3767 :log LOG -- Install LOG as the server process log function. This
3768 function is called when the server accepts a network connection from a
3769 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3770 is the server process, CLIENT is the new process for the connection,
3771 and MESSAGE is a string.
3773 :plist PLIST -- Install PLIST as the new process's initial plist.
3775 :tls-parameters LIST -- is a list that should be supplied if you're
3776 opening a TLS connection. The first element is the TLS type (either
3777 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3778 be a keyword list accepted by gnutls-boot (as returned by
3779 `gnutls-boot-parameters').
3781 :server QLEN -- if QLEN is non-nil, create a server process for the
3782 specified FAMILY, SERVICE, and connection type (stream or datagram).
3783 If QLEN is an integer, it is used as the max. length of the server's
3784 pending connection queue (also known as the backlog); the default
3785 queue length is 5. Default is to create a client process.
3787 The following network options can be specified for this connection:
3789 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3790 :dontroute BOOL -- Only send to directly connected hosts.
3791 :keepalive BOOL -- Send keep-alive messages on network stream.
3792 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3793 :oobinline BOOL -- Place out-of-band data in receive data stream.
3794 :priority INT -- Set protocol defined priority for sent packets.
3795 :reuseaddr BOOL -- Allow reusing a recently used local address
3796 (this is allowed by default for a server process).
3797 :bindtodevice NAME -- bind to interface NAME. Using this may require
3798 special privileges on some systems.
3799 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3800 been passed to Emacs. If Emacs wasn't
3801 passed a socket, this option is silently
3802 ignored.
3805 Consult the relevant system programmer's manual pages for more
3806 information on using these options.
3809 A server process will listen for and accept connections from clients.
3810 When a client connection is accepted, a new network process is created
3811 for the connection with the following parameters:
3813 - The client's process name is constructed by concatenating the server
3814 process's NAME and a client identification string.
3815 - If the FILTER argument is non-nil, the client process will not get a
3816 separate process buffer; otherwise, the client's process buffer is a newly
3817 created buffer named after the server process's BUFFER name or process
3818 NAME concatenated with the client identification string.
3819 - The connection type and the process filter and sentinel parameters are
3820 inherited from the server process's TYPE, FILTER and SENTINEL.
3821 - The client process's contact info is set according to the client's
3822 addressing information (typically an IP address and a port number).
3823 - The client process's plist is initialized from the server's plist.
3825 Notice that the FILTER and SENTINEL args are never used directly by
3826 the server process. Also, the BUFFER argument is not used directly by
3827 the server process, but via the optional :log function, accepted (and
3828 failed) connections may be logged in the server process's buffer.
3830 The original argument list, modified with the actual connection
3831 information, is available via the `process-contact' function.
3833 usage: (make-network-process &rest ARGS) */)
3834 (ptrdiff_t nargs, Lisp_Object *args)
3836 Lisp_Object proc;
3837 Lisp_Object contact;
3838 struct Lisp_Process *p;
3839 const char *portstring UNINIT;
3840 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3841 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3842 #ifdef HAVE_LOCAL_SOCKETS
3843 struct sockaddr_un address_un;
3844 #endif
3845 EMACS_INT port = 0;
3846 Lisp_Object tem;
3847 Lisp_Object name, buffer, host, service, address;
3848 Lisp_Object filter, sentinel, use_external_socket_p;
3849 Lisp_Object addrinfos = Qnil;
3850 int socktype;
3851 int family = -1;
3852 enum { any_protocol = 0 };
3853 #ifdef HAVE_GETADDRINFO_A
3854 struct gaicb *dns_request = NULL;
3855 #endif
3856 ptrdiff_t count = SPECPDL_INDEX ();
3858 if (nargs == 0)
3859 return Qnil;
3861 /* Save arguments for process-contact and clone-process. */
3862 contact = Flist (nargs, args);
3864 #ifdef WINDOWSNT
3865 /* Ensure socket support is loaded if available. */
3866 init_winsock (TRUE);
3867 #endif
3869 /* :type TYPE (nil: stream, datagram */
3870 tem = Fplist_get (contact, QCtype);
3871 if (NILP (tem))
3872 socktype = SOCK_STREAM;
3873 #ifdef DATAGRAM_SOCKETS
3874 else if (EQ (tem, Qdatagram))
3875 socktype = SOCK_DGRAM;
3876 #endif
3877 #ifdef HAVE_SEQPACKET
3878 else if (EQ (tem, Qseqpacket))
3879 socktype = SOCK_SEQPACKET;
3880 #endif
3881 else
3882 error ("Unsupported connection type");
3884 name = Fplist_get (contact, QCname);
3885 buffer = Fplist_get (contact, QCbuffer);
3886 filter = Fplist_get (contact, QCfilter);
3887 sentinel = Fplist_get (contact, QCsentinel);
3888 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3890 CHECK_STRING (name);
3892 /* :local ADDRESS or :remote ADDRESS */
3893 tem = Fplist_get (contact, QCserver);
3894 if (NILP (tem))
3895 address = Fplist_get (contact, QCremote);
3896 else
3897 address = Fplist_get (contact, QClocal);
3898 if (!NILP (address))
3900 host = service = Qnil;
3902 if (!get_lisp_to_sockaddr_size (address, &family))
3903 error ("Malformed :address");
3905 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3906 goto open_socket;
3909 /* :family FAMILY -- nil (for Inet), local, or integer. */
3910 tem = Fplist_get (contact, QCfamily);
3911 if (NILP (tem))
3913 #ifdef AF_INET6
3914 family = AF_UNSPEC;
3915 #else
3916 family = AF_INET;
3917 #endif
3919 #ifdef HAVE_LOCAL_SOCKETS
3920 else if (EQ (tem, Qlocal))
3921 family = AF_LOCAL;
3922 #endif
3923 #ifdef AF_INET6
3924 else if (EQ (tem, Qipv6))
3925 family = AF_INET6;
3926 #endif
3927 else if (EQ (tem, Qipv4))
3928 family = AF_INET;
3929 else if (TYPE_RANGED_INTEGERP (int, tem))
3930 family = XINT (tem);
3931 else
3932 error ("Unknown address family");
3934 /* :service SERVICE -- string, integer (port number), or t (random port). */
3935 service = Fplist_get (contact, QCservice);
3937 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3938 host = Fplist_get (contact, QChost);
3939 if (NILP (host))
3941 /* The "connection" function gets it bind info from the address we're
3942 given, so use this dummy address if nothing is specified. */
3943 #ifdef HAVE_LOCAL_SOCKETS
3944 if (family != AF_LOCAL)
3945 #endif
3946 host = build_string ("127.0.0.1");
3948 else
3950 if (EQ (host, Qlocal))
3951 /* Depending on setup, "localhost" may map to different IPv4 and/or
3952 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3953 host = build_string ("127.0.0.1");
3954 CHECK_STRING (host);
3957 #ifdef HAVE_LOCAL_SOCKETS
3958 if (family == AF_LOCAL)
3960 if (!NILP (host))
3962 message (":family local ignores the :host property");
3963 contact = Fplist_put (contact, QChost, Qnil);
3964 host = Qnil;
3966 CHECK_STRING (service);
3967 if (sizeof address_un.sun_path <= SBYTES (service))
3968 error ("Service name too long");
3969 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3970 goto open_socket;
3972 #endif
3974 /* Slow down polling to every ten seconds.
3975 Some kernels have a bug which causes retrying connect to fail
3976 after a connect. Polling can interfere with gethostbyname too. */
3977 #ifdef POLL_FOR_INPUT
3978 if (socktype != SOCK_DGRAM)
3980 record_unwind_protect_void (run_all_atimers);
3981 bind_polling_period (10);
3983 #endif
3985 if (!NILP (host))
3987 /* SERVICE can either be a string or int.
3988 Convert to a C string for later use by getaddrinfo. */
3989 if (EQ (service, Qt))
3991 portstring = "0";
3992 portstringlen = 1;
3994 else if (INTEGERP (service))
3996 portstring = portbuf;
3997 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3999 else
4001 CHECK_STRING (service);
4002 portstring = SSDATA (service);
4003 portstringlen = SBYTES (service);
4007 #ifdef HAVE_GETADDRINFO_A
4008 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
4010 ptrdiff_t hostlen = SBYTES (host);
4011 struct req
4013 struct gaicb gaicb;
4014 struct addrinfo hints;
4015 char str[FLEXIBLE_ARRAY_MEMBER];
4016 } *req = xmalloc (FLEXSIZEOF (struct req, str,
4017 hostlen + 1 + portstringlen + 1));
4018 dns_request = &req->gaicb;
4019 dns_request->ar_name = req->str;
4020 dns_request->ar_service = req->str + hostlen + 1;
4021 dns_request->ar_request = &req->hints;
4022 dns_request->ar_result = NULL;
4023 memset (&req->hints, 0, sizeof req->hints);
4024 req->hints.ai_family = family;
4025 req->hints.ai_socktype = socktype;
4026 strcpy (req->str, SSDATA (host));
4027 strcpy (req->str + hostlen + 1, portstring);
4029 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4030 if (ret)
4031 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
4033 goto open_socket;
4035 #endif /* HAVE_GETADDRINFO_A */
4037 /* If we have a host, use getaddrinfo to resolve both host and service.
4038 Otherwise, use getservbyname to lookup the service. */
4040 if (!NILP (host))
4042 struct addrinfo *res, *lres;
4043 int ret;
4045 maybe_quit ();
4047 struct addrinfo hints;
4048 memset (&hints, 0, sizeof hints);
4049 hints.ai_family = family;
4050 hints.ai_socktype = socktype;
4052 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4053 if (ret)
4054 #ifdef HAVE_GAI_STRERROR
4056 synchronize_system_messages_locale ();
4057 char const *str = gai_strerror (ret);
4058 if (! NILP (Vlocale_coding_system))
4059 str = SSDATA (code_convert_string_norecord
4060 (build_string (str), Vlocale_coding_system, 0));
4061 error ("%s/%s %s", SSDATA (host), portstring, str);
4063 #else
4064 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4065 #endif
4067 for (lres = res; lres; lres = lres->ai_next)
4068 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4070 addrinfos = Fnreverse (addrinfos);
4072 freeaddrinfo (res);
4074 goto open_socket;
4077 /* No hostname has been specified (e.g., a local server process). */
4079 if (EQ (service, Qt))
4080 port = 0;
4081 else if (INTEGERP (service))
4082 port = XINT (service);
4083 else
4085 CHECK_STRING (service);
4087 port = -1;
4088 if (SBYTES (service) != 0)
4090 /* Allow the service to be a string containing the port number,
4091 because that's allowed if you have getaddrbyname. */
4092 char *service_end;
4093 long int lport = strtol (SSDATA (service), &service_end, 10);
4094 if (service_end == SSDATA (service) + SBYTES (service))
4095 port = lport;
4096 else
4098 struct servent *svc_info
4099 = getservbyname (SSDATA (service),
4100 socktype == SOCK_DGRAM ? "udp" : "tcp");
4101 if (svc_info)
4102 port = ntohs (svc_info->s_port);
4107 if (! (0 <= port && port < 1 << 16))
4109 AUTO_STRING (unknown_service, "Unknown service: %s");
4110 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4113 open_socket:
4115 if (!NILP (buffer))
4116 buffer = Fget_buffer_create (buffer);
4118 /* Unwind bind_polling_period. */
4119 unbind_to (count, Qnil);
4121 proc = make_process (name);
4122 record_unwind_protect (remove_process, proc);
4123 p = XPROCESS (proc);
4124 pset_childp (p, contact);
4125 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4126 pset_type (p, Qnetwork);
4128 pset_buffer (p, buffer);
4129 pset_sentinel (p, sentinel);
4130 pset_filter (p, filter);
4131 pset_log (p, Fplist_get (contact, QClog));
4132 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4133 p->kill_without_query = 1;
4134 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4135 pset_command (p, Qt);
4136 eassert (p->pid == 0);
4137 p->backlog = 5;
4138 eassert (! p->is_non_blocking_client);
4139 eassert (! p->is_server);
4140 p->port = port;
4141 p->socktype = socktype;
4142 #ifdef HAVE_GETADDRINFO_A
4143 eassert (! p->dns_request);
4144 #endif
4145 #ifdef HAVE_GNUTLS
4146 tem = Fplist_get (contact, QCtls_parameters);
4147 CHECK_LIST (tem);
4148 p->gnutls_boot_parameters = tem;
4149 #endif
4151 set_network_socket_coding_system (proc, host, service, name);
4153 /* :server BOOL */
4154 tem = Fplist_get (contact, QCserver);
4155 if (!NILP (tem))
4157 /* Don't support network sockets when non-blocking mode is
4158 not available, since a blocked Emacs is not useful. */
4159 p->is_server = true;
4160 if (TYPE_RANGED_INTEGERP (int, tem))
4161 p->backlog = XINT (tem);
4164 /* :nowait BOOL */
4165 if (!p->is_server && socktype != SOCK_DGRAM
4166 && !NILP (Fplist_get (contact, QCnowait)))
4167 p->is_non_blocking_client = true;
4169 bool postpone_connection = false;
4170 #ifdef HAVE_GETADDRINFO_A
4171 /* With async address resolution, the list of addresses is empty, so
4172 postpone connecting to the server. */
4173 if (!p->is_server && NILP (addrinfos))
4175 p->dns_request = dns_request;
4176 p->status = list1 (Qconnect);
4177 postpone_connection = true;
4179 #endif
4180 if (! postpone_connection)
4181 connect_network_socket (proc, addrinfos, use_external_socket_p);
4183 specpdl_ptr = specpdl + count;
4184 return proc;
4188 #ifdef HAVE_NET_IF_H
4190 #ifdef SIOCGIFCONF
4191 static Lisp_Object
4192 network_interface_list (void)
4194 struct ifconf ifconf;
4195 struct ifreq *ifreq;
4196 void *buf = NULL;
4197 ptrdiff_t buf_size = 512;
4198 int s;
4199 Lisp_Object res;
4200 ptrdiff_t count;
4202 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4203 if (s < 0)
4204 return Qnil;
4205 count = SPECPDL_INDEX ();
4206 record_unwind_protect_int (close_file_unwind, s);
4210 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4211 ifconf.ifc_buf = buf;
4212 ifconf.ifc_len = buf_size;
4213 if (ioctl (s, SIOCGIFCONF, &ifconf))
4215 emacs_close (s);
4216 xfree (buf);
4217 return Qnil;
4220 while (ifconf.ifc_len == buf_size);
4222 res = unbind_to (count, Qnil);
4223 ifreq = ifconf.ifc_req;
4224 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4226 struct ifreq *ifq = ifreq;
4227 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4228 #define SIZEOF_IFREQ(sif) \
4229 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4230 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4232 int len = SIZEOF_IFREQ (ifq);
4233 #else
4234 int len = sizeof (*ifreq);
4235 #endif
4236 char namebuf[sizeof (ifq->ifr_name) + 1];
4237 ifreq = (struct ifreq *) ((char *) ifreq + len);
4239 if (ifq->ifr_addr.sa_family != AF_INET)
4240 continue;
4242 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4243 namebuf[sizeof (ifq->ifr_name)] = 0;
4244 res = Fcons (Fcons (build_string (namebuf),
4245 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4246 sizeof (struct sockaddr))),
4247 res);
4250 xfree (buf);
4251 return res;
4253 #endif /* SIOCGIFCONF */
4255 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4257 struct ifflag_def {
4258 int flag_bit;
4259 const char *flag_sym;
4262 static const struct ifflag_def ifflag_table[] = {
4263 #ifdef IFF_UP
4264 { IFF_UP, "up" },
4265 #endif
4266 #ifdef IFF_BROADCAST
4267 { IFF_BROADCAST, "broadcast" },
4268 #endif
4269 #ifdef IFF_DEBUG
4270 { IFF_DEBUG, "debug" },
4271 #endif
4272 #ifdef IFF_LOOPBACK
4273 { IFF_LOOPBACK, "loopback" },
4274 #endif
4275 #ifdef IFF_POINTOPOINT
4276 { IFF_POINTOPOINT, "pointopoint" },
4277 #endif
4278 #ifdef IFF_RUNNING
4279 { IFF_RUNNING, "running" },
4280 #endif
4281 #ifdef IFF_NOARP
4282 { IFF_NOARP, "noarp" },
4283 #endif
4284 #ifdef IFF_PROMISC
4285 { IFF_PROMISC, "promisc" },
4286 #endif
4287 #ifdef IFF_NOTRAILERS
4288 #ifdef NS_IMPL_COCOA
4289 /* Really means smart, notrailers is obsolete. */
4290 { IFF_NOTRAILERS, "smart" },
4291 #else
4292 { IFF_NOTRAILERS, "notrailers" },
4293 #endif
4294 #endif
4295 #ifdef IFF_ALLMULTI
4296 { IFF_ALLMULTI, "allmulti" },
4297 #endif
4298 #ifdef IFF_MASTER
4299 { IFF_MASTER, "master" },
4300 #endif
4301 #ifdef IFF_SLAVE
4302 { IFF_SLAVE, "slave" },
4303 #endif
4304 #ifdef IFF_MULTICAST
4305 { IFF_MULTICAST, "multicast" },
4306 #endif
4307 #ifdef IFF_PORTSEL
4308 { IFF_PORTSEL, "portsel" },
4309 #endif
4310 #ifdef IFF_AUTOMEDIA
4311 { IFF_AUTOMEDIA, "automedia" },
4312 #endif
4313 #ifdef IFF_DYNAMIC
4314 { IFF_DYNAMIC, "dynamic" },
4315 #endif
4316 #ifdef IFF_OACTIVE
4317 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4318 #endif
4319 #ifdef IFF_SIMPLEX
4320 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4321 #endif
4322 #ifdef IFF_LINK0
4323 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4324 #endif
4325 #ifdef IFF_LINK1
4326 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4327 #endif
4328 #ifdef IFF_LINK2
4329 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4330 #endif
4331 { 0, 0 }
4334 static Lisp_Object
4335 network_interface_info (Lisp_Object ifname)
4337 struct ifreq rq;
4338 Lisp_Object res = Qnil;
4339 Lisp_Object elt;
4340 int s;
4341 bool any = 0;
4342 ptrdiff_t count;
4343 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4344 && defined HAVE_GETIFADDRS && defined LLADDR)
4345 struct ifaddrs *ifap;
4346 #endif
4348 CHECK_STRING (ifname);
4350 if (sizeof rq.ifr_name <= SBYTES (ifname))
4351 error ("interface name too long");
4352 lispstpcpy (rq.ifr_name, ifname);
4354 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4355 if (s < 0)
4356 return Qnil;
4357 count = SPECPDL_INDEX ();
4358 record_unwind_protect_int (close_file_unwind, s);
4360 elt = Qnil;
4361 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4362 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4364 int flags = rq.ifr_flags;
4365 const struct ifflag_def *fp;
4366 int fnum;
4368 /* If flags is smaller than int (i.e. short) it may have the high bit set
4369 due to IFF_MULTICAST. In that case, sign extending it into
4370 an int is wrong. */
4371 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4372 flags = (unsigned short) rq.ifr_flags;
4374 any = 1;
4375 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4377 if (flags & fp->flag_bit)
4379 elt = Fcons (intern (fp->flag_sym), elt);
4380 flags -= fp->flag_bit;
4383 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4385 if (flags & 1)
4387 elt = Fcons (make_number (fnum), elt);
4391 #endif
4392 res = Fcons (elt, res);
4394 elt = Qnil;
4395 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4396 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4398 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4399 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4400 int n;
4402 any = 1;
4403 for (n = 0; n < 6; n++)
4404 p->contents[n] = make_number (((unsigned char *)
4405 &rq.ifr_hwaddr.sa_data[0])
4406 [n]);
4407 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4409 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4410 if (getifaddrs (&ifap) != -1)
4412 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4413 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4414 struct ifaddrs *it;
4416 for (it = ifap; it != NULL; it = it->ifa_next)
4418 DECLARE_POINTER_ALIAS (sdl, struct sockaddr_dl, it->ifa_addr);
4419 unsigned char linkaddr[6];
4420 int n;
4422 if (it->ifa_addr->sa_family != AF_LINK
4423 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4424 || sdl->sdl_alen != 6)
4425 continue;
4427 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4428 for (n = 0; n < 6; n++)
4429 p->contents[n] = make_number (linkaddr[n]);
4431 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4432 break;
4435 #ifdef HAVE_FREEIFADDRS
4436 freeifaddrs (ifap);
4437 #endif
4439 #endif /* HAVE_GETIFADDRS && LLADDR */
4441 res = Fcons (elt, res);
4443 elt = Qnil;
4444 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4445 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4447 any = 1;
4448 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4449 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4450 #else
4451 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4452 #endif
4454 #endif
4455 res = Fcons (elt, res);
4457 elt = Qnil;
4458 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4459 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4461 any = 1;
4462 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4464 #endif
4465 res = Fcons (elt, res);
4467 elt = Qnil;
4468 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4469 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4471 any = 1;
4472 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4474 #endif
4475 res = Fcons (elt, res);
4477 return unbind_to (count, any ? res : Qnil);
4479 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4480 #endif /* defined (HAVE_NET_IF_H) */
4482 DEFUN ("network-interface-list", Fnetwork_interface_list,
4483 Snetwork_interface_list, 0, 0, 0,
4484 doc: /* Return an alist of all network interfaces and their network address.
4485 Each element is a cons, the car of which is a string containing the
4486 interface name, and the cdr is the network address in internal
4487 format; see the description of ADDRESS in `make-network-process'.
4489 If the information is not available, return nil. */)
4490 (void)
4492 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4493 return network_interface_list ();
4494 #else
4495 return Qnil;
4496 #endif
4499 DEFUN ("network-interface-info", Fnetwork_interface_info,
4500 Snetwork_interface_info, 1, 1, 0,
4501 doc: /* Return information about network interface named IFNAME.
4502 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4503 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4504 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4505 FLAGS is the current flags of the interface.
4507 Data that is unavailable is returned as nil. */)
4508 (Lisp_Object ifname)
4510 #if ((defined HAVE_NET_IF_H \
4511 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4512 || defined SIOCGIFFLAGS)) \
4513 || defined WINDOWSNT)
4514 return network_interface_info (ifname);
4515 #else
4516 return Qnil;
4517 #endif
4520 /* Turn off input and output for process PROC. */
4522 static void
4523 deactivate_process (Lisp_Object proc)
4525 int inchannel;
4526 struct Lisp_Process *p = XPROCESS (proc);
4527 int i;
4529 #ifdef HAVE_GNUTLS
4530 /* Delete GnuTLS structures in PROC, if any. */
4531 emacs_gnutls_deinit (proc);
4532 #endif /* HAVE_GNUTLS */
4534 if (p->read_output_delay > 0)
4536 if (--process_output_delay_count < 0)
4537 process_output_delay_count = 0;
4538 p->read_output_delay = 0;
4539 p->read_output_skip = 0;
4542 /* Beware SIGCHLD hereabouts. */
4544 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4545 close_process_fd (&p->open_fd[i]);
4547 inchannel = p->infd;
4548 if (inchannel >= 0)
4550 p->infd = -1;
4551 p->outfd = -1;
4552 #ifdef DATAGRAM_SOCKETS
4553 if (DATAGRAM_CHAN_P (inchannel))
4555 xfree (datagram_address[inchannel].sa);
4556 datagram_address[inchannel].sa = 0;
4557 datagram_address[inchannel].len = 0;
4559 #endif
4560 chan_process[inchannel] = Qnil;
4561 delete_read_fd (inchannel);
4562 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4563 delete_write_fd (inchannel);
4564 if (inchannel == max_desc)
4565 recompute_max_desc ();
4570 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4571 0, 4, 0,
4572 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4573 It is given to their filter functions.
4574 Optional argument PROCESS means do not return until output has been
4575 received from PROCESS.
4577 Optional second argument SECONDS and third argument MILLISEC
4578 specify a timeout; return after that much time even if there is
4579 no subprocess output. If SECONDS is a floating point number,
4580 it specifies a fractional number of seconds to wait.
4581 The MILLISEC argument is obsolete and should be avoided.
4583 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4584 from PROCESS only, suspending reading output from other processes.
4585 If JUST-THIS-ONE is an integer, don't run any timers either.
4586 Return non-nil if we received any output from PROCESS (or, if PROCESS
4587 is nil, from any process) before the timeout expired. */)
4588 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4589 Lisp_Object just_this_one)
4591 intmax_t secs;
4592 int nsecs;
4594 if (! NILP (process))
4596 CHECK_PROCESS (process);
4597 struct Lisp_Process *proc = XPROCESS (process);
4599 /* Can't wait for a process that is dedicated to a different
4600 thread. */
4601 if (!EQ (proc->thread, Qnil) && !EQ (proc->thread, Fcurrent_thread ()))
4603 Lisp_Object proc_thread_name = XTHREAD (proc->thread)->name;
4605 if (STRINGP (proc_thread_name))
4606 error ("Attempt to accept output from process %s locked to thread %s",
4607 SDATA (proc->name), SDATA (proc_thread_name));
4608 else
4609 error ("Attempt to accept output from process %s locked to thread %p",
4610 SDATA (proc->name), XTHREAD (proc->thread));
4613 else
4614 just_this_one = Qnil;
4616 if (!NILP (millisec))
4617 { /* Obsolete calling convention using integers rather than floats. */
4618 CHECK_NUMBER (millisec);
4619 if (NILP (seconds))
4620 seconds = make_float (XINT (millisec) / 1000.0);
4621 else
4623 CHECK_NUMBER (seconds);
4624 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4628 secs = 0;
4629 nsecs = -1;
4631 if (!NILP (seconds))
4633 if (INTEGERP (seconds))
4635 if (XINT (seconds) > 0)
4637 secs = XINT (seconds);
4638 nsecs = 0;
4641 else if (FLOATP (seconds))
4643 if (XFLOAT_DATA (seconds) > 0)
4645 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4646 secs = min (t.tv_sec, WAIT_READING_MAX);
4647 nsecs = t.tv_nsec;
4650 else
4651 wrong_type_argument (Qnumberp, seconds);
4653 else if (! NILP (process))
4654 nsecs = 0;
4656 return
4657 ((wait_reading_process_output (secs, nsecs, 0, 0,
4658 Qnil,
4659 !NILP (process) ? XPROCESS (process) : NULL,
4660 (NILP (just_this_one) ? 0
4661 : !INTEGERP (just_this_one) ? 1 : -1))
4662 <= 0)
4663 ? Qnil : Qt);
4666 /* Accept a connection for server process SERVER on CHANNEL. */
4668 static EMACS_INT connect_counter = 0;
4670 static void
4671 server_accept_connection (Lisp_Object server, int channel)
4673 Lisp_Object buffer;
4674 Lisp_Object contact, host, service;
4675 struct Lisp_Process *ps = XPROCESS (server);
4676 struct Lisp_Process *p;
4677 int s;
4678 union u_sockaddr {
4679 struct sockaddr sa;
4680 struct sockaddr_in in;
4681 #ifdef AF_INET6
4682 struct sockaddr_in6 in6;
4683 #endif
4684 #ifdef HAVE_LOCAL_SOCKETS
4685 struct sockaddr_un un;
4686 #endif
4687 } saddr;
4688 socklen_t len = sizeof saddr;
4689 ptrdiff_t count;
4691 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4693 if (s < 0)
4695 int code = errno;
4696 if (!would_block (code) && !NILP (ps->log))
4697 call3 (ps->log, server, Qnil,
4698 concat3 (build_string ("accept failed with code"),
4699 Fnumber_to_string (make_number (code)),
4700 build_string ("\n")));
4701 return;
4704 count = SPECPDL_INDEX ();
4705 record_unwind_protect_int (close_file_unwind, s);
4707 connect_counter++;
4709 /* Setup a new process to handle the connection. */
4711 /* Generate a unique identification of the caller, and build contact
4712 information for this process. */
4713 host = Qt;
4714 service = Qnil;
4715 Lisp_Object args[11];
4716 int nargs = 0;
4717 AUTO_STRING (procname_format_in, "%s <%d.%d.%d.%d:%d>");
4718 AUTO_STRING (procname_format_in6, "%s <[%x:%x:%x:%x:%x:%x:%x:%x]:%d>");
4719 AUTO_STRING (procname_format_default, "%s <%d>");
4720 switch (saddr.sa.sa_family)
4722 case AF_INET:
4724 args[nargs++] = procname_format_in;
4725 nargs++;
4726 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4727 service = make_number (ntohs (saddr.in.sin_port));
4728 for (int i = 0; i < 4; i++)
4729 args[nargs++] = make_number (ip[i]);
4730 args[nargs++] = service;
4732 break;
4734 #ifdef AF_INET6
4735 case AF_INET6:
4737 args[nargs++] = procname_format_in6;
4738 nargs++;
4739 DECLARE_POINTER_ALIAS (ip6, uint16_t, &saddr.in6.sin6_addr);
4740 service = make_number (ntohs (saddr.in.sin_port));
4741 for (int i = 0; i < 8; i++)
4742 args[nargs++] = make_number (ip6[i]);
4743 args[nargs++] = service;
4745 break;
4746 #endif
4748 default:
4749 args[nargs++] = procname_format_default;
4750 nargs++;
4751 args[nargs++] = make_number (connect_counter);
4752 break;
4755 /* Create a new buffer name for this process if it doesn't have a
4756 filter. The new buffer name is based on the buffer name or
4757 process name of the server process concatenated with the caller
4758 identification. */
4760 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4761 || EQ (ps->filter, Qt)))
4762 buffer = Qnil;
4763 else
4765 buffer = ps->buffer;
4766 if (!NILP (buffer))
4767 buffer = Fbuffer_name (buffer);
4768 else
4769 buffer = ps->name;
4770 if (!NILP (buffer))
4772 args[1] = buffer;
4773 buffer = Fget_buffer_create (Fformat (nargs, args));
4777 /* Generate a unique name for the new server process. Combine the
4778 server process name with the caller identification. */
4780 args[1] = ps->name;
4781 Lisp_Object name = Fformat (nargs, args);
4782 Lisp_Object proc = make_process (name);
4784 chan_process[s] = proc;
4786 fcntl (s, F_SETFL, O_NONBLOCK);
4788 p = XPROCESS (proc);
4790 /* Build new contact information for this setup. */
4791 contact = Fcopy_sequence (ps->childp);
4792 contact = Fplist_put (contact, QCserver, Qnil);
4793 contact = Fplist_put (contact, QChost, host);
4794 if (!NILP (service))
4795 contact = Fplist_put (contact, QCservice, service);
4796 contact = Fplist_put (contact, QCremote,
4797 conv_sockaddr_to_lisp (&saddr.sa, len));
4798 #ifdef HAVE_GETSOCKNAME
4799 len = sizeof saddr;
4800 if (getsockname (s, &saddr.sa, &len) == 0)
4801 contact = Fplist_put (contact, QClocal,
4802 conv_sockaddr_to_lisp (&saddr.sa, len));
4803 #endif
4805 pset_childp (p, contact);
4806 pset_plist (p, Fcopy_sequence (ps->plist));
4807 pset_type (p, Qnetwork);
4809 pset_buffer (p, buffer);
4810 pset_sentinel (p, ps->sentinel);
4811 pset_filter (p, ps->filter);
4812 eassert (NILP (p->command));
4813 eassert (p->pid == 0);
4815 /* Discard the unwind protect for closing S. */
4816 specpdl_ptr = specpdl + count;
4818 p->open_fd[SUBPROCESS_STDIN] = s;
4819 p->infd = s;
4820 p->outfd = s;
4821 pset_status (p, Qrun);
4823 /* Client processes for accepted connections are not stopped initially. */
4824 if (!EQ (p->filter, Qt))
4825 add_process_read_fd (s);
4826 if (s > max_desc)
4827 max_desc = s;
4829 /* Setup coding system for new process based on server process.
4830 This seems to be the proper thing to do, as the coding system
4831 of the new process should reflect the settings at the time the
4832 server socket was opened; not the current settings. */
4834 pset_decode_coding_system (p, ps->decode_coding_system);
4835 pset_encode_coding_system (p, ps->encode_coding_system);
4836 setup_process_coding_systems (proc);
4838 pset_decoding_buf (p, empty_unibyte_string);
4839 eassert (p->decoding_carryover == 0);
4840 pset_encoding_buf (p, empty_unibyte_string);
4842 p->inherit_coding_system_flag
4843 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4845 AUTO_STRING (dash, "-");
4846 AUTO_STRING (nl, "\n");
4847 Lisp_Object host_string = STRINGP (host) ? host : dash;
4849 if (!NILP (ps->log))
4851 AUTO_STRING (accept_from, "accept from ");
4852 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4855 AUTO_STRING (open_from, "open from ");
4856 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4859 #ifdef HAVE_GETADDRINFO_A
4860 static Lisp_Object
4861 check_for_dns (Lisp_Object proc)
4863 struct Lisp_Process *p = XPROCESS (proc);
4864 Lisp_Object addrinfos = Qnil;
4866 /* Sanity check. */
4867 if (! p->dns_request)
4868 return Qnil;
4870 int ret = gai_error (p->dns_request);
4871 if (ret == EAI_INPROGRESS)
4872 return Qt;
4874 /* We got a response. */
4875 if (ret == 0)
4877 struct addrinfo *res;
4879 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4880 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4882 addrinfos = Fnreverse (addrinfos);
4884 /* The DNS lookup failed. */
4885 else if (connecting_status (p->status))
4887 deactivate_process (proc);
4888 pset_status (p, (list2
4889 (Qfailed,
4890 concat3 (build_string ("Name lookup of "),
4891 build_string (p->dns_request->ar_name),
4892 build_string (" failed")))));
4895 free_dns_request (proc);
4897 /* This process should not already be connected (or killed). */
4898 if (! connecting_status (p->status))
4899 return Qnil;
4901 return addrinfos;
4904 #endif /* HAVE_GETADDRINFO_A */
4906 static void
4907 wait_for_socket_fds (Lisp_Object process, char const *name)
4909 while (XPROCESS (process)->infd < 0
4910 && connecting_status (XPROCESS (process)->status))
4912 add_to_log ("Waiting for socket from %s...", build_string (name));
4913 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4917 static void
4918 wait_while_connecting (Lisp_Object process)
4920 while (connecting_status (XPROCESS (process)->status))
4922 add_to_log ("Waiting for connection...");
4923 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4927 static void
4928 wait_for_tls_negotiation (Lisp_Object process)
4930 #ifdef HAVE_GNUTLS
4931 while (XPROCESS (process)->gnutls_p
4932 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4934 add_to_log ("Waiting for TLS...");
4935 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4937 #endif
4940 static void
4941 wait_reading_process_output_unwind (int data)
4943 clear_waiting_thread_info ();
4944 waiting_for_user_input_p = data;
4947 /* This is here so breakpoints can be put on it. */
4948 static void
4949 wait_reading_process_output_1 (void)
4953 /* Read and dispose of subprocess output while waiting for timeout to
4954 elapse and/or keyboard input to be available.
4956 TIME_LIMIT is:
4957 timeout in seconds
4958 If negative, gobble data immediately available but don't wait for any.
4960 NSECS is:
4961 an additional duration to wait, measured in nanoseconds
4962 If TIME_LIMIT is zero, then:
4963 If NSECS == 0, there is no limit.
4964 If NSECS > 0, the timeout consists of NSECS only.
4965 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4967 READ_KBD is:
4968 0 to ignore keyboard input, or
4969 1 to return when input is available, or
4970 -1 meaning caller will actually read the input, so don't throw to
4971 the quit handler
4973 DO_DISPLAY means redisplay should be done to show subprocess
4974 output that arrives.
4976 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4977 (and gobble terminal input into the buffer if any arrives).
4979 If WAIT_PROC is specified, wait until something arrives from that
4980 process.
4982 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4983 (suspending output from other processes). A negative value
4984 means don't run any timers either.
4986 Return positive if we received input from WAIT_PROC (or from any
4987 process if WAIT_PROC is null), zero if we attempted to receive
4988 input but got none, and negative if we didn't even try. */
4991 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4992 bool do_display,
4993 Lisp_Object wait_for_cell,
4994 struct Lisp_Process *wait_proc, int just_wait_proc)
4996 int channel, nfds;
4997 fd_set Available;
4998 fd_set Writeok;
4999 bool check_write;
5000 int check_delay;
5001 bool no_avail;
5002 int xerrno;
5003 Lisp_Object proc;
5004 struct timespec timeout, end_time, timer_delay;
5005 struct timespec got_output_end_time = invalid_timespec ();
5006 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
5007 int got_some_output = -1;
5008 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5009 bool retry_for_async;
5010 #endif
5011 ptrdiff_t count = SPECPDL_INDEX ();
5013 /* Close to the current time if known, an invalid timespec otherwise. */
5014 struct timespec now = invalid_timespec ();
5016 eassert (wait_proc == NULL
5017 || EQ (wait_proc->thread, Qnil)
5018 || XTHREAD (wait_proc->thread) == current_thread);
5020 FD_ZERO (&Available);
5021 FD_ZERO (&Writeok);
5023 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
5024 && !(CONSP (wait_proc->status)
5025 && EQ (XCAR (wait_proc->status), Qexit)))
5026 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5028 record_unwind_protect_int (wait_reading_process_output_unwind,
5029 waiting_for_user_input_p);
5030 waiting_for_user_input_p = read_kbd;
5032 if (TYPE_MAXIMUM (time_t) < time_limit)
5033 time_limit = TYPE_MAXIMUM (time_t);
5035 if (time_limit < 0 || nsecs < 0)
5036 wait = MINIMUM;
5037 else if (time_limit > 0 || nsecs > 0)
5039 wait = TIMEOUT;
5040 now = current_timespec ();
5041 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5043 else
5044 wait = INFINITY;
5046 while (1)
5048 bool process_skipped = false;
5050 /* If calling from keyboard input, do not quit
5051 since we want to return C-g as an input character.
5052 Otherwise, do pending quit if requested. */
5053 if (read_kbd >= 0)
5054 maybe_quit ();
5055 else if (pending_signals)
5056 process_pending_signals ();
5058 /* Exit now if the cell we're waiting for became non-nil. */
5059 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5060 break;
5062 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5064 Lisp_Object process_list_head, aproc;
5065 struct Lisp_Process *p;
5067 retry_for_async = false;
5068 FOR_EACH_PROCESS(process_list_head, aproc)
5070 p = XPROCESS (aproc);
5072 if (! wait_proc || p == wait_proc)
5074 #ifdef HAVE_GETADDRINFO_A
5075 /* Check for pending DNS requests. */
5076 if (p->dns_request)
5078 Lisp_Object addrinfos = check_for_dns (aproc);
5079 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5080 connect_network_socket (aproc, addrinfos, Qnil);
5081 else
5082 retry_for_async = true;
5084 #endif
5085 #ifdef HAVE_GNUTLS
5086 /* Continue TLS negotiation. */
5087 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5088 && p->is_non_blocking_client)
5090 gnutls_try_handshake (p);
5091 p->gnutls_handshakes_tried++;
5093 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5095 gnutls_verify_boot (aproc, Qnil);
5096 finish_after_tls_connection (aproc);
5098 else
5100 retry_for_async = true;
5101 if (p->gnutls_handshakes_tried
5102 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5104 deactivate_process (aproc);
5105 pset_status (p, list2 (Qfailed,
5106 build_string ("TLS negotiation failed")));
5110 #endif
5114 #endif /* GETADDRINFO_A or GNUTLS */
5116 /* Compute time from now till when time limit is up. */
5117 /* Exit if already run out. */
5118 if (wait == TIMEOUT)
5120 if (!timespec_valid_p (now))
5121 now = current_timespec ();
5122 if (timespec_cmp (end_time, now) <= 0)
5123 break;
5124 timeout = timespec_sub (end_time, now);
5126 else
5127 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5129 /* Normally we run timers here.
5130 But not if wait_for_cell; in those cases,
5131 the wait is supposed to be short,
5132 and those callers cannot handle running arbitrary Lisp code here. */
5133 if (NILP (wait_for_cell)
5134 && just_wait_proc >= 0)
5138 unsigned old_timers_run = timers_run;
5139 struct buffer *old_buffer = current_buffer;
5140 Lisp_Object old_window = selected_window;
5142 timer_delay = timer_check ();
5144 /* If a timer has run, this might have changed buffers
5145 an alike. Make read_key_sequence aware of that. */
5146 if (timers_run != old_timers_run
5147 && (old_buffer != current_buffer
5148 || !EQ (old_window, selected_window))
5149 && waiting_for_user_input_p == -1)
5150 record_asynch_buffer_change ();
5152 if (timers_run != old_timers_run && do_display)
5153 /* We must retry, since a timer may have requeued itself
5154 and that could alter the time_delay. */
5155 redisplay_preserve_echo_area (9);
5156 else
5157 break;
5159 while (!detect_input_pending ());
5161 /* If there is unread keyboard input, also return. */
5162 if (read_kbd != 0
5163 && requeued_events_pending_p ())
5164 break;
5166 /* This is so a breakpoint can be put here. */
5167 if (!timespec_valid_p (timer_delay))
5168 wait_reading_process_output_1 ();
5171 /* Cause C-g and alarm signals to take immediate action,
5172 and cause input available signals to zero out timeout.
5174 It is important that we do this before checking for process
5175 activity. If we get a SIGCHLD after the explicit checks for
5176 process activity, timeout is the only way we will know. */
5177 if (read_kbd < 0)
5178 set_waiting_for_input (&timeout);
5180 /* If status of something has changed, and no input is
5181 available, notify the user of the change right away. After
5182 this explicit check, we'll let the SIGCHLD handler zap
5183 timeout to get our attention. */
5184 if (update_tick != process_tick)
5186 fd_set Atemp;
5187 fd_set Ctemp;
5189 if (kbd_on_hold_p ())
5190 FD_ZERO (&Atemp);
5191 else
5192 compute_input_wait_mask (&Atemp);
5193 compute_write_mask (&Ctemp);
5195 timeout = make_timespec (0, 0);
5196 if ((thread_select (pselect, max_desc + 1,
5197 &Atemp,
5198 (num_pending_connects > 0 ? &Ctemp : NULL),
5199 NULL, &timeout, NULL)
5200 <= 0))
5202 /* It's okay for us to do this and then continue with
5203 the loop, since timeout has already been zeroed out. */
5204 clear_waiting_for_input ();
5205 got_some_output = status_notify (NULL, wait_proc);
5206 if (do_display) redisplay_preserve_echo_area (13);
5210 /* Don't wait for output from a non-running process. Just
5211 read whatever data has already been received. */
5212 if (wait_proc && wait_proc->raw_status_new)
5213 update_status (wait_proc);
5214 if (wait_proc
5215 && ! EQ (wait_proc->status, Qrun)
5216 && ! connecting_status (wait_proc->status))
5218 bool read_some_bytes = false;
5220 clear_waiting_for_input ();
5222 /* If data can be read from the process, do so until exhausted. */
5223 if (wait_proc->infd >= 0)
5225 XSETPROCESS (proc, wait_proc);
5227 while (true)
5229 int nread = read_process_output (proc, wait_proc->infd);
5230 if (nread < 0)
5232 if (errno == EIO || would_block (errno))
5233 break;
5235 else
5237 if (got_some_output < nread)
5238 got_some_output = nread;
5239 if (nread == 0)
5240 break;
5241 read_some_bytes = true;
5246 if (read_some_bytes && do_display)
5247 redisplay_preserve_echo_area (10);
5249 break;
5252 /* Wait till there is something to do. */
5254 if (wait_proc && just_wait_proc)
5256 if (wait_proc->infd < 0) /* Terminated. */
5257 break;
5258 FD_SET (wait_proc->infd, &Available);
5259 check_delay = 0;
5260 check_write = 0;
5262 else if (!NILP (wait_for_cell))
5264 compute_non_process_wait_mask (&Available);
5265 check_delay = 0;
5266 check_write = 0;
5268 else
5270 if (! read_kbd)
5271 compute_non_keyboard_wait_mask (&Available);
5272 else
5273 compute_input_wait_mask (&Available);
5274 compute_write_mask (&Writeok);
5275 check_delay = wait_proc ? 0 : process_output_delay_count;
5276 check_write = true;
5279 /* If frame size has changed or the window is newly mapped,
5280 redisplay now, before we start to wait. There is a race
5281 condition here; if a SIGIO arrives between now and the select
5282 and indicates that a frame is trashed, the select may block
5283 displaying a trashed screen. */
5284 if (frame_garbaged && do_display)
5286 clear_waiting_for_input ();
5287 redisplay_preserve_echo_area (11);
5288 if (read_kbd < 0)
5289 set_waiting_for_input (&timeout);
5292 /* Skip the `select' call if input is available and we're
5293 waiting for keyboard input or a cell change (which can be
5294 triggered by processing X events). In the latter case, set
5295 nfds to 1 to avoid breaking the loop. */
5296 no_avail = 0;
5297 if ((read_kbd || !NILP (wait_for_cell))
5298 && detect_input_pending ())
5300 nfds = read_kbd ? 0 : 1;
5301 no_avail = 1;
5302 FD_ZERO (&Available);
5304 else
5306 /* Set the timeout for adaptive read buffering if any
5307 process has non-zero read_output_skip and non-zero
5308 read_output_delay, and we are not reading output for a
5309 specific process. It is not executed if
5310 Vprocess_adaptive_read_buffering is nil. */
5311 if (process_output_skip && check_delay > 0)
5313 int adaptive_nsecs = timeout.tv_nsec;
5314 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5315 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5316 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5318 proc = chan_process[channel];
5319 if (NILP (proc))
5320 continue;
5321 /* Find minimum non-zero read_output_delay among the
5322 processes with non-zero read_output_skip. */
5323 if (XPROCESS (proc)->read_output_delay > 0)
5325 check_delay--;
5326 if (!XPROCESS (proc)->read_output_skip)
5327 continue;
5328 FD_CLR (channel, &Available);
5329 process_skipped = true;
5330 XPROCESS (proc)->read_output_skip = 0;
5331 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5332 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5335 timeout = make_timespec (0, adaptive_nsecs);
5336 process_output_skip = 0;
5339 /* If we've got some output and haven't limited our timeout
5340 with adaptive read buffering, limit it. */
5341 if (got_some_output > 0 && !process_skipped
5342 && (timeout.tv_sec
5343 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5344 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5347 if (NILP (wait_for_cell) && just_wait_proc >= 0
5348 && timespec_valid_p (timer_delay)
5349 && timespec_cmp (timer_delay, timeout) < 0)
5351 if (!timespec_valid_p (now))
5352 now = current_timespec ();
5353 struct timespec timeout_abs = timespec_add (now, timeout);
5354 if (!timespec_valid_p (got_output_end_time)
5355 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5356 got_output_end_time = timeout_abs;
5357 timeout = timer_delay;
5359 else
5360 got_output_end_time = invalid_timespec ();
5362 /* NOW can become inaccurate if time can pass during pselect. */
5363 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5364 now = invalid_timespec ();
5366 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5367 if (retry_for_async
5368 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5370 timeout.tv_sec = 0;
5371 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5373 #endif
5375 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5376 #if defined HAVE_GLIB && !defined HAVE_NS
5377 nfds = xg_select (max_desc + 1,
5378 &Available, (check_write ? &Writeok : 0),
5379 NULL, &timeout, NULL);
5380 #elif defined HAVE_NS
5381 /* And NS builds call thread_select in ns_select. */
5382 nfds = ns_select (max_desc + 1,
5383 &Available, (check_write ? &Writeok : 0),
5384 NULL, &timeout, NULL);
5385 #else /* !HAVE_GLIB */
5386 nfds = thread_select (pselect, max_desc + 1,
5387 &Available,
5388 (check_write ? &Writeok : 0),
5389 NULL, &timeout, NULL);
5390 #endif /* !HAVE_GLIB */
5392 #ifdef HAVE_GNUTLS
5393 /* GnuTLS buffers data internally. In lowat mode it leaves
5394 some data in the TCP buffers so that select works, but
5395 with custom pull/push functions we need to check if some
5396 data is available in the buffers manually. */
5397 if (nfds == 0)
5399 fd_set tls_available;
5400 int set = 0;
5402 FD_ZERO (&tls_available);
5403 if (! wait_proc)
5405 /* We're not waiting on a specific process, so loop
5406 through all the channels and check for data.
5407 This is a workaround needed for some versions of
5408 the gnutls library -- 2.12.14 has been confirmed
5409 to need it. See
5410 http://comments.gmane.org/gmane.emacs.devel/145074 */
5411 for (channel = 0; channel < FD_SETSIZE; ++channel)
5412 if (! NILP (chan_process[channel]))
5414 struct Lisp_Process *p =
5415 XPROCESS (chan_process[channel]);
5416 if (p && p->gnutls_p && p->gnutls_state
5417 && ((emacs_gnutls_record_check_pending
5418 (p->gnutls_state))
5419 > 0))
5421 nfds++;
5422 eassert (p->infd == channel);
5423 FD_SET (p->infd, &tls_available);
5424 set++;
5428 else
5430 /* Check this specific channel. */
5431 if (wait_proc->gnutls_p /* Check for valid process. */
5432 && wait_proc->gnutls_state
5433 /* Do we have pending data? */
5434 && ((emacs_gnutls_record_check_pending
5435 (wait_proc->gnutls_state))
5436 > 0))
5438 nfds = 1;
5439 eassert (0 <= wait_proc->infd);
5440 /* Set to Available. */
5441 FD_SET (wait_proc->infd, &tls_available);
5442 set++;
5445 if (set)
5446 Available = tls_available;
5448 #endif
5451 xerrno = errno;
5453 /* Make C-g and alarm signals set flags again. */
5454 clear_waiting_for_input ();
5456 /* If we woke up due to SIGWINCH, actually change size now. */
5457 do_pending_window_change (0);
5459 if (nfds == 0)
5461 /* Exit the main loop if we've passed the requested timeout,
5462 or aren't skipping processes and got some output and
5463 haven't lowered our timeout due to timers or SIGIO and
5464 have waited a long amount of time due to repeated
5465 timers. */
5466 struct timespec huge_timespec
5467 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5468 struct timespec cmp_time = huge_timespec;
5469 if (wait < TIMEOUT)
5470 break;
5471 if (wait == TIMEOUT)
5472 cmp_time = end_time;
5473 if (!process_skipped && got_some_output > 0
5474 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5476 if (!timespec_valid_p (got_output_end_time))
5477 break;
5478 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5479 cmp_time = got_output_end_time;
5481 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5483 now = current_timespec ();
5484 if (timespec_cmp (cmp_time, now) <= 0)
5485 break;
5489 if (nfds < 0)
5491 if (xerrno == EINTR)
5492 no_avail = 1;
5493 else if (xerrno == EBADF)
5494 emacs_abort ();
5495 else
5496 report_file_errno ("Failed select", Qnil, xerrno);
5499 /* Check for keyboard input. */
5500 /* If there is any, return immediately
5501 to give it higher priority than subprocesses. */
5503 if (read_kbd != 0)
5505 unsigned old_timers_run = timers_run;
5506 struct buffer *old_buffer = current_buffer;
5507 Lisp_Object old_window = selected_window;
5508 bool leave = false;
5510 if (detect_input_pending_run_timers (do_display))
5512 swallow_events (do_display);
5513 if (detect_input_pending_run_timers (do_display))
5514 leave = true;
5517 /* If a timer has run, this might have changed buffers
5518 an alike. Make read_key_sequence aware of that. */
5519 if (timers_run != old_timers_run
5520 && waiting_for_user_input_p == -1
5521 && (old_buffer != current_buffer
5522 || !EQ (old_window, selected_window)))
5523 record_asynch_buffer_change ();
5525 if (leave)
5526 break;
5529 /* If there is unread keyboard input, also return. */
5530 if (read_kbd != 0
5531 && requeued_events_pending_p ())
5532 break;
5534 /* If we are not checking for keyboard input now,
5535 do process events (but don't run any timers).
5536 This is so that X events will be processed.
5537 Otherwise they may have to wait until polling takes place.
5538 That would causes delays in pasting selections, for example.
5540 (We used to do this only if wait_for_cell.) */
5541 if (read_kbd == 0 && detect_input_pending ())
5543 swallow_events (do_display);
5544 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5545 if (detect_input_pending ())
5546 break;
5547 #endif
5550 /* Exit now if the cell we're waiting for became non-nil. */
5551 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5552 break;
5554 #ifdef USABLE_SIGIO
5555 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5556 go read it. This can happen with X on BSD after logging out.
5557 In that case, there really is no input and no SIGIO,
5558 but select says there is input. */
5560 if (read_kbd && interrupt_input
5561 && keyboard_bit_set (&Available) && ! noninteractive)
5562 handle_input_available_signal (SIGIO);
5563 #endif
5565 /* If checking input just got us a size-change event from X,
5566 obey it now if we should. */
5567 if (read_kbd || ! NILP (wait_for_cell))
5568 do_pending_window_change (0);
5570 /* Check for data from a process. */
5571 if (no_avail || nfds == 0)
5572 continue;
5574 for (channel = 0; channel <= max_desc; ++channel)
5576 struct fd_callback_data *d = &fd_callback_info[channel];
5577 if (d->func
5578 && ((d->flags & FOR_READ
5579 && FD_ISSET (channel, &Available))
5580 || ((d->flags & FOR_WRITE)
5581 && FD_ISSET (channel, &Writeok))))
5582 d->func (channel, d->data);
5585 for (channel = 0; channel <= max_desc; channel++)
5587 if (FD_ISSET (channel, &Available)
5588 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5589 == PROCESS_FD))
5591 int nread;
5593 /* If waiting for this channel, arrange to return as
5594 soon as no more input to be processed. No more
5595 waiting. */
5596 proc = chan_process[channel];
5597 if (NILP (proc))
5598 continue;
5600 /* If this is a server stream socket, accept connection. */
5601 if (EQ (XPROCESS (proc)->status, Qlisten))
5603 server_accept_connection (proc, channel);
5604 continue;
5607 /* Read data from the process, starting with our
5608 buffered-ahead character if we have one. */
5610 nread = read_process_output (proc, channel);
5611 if ((!wait_proc || wait_proc == XPROCESS (proc))
5612 && got_some_output < nread)
5613 got_some_output = nread;
5614 if (nread > 0)
5616 /* Vacuum up any leftovers without waiting. */
5617 if (wait_proc == XPROCESS (proc))
5618 wait = MINIMUM;
5619 /* Since read_process_output can run a filter,
5620 which can call accept-process-output,
5621 don't try to read from any other processes
5622 before doing the select again. */
5623 FD_ZERO (&Available);
5625 if (do_display)
5626 redisplay_preserve_echo_area (12);
5628 else if (nread == -1 && would_block (errno))
5630 #ifdef WINDOWSNT
5631 /* FIXME: Is this special case still needed? */
5632 /* Note that we cannot distinguish between no input
5633 available now and a closed pipe.
5634 With luck, a closed pipe will be accompanied by
5635 subprocess termination and SIGCHLD. */
5636 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5637 && !PIPECONN_P (proc))
5639 #endif
5640 #ifdef HAVE_PTYS
5641 /* On some OSs with ptys, when the process on one end of
5642 a pty exits, the other end gets an error reading with
5643 errno = EIO instead of getting an EOF (0 bytes read).
5644 Therefore, if we get an error reading and errno =
5645 EIO, just continue, because the child process has
5646 exited and should clean itself up soon (e.g. when we
5647 get a SIGCHLD). */
5648 else if (nread == -1 && errno == EIO)
5650 struct Lisp_Process *p = XPROCESS (proc);
5652 /* Clear the descriptor now, so we only raise the
5653 signal once. */
5654 delete_read_fd (channel);
5656 if (p->pid == -2)
5658 /* If the EIO occurs on a pty, the SIGCHLD handler's
5659 waitpid call will not find the process object to
5660 delete. Do it here. */
5661 p->tick = ++process_tick;
5662 pset_status (p, Qfailed);
5665 #endif /* HAVE_PTYS */
5666 /* If we can detect process termination, don't consider the
5667 process gone just because its pipe is closed. */
5668 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5669 && !PIPECONN_P (proc))
5671 else if (nread == 0 && PIPECONN_P (proc))
5673 /* Preserve status of processes already terminated. */
5674 XPROCESS (proc)->tick = ++process_tick;
5675 deactivate_process (proc);
5676 if (EQ (XPROCESS (proc)->status, Qrun))
5677 pset_status (XPROCESS (proc),
5678 list2 (Qexit, make_number (0)));
5680 else
5682 /* Preserve status of processes already terminated. */
5683 XPROCESS (proc)->tick = ++process_tick;
5684 deactivate_process (proc);
5685 if (XPROCESS (proc)->raw_status_new)
5686 update_status (XPROCESS (proc));
5687 if (EQ (XPROCESS (proc)->status, Qrun))
5688 pset_status (XPROCESS (proc),
5689 list2 (Qexit, make_number (256)));
5692 if (FD_ISSET (channel, &Writeok)
5693 && (fd_callback_info[channel].flags
5694 & NON_BLOCKING_CONNECT_FD) != 0)
5696 struct Lisp_Process *p;
5698 delete_write_fd (channel);
5700 proc = chan_process[channel];
5701 if (NILP (proc))
5702 continue;
5704 p = XPROCESS (proc);
5706 #ifndef WINDOWSNT
5708 socklen_t xlen = sizeof (xerrno);
5709 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5710 xerrno = errno;
5712 #else
5713 /* On MS-Windows, getsockopt clears the error for the
5714 entire process, which may not be the right thing; see
5715 w32.c. Use getpeername instead. */
5717 struct sockaddr pname;
5718 socklen_t pnamelen = sizeof (pname);
5720 /* If connection failed, getpeername will fail. */
5721 xerrno = 0;
5722 if (getpeername (channel, &pname, &pnamelen) < 0)
5724 /* Obtain connect failure code through error slippage. */
5725 char dummy;
5726 xerrno = errno;
5727 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5728 xerrno = errno;
5731 #endif
5732 if (xerrno)
5734 Lisp_Object addrinfos
5735 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5736 if (!NILP (addrinfos))
5737 XSETCDR (p->status, XCDR (addrinfos));
5738 else
5740 p->tick = ++process_tick;
5741 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5743 deactivate_process (proc);
5744 if (!NILP (addrinfos))
5745 connect_network_socket (proc, addrinfos, Qnil);
5747 else
5749 #ifdef HAVE_GNUTLS
5750 /* If we have an incompletely set up TLS connection,
5751 then defer the sentinel signaling until
5752 later. */
5753 if (NILP (p->gnutls_boot_parameters)
5754 && !p->gnutls_p)
5755 #endif
5757 pset_status (p, Qrun);
5758 /* Execute the sentinel here. If we had relied on
5759 status_notify to do it later, it will read input
5760 from the process before calling the sentinel. */
5761 exec_sentinel (proc, build_string ("open\n"));
5764 if (0 <= p->infd && !EQ (p->filter, Qt)
5765 && !EQ (p->command, Qt))
5766 add_process_read_fd (p->infd);
5769 } /* End for each file descriptor. */
5770 } /* End while exit conditions not met. */
5772 unbind_to (count, Qnil);
5774 /* If calling from keyboard input, do not quit
5775 since we want to return C-g as an input character.
5776 Otherwise, do pending quit if requested. */
5777 if (read_kbd >= 0)
5779 /* Prevent input_pending from remaining set if we quit. */
5780 clear_input_pending ();
5781 maybe_quit ();
5784 return got_some_output;
5787 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5789 static Lisp_Object
5790 read_process_output_call (Lisp_Object fun_and_args)
5792 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5795 static Lisp_Object
5796 read_process_output_error_handler (Lisp_Object error_val)
5798 cmd_error_internal (error_val, "error in process filter: ");
5799 Vinhibit_quit = Qt;
5800 update_echo_area ();
5801 Fsleep_for (make_number (2), Qnil);
5802 return Qt;
5805 static void
5806 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5807 ssize_t nbytes,
5808 struct coding_system *coding);
5810 /* Read pending output from the process channel,
5811 starting with our buffered-ahead character if we have one.
5812 Yield number of decoded characters read.
5814 This function reads at most 4096 characters.
5815 If you want to read all available subprocess output,
5816 you must call it repeatedly until it returns zero.
5818 The characters read are decoded according to PROC's coding-system
5819 for decoding. */
5821 static int
5822 read_process_output (Lisp_Object proc, int channel)
5824 ssize_t nbytes;
5825 struct Lisp_Process *p = XPROCESS (proc);
5826 struct coding_system *coding = proc_decode_coding_system[channel];
5827 int carryover = p->decoding_carryover;
5828 enum { readmax = 4096 };
5829 ptrdiff_t count = SPECPDL_INDEX ();
5830 Lisp_Object odeactivate;
5831 char chars[sizeof coding->carryover + readmax];
5833 if (carryover)
5834 /* See the comment above. */
5835 memcpy (chars, SDATA (p->decoding_buf), carryover);
5837 #ifdef DATAGRAM_SOCKETS
5838 /* We have a working select, so proc_buffered_char is always -1. */
5839 if (DATAGRAM_CHAN_P (channel))
5841 socklen_t len = datagram_address[channel].len;
5842 nbytes = recvfrom (channel, chars + carryover, readmax,
5843 0, datagram_address[channel].sa, &len);
5845 else
5846 #endif
5848 bool buffered = proc_buffered_char[channel] >= 0;
5849 if (buffered)
5851 chars[carryover] = proc_buffered_char[channel];
5852 proc_buffered_char[channel] = -1;
5854 #ifdef HAVE_GNUTLS
5855 if (p->gnutls_p && p->gnutls_state)
5856 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5857 readmax - buffered);
5858 else
5859 #endif
5860 nbytes = emacs_read (channel, chars + carryover + buffered,
5861 readmax - buffered);
5862 if (nbytes > 0 && p->adaptive_read_buffering)
5864 int delay = p->read_output_delay;
5865 if (nbytes < 256)
5867 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5869 if (delay == 0)
5870 process_output_delay_count++;
5871 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5874 else if (delay > 0 && nbytes == readmax - buffered)
5876 delay -= READ_OUTPUT_DELAY_INCREMENT;
5877 if (delay == 0)
5878 process_output_delay_count--;
5880 p->read_output_delay = delay;
5881 if (delay)
5883 p->read_output_skip = 1;
5884 process_output_skip = 1;
5887 nbytes += buffered;
5888 nbytes += buffered && nbytes <= 0;
5891 p->decoding_carryover = 0;
5893 /* At this point, NBYTES holds number of bytes just received
5894 (including the one in proc_buffered_char[channel]). */
5895 if (nbytes <= 0)
5897 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5898 return nbytes;
5899 coding->mode |= CODING_MODE_LAST_BLOCK;
5902 /* Now set NBYTES how many bytes we must decode. */
5903 nbytes += carryover;
5905 odeactivate = Vdeactivate_mark;
5906 /* There's no good reason to let process filters change the current
5907 buffer, and many callers of accept-process-output, sit-for, and
5908 friends don't expect current-buffer to be changed from under them. */
5909 record_unwind_current_buffer ();
5911 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5913 /* Handling the process output should not deactivate the mark. */
5914 Vdeactivate_mark = odeactivate;
5916 unbind_to (count, Qnil);
5917 return nbytes;
5920 static void
5921 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5922 ssize_t nbytes,
5923 struct coding_system *coding)
5925 Lisp_Object outstream = p->filter;
5926 Lisp_Object text;
5927 bool outer_running_asynch_code = running_asynch_code;
5928 int waiting = waiting_for_user_input_p;
5930 #if 0
5931 Lisp_Object obuffer, okeymap;
5932 XSETBUFFER (obuffer, current_buffer);
5933 okeymap = BVAR (current_buffer, keymap);
5934 #endif
5936 /* We inhibit quit here instead of just catching it so that
5937 hitting ^G when a filter happens to be running won't screw
5938 it up. */
5939 specbind (Qinhibit_quit, Qt);
5940 specbind (Qlast_nonmenu_event, Qt);
5942 /* In case we get recursively called,
5943 and we already saved the match data nonrecursively,
5944 save the same match data in safely recursive fashion. */
5945 if (outer_running_asynch_code)
5947 Lisp_Object tem;
5948 /* Don't clobber the CURRENT match data, either! */
5949 tem = Fmatch_data (Qnil, Qnil, Qnil);
5950 restore_search_regs ();
5951 record_unwind_save_match_data ();
5952 Fset_match_data (tem, Qt);
5955 /* For speed, if a search happens within this code,
5956 save the match data in a special nonrecursive fashion. */
5957 running_asynch_code = 1;
5959 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5960 text = coding->dst_object;
5961 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5962 /* A new coding system might be found. */
5963 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5965 pset_decode_coding_system (p, Vlast_coding_system_used);
5967 /* Don't call setup_coding_system for
5968 proc_decode_coding_system[channel] here. It is done in
5969 detect_coding called via decode_coding above. */
5971 /* If a coding system for encoding is not yet decided, we set
5972 it as the same as coding-system for decoding.
5974 But, before doing that we must check if
5975 proc_encode_coding_system[p->outfd] surely points to a
5976 valid memory because p->outfd will be changed once EOF is
5977 sent to the process. */
5978 if (NILP (p->encode_coding_system) && p->outfd >= 0
5979 && proc_encode_coding_system[p->outfd])
5981 pset_encode_coding_system
5982 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5983 setup_coding_system (p->encode_coding_system,
5984 proc_encode_coding_system[p->outfd]);
5988 if (coding->carryover_bytes > 0)
5990 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5991 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5992 memcpy (SDATA (p->decoding_buf), coding->carryover,
5993 coding->carryover_bytes);
5994 p->decoding_carryover = coding->carryover_bytes;
5996 if (SBYTES (text) > 0)
5997 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5998 sometimes it's simply wrong to wrap (e.g. when called from
5999 accept-process-output). */
6000 internal_condition_case_1 (read_process_output_call,
6001 list3 (outstream, make_lisp_proc (p), text),
6002 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6003 read_process_output_error_handler);
6005 /* If we saved the match data nonrecursively, restore it now. */
6006 restore_search_regs ();
6007 running_asynch_code = outer_running_asynch_code;
6009 /* Restore waiting_for_user_input_p as it was
6010 when we were called, in case the filter clobbered it. */
6011 waiting_for_user_input_p = waiting;
6013 #if 0 /* Call record_asynch_buffer_change unconditionally,
6014 because we might have changed minor modes or other things
6015 that affect key bindings. */
6016 if (! EQ (Fcurrent_buffer (), obuffer)
6017 || ! EQ (current_buffer->keymap, okeymap))
6018 #endif
6019 /* But do it only if the caller is actually going to read events.
6020 Otherwise there's no need to make him wake up, and it could
6021 cause trouble (for example it would make sit_for return). */
6022 if (waiting_for_user_input_p == -1)
6023 record_asynch_buffer_change ();
6026 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
6027 Sinternal_default_process_filter, 2, 2, 0,
6028 doc: /* Function used as default process filter.
6029 This inserts the process's output into its buffer, if there is one.
6030 Otherwise it discards the output. */)
6031 (Lisp_Object proc, Lisp_Object text)
6033 struct Lisp_Process *p;
6034 ptrdiff_t opoint;
6036 CHECK_PROCESS (proc);
6037 p = XPROCESS (proc);
6038 CHECK_STRING (text);
6040 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6042 Lisp_Object old_read_only;
6043 ptrdiff_t old_begv, old_zv;
6044 ptrdiff_t old_begv_byte, old_zv_byte;
6045 ptrdiff_t before, before_byte;
6046 ptrdiff_t opoint_byte;
6047 struct buffer *b;
6049 Fset_buffer (p->buffer);
6050 opoint = PT;
6051 opoint_byte = PT_BYTE;
6052 old_read_only = BVAR (current_buffer, read_only);
6053 old_begv = BEGV;
6054 old_zv = ZV;
6055 old_begv_byte = BEGV_BYTE;
6056 old_zv_byte = ZV_BYTE;
6058 bset_read_only (current_buffer, Qnil);
6060 /* Insert new output into buffer at the current end-of-output
6061 marker, thus preserving logical ordering of input and output. */
6062 if (XMARKER (p->mark)->buffer)
6063 set_point_from_marker (p->mark);
6064 else
6065 SET_PT_BOTH (ZV, ZV_BYTE);
6066 before = PT;
6067 before_byte = PT_BYTE;
6069 /* If the output marker is outside of the visible region, save
6070 the restriction and widen. */
6071 if (! (BEGV <= PT && PT <= ZV))
6072 Fwiden ();
6074 /* Adjust the multibyteness of TEXT to that of the buffer. */
6075 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6076 != ! STRING_MULTIBYTE (text))
6077 text = (STRING_MULTIBYTE (text)
6078 ? Fstring_as_unibyte (text)
6079 : Fstring_to_multibyte (text));
6080 /* Insert before markers in case we are inserting where
6081 the buffer's mark is, and the user's next command is Meta-y. */
6082 insert_from_string_before_markers (text, 0, 0,
6083 SCHARS (text), SBYTES (text), 0);
6085 /* Make sure the process marker's position is valid when the
6086 process buffer is changed in the signal_after_change above.
6087 W3 is known to do that. */
6088 if (BUFFERP (p->buffer)
6089 && (b = XBUFFER (p->buffer), b != current_buffer))
6090 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6091 else
6092 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6094 update_mode_lines = 23;
6096 /* Make sure opoint and the old restrictions
6097 float ahead of any new text just as point would. */
6098 if (opoint >= before)
6100 opoint += PT - before;
6101 opoint_byte += PT_BYTE - before_byte;
6103 if (old_begv > before)
6105 old_begv += PT - before;
6106 old_begv_byte += PT_BYTE - before_byte;
6108 if (old_zv >= before)
6110 old_zv += PT - before;
6111 old_zv_byte += PT_BYTE - before_byte;
6114 /* If the restriction isn't what it should be, set it. */
6115 if (old_begv != BEGV || old_zv != ZV)
6116 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
6118 bset_read_only (current_buffer, old_read_only);
6119 SET_PT_BOTH (opoint, opoint_byte);
6121 return Qnil;
6124 /* Sending data to subprocess. */
6126 /* In send_process, when a write fails temporarily,
6127 wait_reading_process_output is called. It may execute user code,
6128 e.g. timers, that attempts to write new data to the same process.
6129 We must ensure that data is sent in the right order, and not
6130 interspersed half-completed with other writes (Bug#10815). This is
6131 handled by the write_queue element of struct process. It is a list
6132 with each entry having the form
6134 (string . (offset . length))
6136 where STRING is a lisp string, OFFSET is the offset into the
6137 string's byte sequence from which we should begin to send, and
6138 LENGTH is the number of bytes left to send. */
6140 /* Create a new entry in write_queue.
6141 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6142 BUF is a pointer to the string sequence of the input_obj or a C
6143 string in case of Qt or Qnil. */
6145 static void
6146 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6147 const char *buf, ptrdiff_t len, bool front)
6149 ptrdiff_t offset;
6150 Lisp_Object entry, obj;
6152 if (STRINGP (input_obj))
6154 offset = buf - SSDATA (input_obj);
6155 obj = input_obj;
6157 else
6159 offset = 0;
6160 obj = make_unibyte_string (buf, len);
6163 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
6165 if (front)
6166 pset_write_queue (p, Fcons (entry, p->write_queue));
6167 else
6168 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6171 /* Remove the first element in the write_queue of process P, put its
6172 contents in OBJ, BUF and LEN, and return true. If the
6173 write_queue is empty, return false. */
6175 static bool
6176 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6177 const char **buf, ptrdiff_t *len)
6179 Lisp_Object entry, offset_length;
6180 ptrdiff_t offset;
6182 if (NILP (p->write_queue))
6183 return 0;
6185 entry = XCAR (p->write_queue);
6186 pset_write_queue (p, XCDR (p->write_queue));
6188 *obj = XCAR (entry);
6189 offset_length = XCDR (entry);
6191 *len = XINT (XCDR (offset_length));
6192 offset = XINT (XCAR (offset_length));
6193 *buf = SSDATA (*obj) + offset;
6195 return 1;
6198 /* Send some data to process PROC.
6199 BUF is the beginning of the data; LEN is the number of characters.
6200 OBJECT is the Lisp object that the data comes from. If OBJECT is
6201 nil or t, it means that the data comes from C string.
6203 If OBJECT is not nil, the data is encoded by PROC's coding-system
6204 for encoding before it is sent.
6206 This function can evaluate Lisp code and can garbage collect. */
6208 static void
6209 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6210 Lisp_Object object)
6212 struct Lisp_Process *p = XPROCESS (proc);
6213 ssize_t rv;
6214 struct coding_system *coding;
6216 if (NETCONN_P (proc))
6218 wait_while_connecting (proc);
6219 wait_for_tls_negotiation (proc);
6222 if (p->raw_status_new)
6223 update_status (p);
6224 if (! EQ (p->status, Qrun))
6225 error ("Process %s not running", SDATA (p->name));
6226 if (p->outfd < 0)
6227 error ("Output file descriptor of %s is closed", SDATA (p->name));
6229 coding = proc_encode_coding_system[p->outfd];
6230 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6232 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6233 || (BUFFERP (object)
6234 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6235 || EQ (object, Qt))
6237 pset_encode_coding_system
6238 (p, complement_process_encoding_system (p->encode_coding_system));
6239 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6241 /* The coding system for encoding was changed to raw-text
6242 because we sent a unibyte text previously. Now we are
6243 sending a multibyte text, thus we must encode it by the
6244 original coding system specified for the current process.
6246 Another reason we come here is that the coding system
6247 was just complemented and a new one was returned by
6248 complement_process_encoding_system. */
6249 setup_coding_system (p->encode_coding_system, coding);
6250 Vlast_coding_system_used = p->encode_coding_system;
6252 coding->src_multibyte = 1;
6254 else
6256 coding->src_multibyte = 0;
6257 /* For sending a unibyte text, character code conversion should
6258 not take place but EOL conversion should. So, setup raw-text
6259 or one of the subsidiary if we have not yet done it. */
6260 if (CODING_REQUIRE_ENCODING (coding))
6262 if (CODING_REQUIRE_FLUSHING (coding))
6264 /* But, before changing the coding, we must flush out data. */
6265 coding->mode |= CODING_MODE_LAST_BLOCK;
6266 send_process (proc, "", 0, Qt);
6267 coding->mode &= CODING_MODE_LAST_BLOCK;
6269 setup_coding_system (raw_text_coding_system
6270 (Vlast_coding_system_used),
6271 coding);
6272 coding->src_multibyte = 0;
6275 coding->dst_multibyte = 0;
6277 if (CODING_REQUIRE_ENCODING (coding))
6279 coding->dst_object = Qt;
6280 if (BUFFERP (object))
6282 ptrdiff_t from_byte, from, to;
6283 ptrdiff_t save_pt, save_pt_byte;
6284 struct buffer *cur = current_buffer;
6286 set_buffer_internal (XBUFFER (object));
6287 save_pt = PT, save_pt_byte = PT_BYTE;
6289 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6290 from = BYTE_TO_CHAR (from_byte);
6291 to = BYTE_TO_CHAR (from_byte + len);
6292 TEMP_SET_PT_BOTH (from, from_byte);
6293 encode_coding_object (coding, object, from, from_byte,
6294 to, from_byte + len, Qt);
6295 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6296 set_buffer_internal (cur);
6298 else if (STRINGP (object))
6300 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6301 SBYTES (object), Qt);
6303 else
6305 coding->dst_object = make_unibyte_string (buf, len);
6306 coding->produced = len;
6309 len = coding->produced;
6310 object = coding->dst_object;
6311 buf = SSDATA (object);
6314 /* If there is already data in the write_queue, put the new data
6315 in the back of queue. Otherwise, ignore it. */
6316 if (!NILP (p->write_queue))
6317 write_queue_push (p, object, buf, len, 0);
6319 do /* while !NILP (p->write_queue) */
6321 ptrdiff_t cur_len = -1;
6322 const char *cur_buf;
6323 Lisp_Object cur_object;
6325 /* If write_queue is empty, ignore it. */
6326 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6328 cur_len = len;
6329 cur_buf = buf;
6330 cur_object = object;
6333 while (cur_len > 0)
6335 /* Send this batch, using one or more write calls. */
6336 ptrdiff_t written = 0;
6337 int outfd = p->outfd;
6338 #ifdef DATAGRAM_SOCKETS
6339 if (DATAGRAM_CHAN_P (outfd))
6341 rv = sendto (outfd, cur_buf, cur_len,
6342 0, datagram_address[outfd].sa,
6343 datagram_address[outfd].len);
6344 if (rv >= 0)
6345 written = rv;
6346 else if (errno == EMSGSIZE)
6347 report_file_error ("Sending datagram", proc);
6349 else
6350 #endif
6352 #ifdef HAVE_GNUTLS
6353 if (p->gnutls_p && p->gnutls_state)
6354 written = emacs_gnutls_write (p, cur_buf, cur_len);
6355 else
6356 #endif
6357 written = emacs_write_sig (outfd, cur_buf, cur_len);
6358 rv = (written ? 0 : -1);
6359 if (p->read_output_delay > 0
6360 && p->adaptive_read_buffering == 1)
6362 p->read_output_delay = 0;
6363 process_output_delay_count--;
6364 p->read_output_skip = 0;
6368 if (rv < 0)
6370 if (would_block (errno))
6371 /* Buffer is full. Wait, accepting input;
6372 that may allow the program
6373 to finish doing output and read more. */
6375 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6376 /* A gross hack to work around a bug in FreeBSD.
6377 In the following sequence, read(2) returns
6378 bogus data:
6380 write(2) 1022 bytes
6381 write(2) 954 bytes, get EAGAIN
6382 read(2) 1024 bytes in process_read_output
6383 read(2) 11 bytes in process_read_output
6385 That is, read(2) returns more bytes than have
6386 ever been written successfully. The 1033 bytes
6387 read are the 1022 bytes written successfully
6388 after processing (for example with CRs added if
6389 the terminal is set up that way which it is
6390 here). The same bytes will be seen again in a
6391 later read(2), without the CRs. */
6393 if (errno == EAGAIN)
6395 int flags = FWRITE;
6396 ioctl (p->outfd, TIOCFLUSH, &flags);
6398 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6400 /* Put what we should have written in wait_queue. */
6401 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6402 wait_reading_process_output (0, 20 * 1000 * 1000,
6403 0, 0, Qnil, NULL, 0);
6404 /* Reread queue, to see what is left. */
6405 break;
6407 else if (errno == EPIPE)
6409 p->raw_status_new = 0;
6410 pset_status (p, list2 (Qexit, make_number (256)));
6411 p->tick = ++process_tick;
6412 deactivate_process (proc);
6413 error ("process %s no longer connected to pipe; closed it",
6414 SDATA (p->name));
6416 else
6417 /* This is a real error. */
6418 report_file_error ("Writing to process", proc);
6420 cur_buf += written;
6421 cur_len -= written;
6424 while (!NILP (p->write_queue));
6427 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6428 3, 3, 0,
6429 doc: /* Send current contents of region as input to PROCESS.
6430 PROCESS may be a process, a buffer, the name of a process or buffer, or
6431 nil, indicating the current buffer's process.
6432 Called from program, takes three arguments, PROCESS, START and END.
6433 If the region is more than 500 characters long,
6434 it is sent in several bunches. This may happen even for shorter regions.
6435 Output from processes can arrive in between bunches.
6437 If PROCESS is a non-blocking network process that hasn't been fully
6438 set up yet, this function will block until socket setup has completed. */)
6439 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6441 Lisp_Object proc = get_process (process);
6442 ptrdiff_t start_byte, end_byte;
6444 validate_region (&start, &end);
6446 start_byte = CHAR_TO_BYTE (XINT (start));
6447 end_byte = CHAR_TO_BYTE (XINT (end));
6449 if (XINT (start) < GPT && XINT (end) > GPT)
6450 move_gap_both (XINT (start), start_byte);
6452 if (NETCONN_P (proc))
6453 wait_while_connecting (proc);
6455 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6456 end_byte - start_byte, Fcurrent_buffer ());
6458 return Qnil;
6461 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6462 2, 2, 0,
6463 doc: /* Send PROCESS the contents of STRING as input.
6464 PROCESS may be a process, a buffer, the name of a process or buffer, or
6465 nil, indicating the current buffer's process.
6466 If STRING is more than 500 characters long,
6467 it is sent in several bunches. This may happen even for shorter strings.
6468 Output from processes can arrive in between bunches.
6470 If PROCESS is a non-blocking network process that hasn't been fully
6471 set up yet, this function will block until socket setup has completed. */)
6472 (Lisp_Object process, Lisp_Object string)
6474 CHECK_STRING (string);
6475 Lisp_Object proc = get_process (process);
6476 send_process (proc, SSDATA (string),
6477 SBYTES (string), string);
6478 return Qnil;
6481 /* Return the foreground process group for the tty/pty that
6482 the process P uses. */
6483 static pid_t
6484 emacs_get_tty_pgrp (struct Lisp_Process *p)
6486 pid_t gid = -1;
6488 #ifdef TIOCGPGRP
6489 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6491 int fd;
6492 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6493 master side. Try the slave side. */
6494 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6496 if (fd != -1)
6498 ioctl (fd, TIOCGPGRP, &gid);
6499 emacs_close (fd);
6502 #endif /* defined (TIOCGPGRP ) */
6504 return gid;
6507 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6508 Sprocess_running_child_p, 0, 1, 0,
6509 doc: /* Return non-nil if PROCESS has given the terminal to a
6510 child. If the operating system does not make it possible to find out,
6511 return t. If we can find out, return the numeric ID of the foreground
6512 process group. */)
6513 (Lisp_Object process)
6515 /* Initialize in case ioctl doesn't exist or gives an error,
6516 in a way that will cause returning t. */
6517 Lisp_Object proc = get_process (process);
6518 struct Lisp_Process *p = XPROCESS (proc);
6520 if (!EQ (p->type, Qreal))
6521 error ("Process %s is not a subprocess",
6522 SDATA (p->name));
6523 if (p->infd < 0)
6524 error ("Process %s is not active",
6525 SDATA (p->name));
6527 pid_t gid = emacs_get_tty_pgrp (p);
6529 if (gid == p->pid)
6530 return Qnil;
6531 if (gid != -1)
6532 return make_number (gid);
6533 return Qt;
6536 /* Send a signal number SIGNO to PROCESS.
6537 If CURRENT_GROUP is t, that means send to the process group
6538 that currently owns the terminal being used to communicate with PROCESS.
6539 This is used for various commands in shell mode.
6540 If CURRENT_GROUP is lambda, that means send to the process group
6541 that currently owns the terminal, but only if it is NOT the shell itself.
6543 If NOMSG is false, insert signal-announcements into process's buffers
6544 right away.
6546 If we can, we try to signal PROCESS by sending control characters
6547 down the pty. This allows us to signal inferiors who have changed
6548 their uid, for which kill would return an EPERM error. */
6550 static void
6551 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6552 bool nomsg)
6554 Lisp_Object proc;
6555 struct Lisp_Process *p;
6556 pid_t gid;
6557 bool no_pgrp = 0;
6559 proc = get_process (process);
6560 p = XPROCESS (proc);
6562 if (!EQ (p->type, Qreal))
6563 error ("Process %s is not a subprocess",
6564 SDATA (p->name));
6565 if (p->infd < 0)
6566 error ("Process %s is not active",
6567 SDATA (p->name));
6569 if (!p->pty_flag)
6570 current_group = Qnil;
6572 /* If we are using pgrps, get a pgrp number and make it negative. */
6573 if (NILP (current_group))
6574 /* Send the signal to the shell's process group. */
6575 gid = p->pid;
6576 else
6578 #ifdef SIGNALS_VIA_CHARACTERS
6579 /* If possible, send signals to the entire pgrp
6580 by sending an input character to it. */
6582 struct termios t;
6583 cc_t *sig_char = NULL;
6585 tcgetattr (p->infd, &t);
6587 switch (signo)
6589 case SIGINT:
6590 sig_char = &t.c_cc[VINTR];
6591 break;
6593 case SIGQUIT:
6594 sig_char = &t.c_cc[VQUIT];
6595 break;
6597 case SIGTSTP:
6598 #ifdef VSWTCH
6599 sig_char = &t.c_cc[VSWTCH];
6600 #else
6601 sig_char = &t.c_cc[VSUSP];
6602 #endif
6603 break;
6606 if (sig_char && *sig_char != CDISABLE)
6608 send_process (proc, (char *) sig_char, 1, Qnil);
6609 return;
6611 /* If we can't send the signal with a character,
6612 fall through and send it another way. */
6614 /* The code above may fall through if it can't
6615 handle the signal. */
6616 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6618 #ifdef TIOCGPGRP
6619 /* Get the current pgrp using the tty itself, if we have that.
6620 Otherwise, use the pty to get the pgrp.
6621 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6622 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6623 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6624 His patch indicates that if TIOCGPGRP returns an error, then
6625 we should just assume that p->pid is also the process group id. */
6627 gid = emacs_get_tty_pgrp (p);
6629 if (gid == -1)
6630 /* If we can't get the information, assume
6631 the shell owns the tty. */
6632 gid = p->pid;
6634 /* It is not clear whether anything really can set GID to -1.
6635 Perhaps on some system one of those ioctls can or could do so.
6636 Or perhaps this is vestigial. */
6637 if (gid == -1)
6638 no_pgrp = 1;
6639 #else /* ! defined (TIOCGPGRP) */
6640 /* Can't select pgrps on this system, so we know that
6641 the child itself heads the pgrp. */
6642 gid = p->pid;
6643 #endif /* ! defined (TIOCGPGRP) */
6645 /* If current_group is lambda, and the shell owns the terminal,
6646 don't send any signal. */
6647 if (EQ (current_group, Qlambda) && gid == p->pid)
6648 return;
6651 #ifdef SIGCONT
6652 if (signo == SIGCONT)
6654 p->raw_status_new = 0;
6655 pset_status (p, Qrun);
6656 p->tick = ++process_tick;
6657 if (!nomsg)
6659 status_notify (NULL, NULL);
6660 redisplay_preserve_echo_area (13);
6663 #endif
6665 #ifdef TIOCSIGSEND
6666 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6667 We don't know whether the bug is fixed in later HP-UX versions. */
6668 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6669 return;
6670 #endif
6672 /* If we don't have process groups, send the signal to the immediate
6673 subprocess. That isn't really right, but it's better than any
6674 obvious alternative. */
6675 pid_t pid = no_pgrp ? gid : - gid;
6677 /* Do not kill an already-reaped process, as that could kill an
6678 innocent bystander that happens to have the same process ID. */
6679 sigset_t oldset;
6680 block_child_signal (&oldset);
6681 if (p->alive)
6682 kill (pid, signo);
6683 unblock_child_signal (&oldset);
6686 DEFUN ("internal-default-interrupt-process",
6687 Finternal_default_interrupt_process,
6688 Sinternal_default_interrupt_process, 0, 2, 0,
6689 doc: /* Default function to interrupt process PROCESS.
6690 It shall be the last element in list `interrupt-process-functions'.
6691 See function `interrupt-process' for more details on usage. */)
6692 (Lisp_Object process, Lisp_Object current_group)
6694 process_send_signal (process, SIGINT, current_group, 0);
6695 return process;
6698 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6699 doc: /* Interrupt process PROCESS.
6700 PROCESS may be a process, a buffer, or the name of a process or buffer.
6701 No arg or nil means current buffer's process.
6702 Second arg CURRENT-GROUP non-nil means send signal to
6703 the current process-group of the process's controlling terminal
6704 rather than to the process's own process group.
6705 If the process is a shell, this means interrupt current subjob
6706 rather than the shell.
6708 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6709 don't send the signal.
6711 This function calls the functions of `interrupt-process-functions' in
6712 the order of the list, until one of them returns non-`nil'. */)
6713 (Lisp_Object process, Lisp_Object current_group)
6715 return CALLN (Frun_hook_with_args_until_success, Qinterrupt_process_functions,
6716 process, current_group);
6719 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6720 doc: /* Kill process PROCESS. May be process or name of one.
6721 See function `interrupt-process' for more details on usage. */)
6722 (Lisp_Object process, Lisp_Object current_group)
6724 process_send_signal (process, SIGKILL, current_group, 0);
6725 return process;
6728 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6729 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6730 See function `interrupt-process' for more details on usage. */)
6731 (Lisp_Object process, Lisp_Object current_group)
6733 process_send_signal (process, SIGQUIT, current_group, 0);
6734 return process;
6737 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6738 doc: /* Stop process PROCESS. May be process or name of one.
6739 See function `interrupt-process' for more details on usage.
6740 If PROCESS is a network or serial or pipe connection, inhibit handling
6741 of incoming traffic. */)
6742 (Lisp_Object process, Lisp_Object current_group)
6744 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6745 || PIPECONN_P (process)))
6747 struct Lisp_Process *p;
6749 p = XPROCESS (process);
6750 if (NILP (p->command)
6751 && p->infd >= 0)
6752 delete_read_fd (p->infd);
6753 pset_command (p, Qt);
6754 return process;
6756 #ifndef SIGTSTP
6757 error ("No SIGTSTP support");
6758 #else
6759 process_send_signal (process, SIGTSTP, current_group, 0);
6760 #endif
6761 return process;
6764 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6765 doc: /* Continue process PROCESS. May be process or name of one.
6766 See function `interrupt-process' for more details on usage.
6767 If PROCESS is a network or serial process, resume handling of incoming
6768 traffic. */)
6769 (Lisp_Object process, Lisp_Object current_group)
6771 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6772 || PIPECONN_P (process)))
6774 struct Lisp_Process *p;
6776 p = XPROCESS (process);
6777 if (EQ (p->command, Qt)
6778 && p->infd >= 0
6779 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6781 add_process_read_fd (p->infd);
6782 #ifdef WINDOWSNT
6783 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6784 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6785 #else /* not WINDOWSNT */
6786 tcflush (p->infd, TCIFLUSH);
6787 #endif /* not WINDOWSNT */
6789 pset_command (p, Qnil);
6790 return process;
6792 #ifdef SIGCONT
6793 process_send_signal (process, SIGCONT, current_group, 0);
6794 #else
6795 error ("No SIGCONT support");
6796 #endif
6797 return process;
6800 /* Return the integer value of the signal whose abbreviation is ABBR,
6801 or a negative number if there is no such signal. */
6802 static int
6803 abbr_to_signal (char const *name)
6805 int i, signo;
6806 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6808 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6809 name += 3;
6811 for (i = 0; i < sizeof sigbuf; i++)
6813 sigbuf[i] = c_toupper (name[i]);
6814 if (! sigbuf[i])
6815 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6818 return -1;
6821 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6822 2, 2, "sProcess (name or number): \nnSignal code: ",
6823 doc: /* Send PROCESS the signal with code SIGCODE.
6824 PROCESS may also be a number specifying the process id of the
6825 process to signal; in this case, the process need not be a child of
6826 this Emacs.
6827 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6828 (Lisp_Object process, Lisp_Object sigcode)
6830 pid_t pid;
6831 int signo;
6833 if (STRINGP (process))
6835 Lisp_Object tem = Fget_process (process);
6836 if (NILP (tem))
6838 Lisp_Object process_number
6839 = string_to_number (SSDATA (process), 10, 1);
6840 if (NUMBERP (process_number))
6841 tem = process_number;
6843 process = tem;
6845 else if (!NUMBERP (process))
6846 process = get_process (process);
6848 if (NILP (process))
6849 return process;
6851 if (NUMBERP (process))
6852 CONS_TO_INTEGER (process, pid_t, pid);
6853 else
6855 CHECK_PROCESS (process);
6856 pid = XPROCESS (process)->pid;
6857 if (pid <= 0)
6858 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6861 if (INTEGERP (sigcode))
6863 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6864 signo = XINT (sigcode);
6866 else
6868 char *name;
6870 CHECK_SYMBOL (sigcode);
6871 name = SSDATA (SYMBOL_NAME (sigcode));
6873 signo = abbr_to_signal (name);
6874 if (signo < 0)
6875 error ("Undefined signal name %s", name);
6878 return make_number (kill (pid, signo));
6881 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6882 doc: /* Make PROCESS see end-of-file in its input.
6883 EOF comes after any text already sent to it.
6884 PROCESS may be a process, a buffer, the name of a process or buffer, or
6885 nil, indicating the current buffer's process.
6886 If PROCESS is a network connection, or is a process communicating
6887 through a pipe (as opposed to a pty), then you cannot send any more
6888 text to PROCESS after you call this function.
6889 If PROCESS is a serial process, wait until all output written to the
6890 process has been transmitted to the serial port. */)
6891 (Lisp_Object process)
6893 Lisp_Object proc;
6894 struct coding_system *coding = NULL;
6895 int outfd;
6897 proc = get_process (process);
6899 if (NETCONN_P (proc))
6900 wait_while_connecting (proc);
6902 if (DATAGRAM_CONN_P (proc))
6903 return process;
6906 outfd = XPROCESS (proc)->outfd;
6907 if (outfd >= 0)
6908 coding = proc_encode_coding_system[outfd];
6910 /* Make sure the process is really alive. */
6911 if (XPROCESS (proc)->raw_status_new)
6912 update_status (XPROCESS (proc));
6913 if (! EQ (XPROCESS (proc)->status, Qrun))
6914 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6916 if (coding && CODING_REQUIRE_FLUSHING (coding))
6918 coding->mode |= CODING_MODE_LAST_BLOCK;
6919 send_process (proc, "", 0, Qnil);
6922 if (XPROCESS (proc)->pty_flag)
6923 send_process (proc, "\004", 1, Qnil);
6924 else if (EQ (XPROCESS (proc)->type, Qserial))
6926 #ifndef WINDOWSNT
6927 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6928 report_file_error ("Failed tcdrain", Qnil);
6929 #endif /* not WINDOWSNT */
6930 /* Do nothing on Windows because writes are blocking. */
6932 else
6934 struct Lisp_Process *p = XPROCESS (proc);
6935 int old_outfd = p->outfd;
6936 int new_outfd;
6938 #ifdef HAVE_SHUTDOWN
6939 /* If this is a network connection, or socketpair is used
6940 for communication with the subprocess, call shutdown to cause EOF.
6941 (In some old system, shutdown to socketpair doesn't work.
6942 Then we just can't win.) */
6943 if (0 <= old_outfd
6944 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6945 shutdown (old_outfd, 1);
6946 #endif
6947 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6948 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6949 if (new_outfd < 0)
6950 report_file_error ("Opening null device", Qnil);
6951 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6952 p->outfd = new_outfd;
6954 if (!proc_encode_coding_system[new_outfd])
6955 proc_encode_coding_system[new_outfd]
6956 = xmalloc (sizeof (struct coding_system));
6957 if (old_outfd >= 0)
6959 *proc_encode_coding_system[new_outfd]
6960 = *proc_encode_coding_system[old_outfd];
6961 memset (proc_encode_coding_system[old_outfd], 0,
6962 sizeof (struct coding_system));
6964 else
6965 setup_coding_system (p->encode_coding_system,
6966 proc_encode_coding_system[new_outfd]);
6968 return process;
6971 /* The main Emacs thread records child processes in three places:
6973 - Vprocess_alist, for asynchronous subprocesses, which are child
6974 processes visible to Lisp.
6976 - deleted_pid_list, for child processes invisible to Lisp,
6977 typically because of delete-process. These are recorded so that
6978 the processes can be reaped when they exit, so that the operating
6979 system's process table is not cluttered by zombies.
6981 - the local variable PID in Fcall_process, call_process_cleanup and
6982 call_process_kill, for synchronous subprocesses.
6983 record_unwind_protect is used to make sure this process is not
6984 forgotten: if the user interrupts call-process and the child
6985 process refuses to exit immediately even with two C-g's,
6986 call_process_kill adds PID's contents to deleted_pid_list before
6987 returning.
6989 The main Emacs thread invokes waitpid only on child processes that
6990 it creates and that have not been reaped. This avoid races on
6991 platforms such as GTK, where other threads create their own
6992 subprocesses which the main thread should not reap. For example,
6993 if the main thread attempted to reap an already-reaped child, it
6994 might inadvertently reap a GTK-created process that happened to
6995 have the same process ID. */
6997 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6998 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6999 keep track of its own children. GNUstep is similar. */
7001 static void dummy_handler (int sig) {}
7002 static signal_handler_t volatile lib_child_handler;
7004 /* Handle a SIGCHLD signal by looking for known child processes of
7005 Emacs whose status have changed. For each one found, record its
7006 new status.
7008 All we do is change the status; we do not run sentinels or print
7009 notifications. That is saved for the next time keyboard input is
7010 done, in order to avoid timing errors.
7012 ** WARNING: this can be called during garbage collection.
7013 Therefore, it must not be fooled by the presence of mark bits in
7014 Lisp objects.
7016 ** USG WARNING: Although it is not obvious from the documentation
7017 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7018 signal() before executing at least one wait(), otherwise the
7019 handler will be called again, resulting in an infinite loop. The
7020 relevant portion of the documentation reads "SIGCLD signals will be
7021 queued and the signal-catching function will be continually
7022 reentered until the queue is empty". Invoking signal() causes the
7023 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7024 Inc.
7026 ** Malloc WARNING: This should never call malloc either directly or
7027 indirectly; if it does, that is a bug. */
7029 static void
7030 handle_child_signal (int sig)
7032 Lisp_Object tail, proc;
7034 /* Find the process that signaled us, and record its status. */
7036 /* The process can have been deleted by Fdelete_process, or have
7037 been started asynchronously by Fcall_process. */
7038 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
7040 bool all_pids_are_fixnums
7041 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
7042 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
7043 Lisp_Object head = XCAR (tail);
7044 Lisp_Object xpid;
7045 if (! CONSP (head))
7046 continue;
7047 xpid = XCAR (head);
7048 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
7050 pid_t deleted_pid;
7051 if (INTEGERP (xpid))
7052 deleted_pid = XINT (xpid);
7053 else
7054 deleted_pid = XFLOAT_DATA (xpid);
7055 if (child_status_changed (deleted_pid, 0, 0))
7057 if (STRINGP (XCDR (head)))
7058 unlink (SSDATA (XCDR (head)));
7059 XSETCAR (tail, Qnil);
7064 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7065 FOR_EACH_PROCESS (tail, proc)
7067 struct Lisp_Process *p = XPROCESS (proc);
7068 int status;
7070 if (p->alive
7071 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7073 /* Change the status of the process that was found. */
7074 p->tick = ++process_tick;
7075 p->raw_status = status;
7076 p->raw_status_new = 1;
7078 /* If process has terminated, stop waiting for its output. */
7079 if (WIFSIGNALED (status) || WIFEXITED (status))
7081 bool clear_desc_flag = 0;
7082 p->alive = 0;
7083 if (p->infd >= 0)
7084 clear_desc_flag = 1;
7086 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7087 if (clear_desc_flag)
7088 delete_read_fd (p->infd);
7093 lib_child_handler (sig);
7094 #ifdef NS_IMPL_GNUSTEP
7095 /* NSTask in GNUstep sets its child handler each time it is called.
7096 So we must re-set ours. */
7097 catch_child_signal ();
7098 #endif
7101 static void
7102 deliver_child_signal (int sig)
7104 deliver_process_signal (sig, handle_child_signal);
7108 static Lisp_Object
7109 exec_sentinel_error_handler (Lisp_Object error_val)
7111 /* Make sure error_val is a cons cell, as all the rest of error
7112 handling expects that, and will barf otherwise. */
7113 if (!CONSP (error_val))
7114 error_val = Fcons (Qerror, error_val);
7115 cmd_error_internal (error_val, "error in process sentinel: ");
7116 Vinhibit_quit = Qt;
7117 update_echo_area ();
7118 Fsleep_for (make_number (2), Qnil);
7119 return Qt;
7122 static void
7123 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7125 Lisp_Object sentinel, odeactivate;
7126 struct Lisp_Process *p = XPROCESS (proc);
7127 ptrdiff_t count = SPECPDL_INDEX ();
7128 bool outer_running_asynch_code = running_asynch_code;
7129 int waiting = waiting_for_user_input_p;
7131 if (inhibit_sentinels)
7132 return;
7134 odeactivate = Vdeactivate_mark;
7135 #if 0
7136 Lisp_Object obuffer, okeymap;
7137 XSETBUFFER (obuffer, current_buffer);
7138 okeymap = BVAR (current_buffer, keymap);
7139 #endif
7141 /* There's no good reason to let sentinels change the current
7142 buffer, and many callers of accept-process-output, sit-for, and
7143 friends don't expect current-buffer to be changed from under them. */
7144 record_unwind_current_buffer ();
7146 sentinel = p->sentinel;
7148 /* Inhibit quit so that random quits don't screw up a running filter. */
7149 specbind (Qinhibit_quit, Qt);
7150 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7152 /* In case we get recursively called,
7153 and we already saved the match data nonrecursively,
7154 save the same match data in safely recursive fashion. */
7155 if (outer_running_asynch_code)
7157 Lisp_Object tem;
7158 tem = Fmatch_data (Qnil, Qnil, Qnil);
7159 restore_search_regs ();
7160 record_unwind_save_match_data ();
7161 Fset_match_data (tem, Qt);
7164 /* For speed, if a search happens within this code,
7165 save the match data in a special nonrecursive fashion. */
7166 running_asynch_code = 1;
7168 internal_condition_case_1 (read_process_output_call,
7169 list3 (sentinel, proc, reason),
7170 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7171 exec_sentinel_error_handler);
7173 /* If we saved the match data nonrecursively, restore it now. */
7174 restore_search_regs ();
7175 running_asynch_code = outer_running_asynch_code;
7177 Vdeactivate_mark = odeactivate;
7179 /* Restore waiting_for_user_input_p as it was
7180 when we were called, in case the filter clobbered it. */
7181 waiting_for_user_input_p = waiting;
7183 #if 0
7184 if (! EQ (Fcurrent_buffer (), obuffer)
7185 || ! EQ (current_buffer->keymap, okeymap))
7186 #endif
7187 /* But do it only if the caller is actually going to read events.
7188 Otherwise there's no need to make him wake up, and it could
7189 cause trouble (for example it would make sit_for return). */
7190 if (waiting_for_user_input_p == -1)
7191 record_asynch_buffer_change ();
7193 unbind_to (count, Qnil);
7196 /* Report all recent events of a change in process status
7197 (either run the sentinel or output a message).
7198 This is usually done while Emacs is waiting for keyboard input
7199 but can be done at other times.
7201 Return positive if any input was received from WAIT_PROC (or from
7202 any process if WAIT_PROC is null), zero if input was attempted but
7203 none received, and negative if we didn't even try. */
7205 static int
7206 status_notify (struct Lisp_Process *deleting_process,
7207 struct Lisp_Process *wait_proc)
7209 Lisp_Object proc;
7210 Lisp_Object tail, msg;
7211 int got_some_output = -1;
7213 tail = Qnil;
7214 msg = Qnil;
7216 /* Set this now, so that if new processes are created by sentinels
7217 that we run, we get called again to handle their status changes. */
7218 update_tick = process_tick;
7220 FOR_EACH_PROCESS (tail, proc)
7222 Lisp_Object symbol;
7223 register struct Lisp_Process *p = XPROCESS (proc);
7225 if (p->tick != p->update_tick)
7227 p->update_tick = p->tick;
7229 /* If process is still active, read any output that remains. */
7230 while (! EQ (p->filter, Qt)
7231 && ! connecting_status (p->status)
7232 && ! EQ (p->status, Qlisten)
7233 /* Network or serial process not stopped: */
7234 && ! EQ (p->command, Qt)
7235 && p->infd >= 0
7236 && p != deleting_process)
7238 int nread = read_process_output (proc, p->infd);
7239 if ((!wait_proc || wait_proc == XPROCESS (proc))
7240 && got_some_output < nread)
7241 got_some_output = nread;
7242 if (nread <= 0)
7243 break;
7246 /* Get the text to use for the message. */
7247 if (p->raw_status_new)
7248 update_status (p);
7249 msg = status_message (p);
7251 /* If process is terminated, deactivate it or delete it. */
7252 symbol = p->status;
7253 if (CONSP (p->status))
7254 symbol = XCAR (p->status);
7256 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7257 || EQ (symbol, Qclosed))
7259 if (delete_exited_processes)
7260 remove_process (proc);
7261 else
7262 deactivate_process (proc);
7265 /* The actions above may have further incremented p->tick.
7266 So set p->update_tick again so that an error in the sentinel will
7267 not cause this code to be run again. */
7268 p->update_tick = p->tick;
7269 /* Now output the message suitably. */
7270 exec_sentinel (proc, msg);
7271 if (BUFFERP (p->buffer))
7272 /* In case it uses %s in mode-line-format. */
7273 bset_update_mode_line (XBUFFER (p->buffer));
7275 } /* end for */
7277 return got_some_output;
7280 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7281 Sinternal_default_process_sentinel, 2, 2, 0,
7282 doc: /* Function used as default sentinel for processes.
7283 This inserts a status message into the process's buffer, if there is one. */)
7284 (Lisp_Object proc, Lisp_Object msg)
7286 Lisp_Object buffer, symbol;
7287 struct Lisp_Process *p;
7288 CHECK_PROCESS (proc);
7289 p = XPROCESS (proc);
7290 buffer = p->buffer;
7291 symbol = p->status;
7292 if (CONSP (symbol))
7293 symbol = XCAR (symbol);
7295 if (!EQ (symbol, Qrun) && !NILP (buffer))
7297 Lisp_Object tem;
7298 struct buffer *old = current_buffer;
7299 ptrdiff_t opoint, opoint_byte;
7300 ptrdiff_t before, before_byte;
7302 /* Avoid error if buffer is deleted
7303 (probably that's why the process is dead, too). */
7304 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7305 return Qnil;
7306 Fset_buffer (buffer);
7308 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7309 msg = (code_convert_string_norecord
7310 (msg, Vlocale_coding_system, 1));
7312 opoint = PT;
7313 opoint_byte = PT_BYTE;
7314 /* Insert new output into buffer
7315 at the current end-of-output marker,
7316 thus preserving logical ordering of input and output. */
7317 if (XMARKER (p->mark)->buffer)
7318 Fgoto_char (p->mark);
7319 else
7320 SET_PT_BOTH (ZV, ZV_BYTE);
7322 before = PT;
7323 before_byte = PT_BYTE;
7325 tem = BVAR (current_buffer, read_only);
7326 bset_read_only (current_buffer, Qnil);
7327 insert_string ("\nProcess ");
7328 { /* FIXME: temporary kludge. */
7329 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7330 insert_string (" ");
7331 Finsert (1, &msg);
7332 bset_read_only (current_buffer, tem);
7333 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7335 if (opoint >= before)
7336 SET_PT_BOTH (opoint + (PT - before),
7337 opoint_byte + (PT_BYTE - before_byte));
7338 else
7339 SET_PT_BOTH (opoint, opoint_byte);
7341 set_buffer_internal (old);
7343 return Qnil;
7347 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7348 Sset_process_coding_system, 1, 3, 0,
7349 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7350 DECODING will be used to decode subprocess output and ENCODING to
7351 encode subprocess input. */)
7352 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7354 CHECK_PROCESS (process);
7356 struct Lisp_Process *p = XPROCESS (process);
7358 Fcheck_coding_system (decoding);
7359 Fcheck_coding_system (encoding);
7360 encoding = coding_inherit_eol_type (encoding, Qnil);
7361 pset_decode_coding_system (p, decoding);
7362 pset_encode_coding_system (p, encoding);
7364 /* If the sockets haven't been set up yet, the final setup part of
7365 this will be called asynchronously. */
7366 if (p->infd < 0 || p->outfd < 0)
7367 return Qnil;
7369 setup_process_coding_systems (process);
7371 return Qnil;
7374 DEFUN ("process-coding-system",
7375 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7376 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7377 (register Lisp_Object process)
7379 CHECK_PROCESS (process);
7380 return Fcons (XPROCESS (process)->decode_coding_system,
7381 XPROCESS (process)->encode_coding_system);
7384 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7385 Sset_process_filter_multibyte, 2, 2, 0,
7386 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7387 If FLAG is non-nil, the filter is given multibyte strings.
7388 If FLAG is nil, the filter is given unibyte strings. In this case,
7389 all character code conversion except for end-of-line conversion is
7390 suppressed. */)
7391 (Lisp_Object process, Lisp_Object flag)
7393 CHECK_PROCESS (process);
7395 struct Lisp_Process *p = XPROCESS (process);
7396 if (NILP (flag))
7397 pset_decode_coding_system
7398 (p, raw_text_coding_system (p->decode_coding_system));
7400 /* If the sockets haven't been set up yet, the final setup part of
7401 this will be called asynchronously. */
7402 if (p->infd < 0 || p->outfd < 0)
7403 return Qnil;
7405 setup_process_coding_systems (process);
7407 return Qnil;
7410 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7411 Sprocess_filter_multibyte_p, 1, 1, 0,
7412 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7413 (Lisp_Object process)
7415 CHECK_PROCESS (process);
7416 struct Lisp_Process *p = XPROCESS (process);
7417 if (p->infd < 0)
7418 return Qnil;
7419 struct coding_system *coding = proc_decode_coding_system[p->infd];
7420 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7426 # ifdef HAVE_GPM
7428 void
7429 add_gpm_wait_descriptor (int desc)
7431 add_keyboard_wait_descriptor (desc);
7434 void
7435 delete_gpm_wait_descriptor (int desc)
7437 delete_keyboard_wait_descriptor (desc);
7440 # endif
7442 # ifdef USABLE_SIGIO
7444 /* Return true if *MASK has a bit set
7445 that corresponds to one of the keyboard input descriptors. */
7447 static bool
7448 keyboard_bit_set (fd_set *mask)
7450 int fd;
7452 for (fd = 0; fd <= max_desc; fd++)
7453 if (FD_ISSET (fd, mask)
7454 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7455 == (FOR_READ | KEYBOARD_FD)))
7456 return 1;
7458 return 0;
7460 # endif
7462 #else /* not subprocesses */
7464 /* This is referenced in thread.c:run_thread (which is never actually
7465 called, since threads are not enabled for this configuration. */
7466 void
7467 update_processes_for_thread_death (Lisp_Object dying_thread)
7471 /* Defined in msdos.c. */
7472 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7473 struct timespec *, void *);
7475 /* Implementation of wait_reading_process_output, assuming that there
7476 are no subprocesses. Used only by the MS-DOS build.
7478 Wait for timeout to elapse and/or keyboard input to be available.
7480 TIME_LIMIT is:
7481 timeout in seconds
7482 If negative, gobble data immediately available but don't wait for any.
7484 NSECS is:
7485 an additional duration to wait, measured in nanoseconds
7486 If TIME_LIMIT is zero, then:
7487 If NSECS == 0, there is no limit.
7488 If NSECS > 0, the timeout consists of NSECS only.
7489 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7491 READ_KBD is:
7492 0 to ignore keyboard input, or
7493 1 to return when input is available, or
7494 -1 means caller will actually read the input, so don't throw to
7495 the quit handler.
7497 see full version for other parameters. We know that wait_proc will
7498 always be NULL, since `subprocesses' isn't defined.
7500 DO_DISPLAY means redisplay should be done to show subprocess
7501 output that arrives.
7503 Return -1 signifying we got no output and did not try. */
7506 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7507 bool do_display,
7508 Lisp_Object wait_for_cell,
7509 struct Lisp_Process *wait_proc, int just_wait_proc)
7511 register int nfds;
7512 struct timespec end_time, timeout;
7513 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7515 if (TYPE_MAXIMUM (time_t) < time_limit)
7516 time_limit = TYPE_MAXIMUM (time_t);
7518 if (time_limit < 0 || nsecs < 0)
7519 wait = MINIMUM;
7520 else if (time_limit > 0 || nsecs > 0)
7522 wait = TIMEOUT;
7523 end_time = timespec_add (current_timespec (),
7524 make_timespec (time_limit, nsecs));
7526 else
7527 wait = INFINITY;
7529 /* Turn off periodic alarms (in case they are in use)
7530 and then turn off any other atimers,
7531 because the select emulator uses alarms. */
7532 stop_polling ();
7533 turn_on_atimers (0);
7535 while (1)
7537 bool timeout_reduced_for_timers = false;
7538 fd_set waitchannels;
7539 int xerrno;
7541 /* If calling from keyboard input, do not quit
7542 since we want to return C-g as an input character.
7543 Otherwise, do pending quit if requested. */
7544 if (read_kbd >= 0)
7545 maybe_quit ();
7547 /* Exit now if the cell we're waiting for became non-nil. */
7548 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7549 break;
7551 /* Compute time from now till when time limit is up. */
7552 /* Exit if already run out. */
7553 if (wait == TIMEOUT)
7555 struct timespec now = current_timespec ();
7556 if (timespec_cmp (end_time, now) <= 0)
7557 break;
7558 timeout = timespec_sub (end_time, now);
7560 else
7561 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7563 /* If our caller will not immediately handle keyboard events,
7564 run timer events directly.
7565 (Callers that will immediately read keyboard events
7566 call timer_delay on their own.) */
7567 if (NILP (wait_for_cell))
7569 struct timespec timer_delay;
7573 unsigned old_timers_run = timers_run;
7574 timer_delay = timer_check ();
7575 if (timers_run != old_timers_run && do_display)
7576 /* We must retry, since a timer may have requeued itself
7577 and that could alter the time delay. */
7578 redisplay_preserve_echo_area (14);
7579 else
7580 break;
7582 while (!detect_input_pending ());
7584 /* If there is unread keyboard input, also return. */
7585 if (read_kbd != 0
7586 && requeued_events_pending_p ())
7587 break;
7589 if (timespec_valid_p (timer_delay))
7591 if (timespec_cmp (timer_delay, timeout) < 0)
7593 timeout = timer_delay;
7594 timeout_reduced_for_timers = true;
7599 /* Cause C-g and alarm signals to take immediate action,
7600 and cause input available signals to zero out timeout. */
7601 if (read_kbd < 0)
7602 set_waiting_for_input (&timeout);
7604 /* If a frame has been newly mapped and needs updating,
7605 reprocess its display stuff. */
7606 if (frame_garbaged && do_display)
7608 clear_waiting_for_input ();
7609 redisplay_preserve_echo_area (15);
7610 if (read_kbd < 0)
7611 set_waiting_for_input (&timeout);
7614 /* Wait till there is something to do. */
7615 FD_ZERO (&waitchannels);
7616 if (read_kbd && detect_input_pending ())
7617 nfds = 0;
7618 else
7620 if (read_kbd || !NILP (wait_for_cell))
7621 FD_SET (0, &waitchannels);
7622 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7625 xerrno = errno;
7627 /* Make C-g and alarm signals set flags again. */
7628 clear_waiting_for_input ();
7630 /* If we woke up due to SIGWINCH, actually change size now. */
7631 do_pending_window_change (0);
7633 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7634 /* We waited the full specified time, so return now. */
7635 break;
7637 if (nfds == -1)
7639 /* If the system call was interrupted, then go around the
7640 loop again. */
7641 if (xerrno == EINTR)
7642 FD_ZERO (&waitchannels);
7643 else
7644 report_file_errno ("Failed select", Qnil, xerrno);
7647 /* Check for keyboard input. */
7649 if (read_kbd
7650 && detect_input_pending_run_timers (do_display))
7652 swallow_events (do_display);
7653 if (detect_input_pending_run_timers (do_display))
7654 break;
7657 /* If there is unread keyboard input, also return. */
7658 if (read_kbd
7659 && requeued_events_pending_p ())
7660 break;
7662 /* If wait_for_cell. check for keyboard input
7663 but don't run any timers.
7664 ??? (It seems wrong to me to check for keyboard
7665 input at all when wait_for_cell, but the code
7666 has been this way since July 1994.
7667 Try changing this after version 19.31.) */
7668 if (! NILP (wait_for_cell)
7669 && detect_input_pending ())
7671 swallow_events (do_display);
7672 if (detect_input_pending ())
7673 break;
7676 /* Exit now if the cell we're waiting for became non-nil. */
7677 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7678 break;
7681 start_polling ();
7683 return -1;
7686 #endif /* not subprocesses */
7688 /* The following functions are needed even if async subprocesses are
7689 not supported. Some of them are no-op stubs in that case. */
7691 #ifdef HAVE_TIMERFD
7693 /* Add FD, which is a descriptor returned by timerfd_create,
7694 to the set of non-keyboard input descriptors. */
7696 void
7697 add_timer_wait_descriptor (int fd)
7699 add_read_fd (fd, timerfd_callback, NULL);
7700 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7703 #endif /* HAVE_TIMERFD */
7705 /* If program file NAME starts with /: for quoting a magic
7706 name, remove that, preserving the multibyteness of NAME. */
7708 Lisp_Object
7709 remove_slash_colon (Lisp_Object name)
7711 return
7712 (SREF (name, 0) == '/' && SREF (name, 1) == ':'
7713 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7714 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7715 : name);
7718 /* Add DESC to the set of keyboard input descriptors. */
7720 void
7721 add_keyboard_wait_descriptor (int desc)
7723 #ifdef subprocesses /* Actually means "not MSDOS". */
7724 eassert (desc >= 0 && desc < FD_SETSIZE);
7725 fd_callback_info[desc].flags &= ~PROCESS_FD;
7726 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7727 if (desc > max_desc)
7728 max_desc = desc;
7729 #endif
7732 /* From now on, do not expect DESC to give keyboard input. */
7734 void
7735 delete_keyboard_wait_descriptor (int desc)
7737 #ifdef subprocesses
7738 eassert (desc >= 0 && desc < FD_SETSIZE);
7740 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7742 if (desc == max_desc)
7743 recompute_max_desc ();
7744 #endif
7747 /* Setup coding systems of PROCESS. */
7749 void
7750 setup_process_coding_systems (Lisp_Object process)
7752 #ifdef subprocesses
7753 struct Lisp_Process *p = XPROCESS (process);
7754 int inch = p->infd;
7755 int outch = p->outfd;
7756 Lisp_Object coding_system;
7758 if (inch < 0 || outch < 0)
7759 return;
7761 if (!proc_decode_coding_system[inch])
7762 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7763 coding_system = p->decode_coding_system;
7764 if (EQ (p->filter, Qinternal_default_process_filter)
7765 && BUFFERP (p->buffer))
7767 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7768 coding_system = raw_text_coding_system (coding_system);
7770 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7772 if (!proc_encode_coding_system[outch])
7773 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7774 setup_coding_system (p->encode_coding_system,
7775 proc_encode_coding_system[outch]);
7776 #endif
7779 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7780 doc: /* Return the (or a) live process associated with BUFFER.
7781 BUFFER may be a buffer or the name of one.
7782 Return nil if all processes associated with BUFFER have been
7783 deleted or killed. */)
7784 (register Lisp_Object buffer)
7786 #ifdef subprocesses
7787 register Lisp_Object buf, tail, proc;
7789 if (NILP (buffer)) return Qnil;
7790 buf = Fget_buffer (buffer);
7791 if (NILP (buf)) return Qnil;
7793 FOR_EACH_PROCESS (tail, proc)
7794 if (EQ (XPROCESS (proc)->buffer, buf))
7795 return proc;
7796 #endif /* subprocesses */
7797 return Qnil;
7800 DEFUN ("process-inherit-coding-system-flag",
7801 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7802 1, 1, 0,
7803 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7804 If this flag is t, `buffer-file-coding-system' of the buffer
7805 associated with PROCESS will inherit the coding system used to decode
7806 the process output. */)
7807 (register Lisp_Object process)
7809 #ifdef subprocesses
7810 CHECK_PROCESS (process);
7811 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7812 #else
7813 /* Ignore the argument and return the value of
7814 inherit-process-coding-system. */
7815 return inherit_process_coding_system ? Qt : Qnil;
7816 #endif
7819 /* Kill all processes associated with `buffer'.
7820 If `buffer' is nil, kill all processes. */
7822 void
7823 kill_buffer_processes (Lisp_Object buffer)
7825 #ifdef subprocesses
7826 Lisp_Object tail, proc;
7828 FOR_EACH_PROCESS (tail, proc)
7829 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7831 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7832 Fdelete_process (proc);
7833 else if (XPROCESS (proc)->infd >= 0)
7834 process_send_signal (proc, SIGHUP, Qnil, 1);
7836 #else /* subprocesses */
7837 /* Since we have no subprocesses, this does nothing. */
7838 #endif /* subprocesses */
7841 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7842 Swaiting_for_user_input_p, 0, 0, 0,
7843 doc: /* Return non-nil if Emacs is waiting for input from the user.
7844 This is intended for use by asynchronous process output filters and sentinels. */)
7845 (void)
7847 #ifdef subprocesses
7848 return (waiting_for_user_input_p ? Qt : Qnil);
7849 #else
7850 return Qnil;
7851 #endif
7854 /* Stop reading input from keyboard sources. */
7856 void
7857 hold_keyboard_input (void)
7859 kbd_is_on_hold = 1;
7862 /* Resume reading input from keyboard sources. */
7864 void
7865 unhold_keyboard_input (void)
7867 kbd_is_on_hold = 0;
7870 /* Return true if keyboard input is on hold, zero otherwise. */
7872 bool
7873 kbd_on_hold_p (void)
7875 return kbd_is_on_hold;
7879 /* Enumeration of and access to system processes a-la ps(1). */
7881 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7882 0, 0, 0,
7883 doc: /* Return a list of numerical process IDs of all running processes.
7884 If this functionality is unsupported, return nil.
7886 See `process-attributes' for getting attributes of a process given its ID. */)
7887 (void)
7889 return list_system_processes ();
7892 DEFUN ("process-attributes", Fprocess_attributes,
7893 Sprocess_attributes, 1, 1, 0,
7894 doc: /* Return attributes of the process given by its PID, a number.
7896 Value is an alist where each element is a cons cell of the form
7898 (KEY . VALUE)
7900 If this functionality is unsupported, the value is nil.
7902 See `list-system-processes' for getting a list of all process IDs.
7904 The KEYs of the attributes that this function may return are listed
7905 below, together with the type of the associated VALUE (in parentheses).
7906 Not all platforms support all of these attributes; unsupported
7907 attributes will not appear in the returned alist.
7908 Unless explicitly indicated otherwise, numbers can have either
7909 integer or floating point values.
7911 euid -- Effective user User ID of the process (number)
7912 user -- User name corresponding to euid (string)
7913 egid -- Effective user Group ID of the process (number)
7914 group -- Group name corresponding to egid (string)
7915 comm -- Command name (executable name only) (string)
7916 state -- Process state code, such as "S", "R", or "T" (string)
7917 ppid -- Parent process ID (number)
7918 pgrp -- Process group ID (number)
7919 sess -- Session ID, i.e. process ID of session leader (number)
7920 ttname -- Controlling tty name (string)
7921 tpgid -- ID of foreground process group on the process's tty (number)
7922 minflt -- number of minor page faults (number)
7923 majflt -- number of major page faults (number)
7924 cminflt -- cumulative number of minor page faults (number)
7925 cmajflt -- cumulative number of major page faults (number)
7926 utime -- user time used by the process, in (current-time) format,
7927 which is a list of integers (HIGH LOW USEC PSEC)
7928 stime -- system time used by the process (current-time)
7929 time -- sum of utime and stime (current-time)
7930 cutime -- user time used by the process and its children (current-time)
7931 cstime -- system time used by the process and its children (current-time)
7932 ctime -- sum of cutime and cstime (current-time)
7933 pri -- priority of the process (number)
7934 nice -- nice value of the process (number)
7935 thcount -- process thread count (number)
7936 start -- time the process started (current-time)
7937 vsize -- virtual memory size of the process in KB's (number)
7938 rss -- resident set size of the process in KB's (number)
7939 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7940 pcpu -- percents of CPU time used by the process (floating-point number)
7941 pmem -- percents of total physical memory used by process's resident set
7942 (floating-point number)
7943 args -- command line which invoked the process (string). */)
7944 ( Lisp_Object pid)
7946 return system_process_attributes (pid);
7949 #ifdef subprocesses
7950 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7951 Invoke this after init_process_emacs, and after glib and/or GNUstep
7952 futz with the SIGCHLD handler, but before Emacs forks any children.
7953 This function's caller should block SIGCHLD. */
7955 void
7956 catch_child_signal (void)
7958 struct sigaction action, old_action;
7959 sigset_t oldset;
7960 emacs_sigaction_init (&action, deliver_child_signal);
7961 block_child_signal (&oldset);
7962 sigaction (SIGCHLD, &action, &old_action);
7963 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7964 || ! (old_action.sa_flags & SA_SIGINFO));
7966 if (old_action.sa_handler != deliver_child_signal)
7967 lib_child_handler
7968 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7969 ? dummy_handler
7970 : old_action.sa_handler);
7971 unblock_child_signal (&oldset);
7973 #endif /* subprocesses */
7975 /* Limit the number of open files to the value it had at startup. */
7977 void
7978 restore_nofile_limit (void)
7980 #ifdef HAVE_SETRLIMIT
7981 if (FD_SETSIZE < nofile_limit.rlim_cur)
7982 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7983 #endif
7987 /* This is not called "init_process" because that is the name of a
7988 Mach system call, so it would cause problems on Darwin systems. */
7989 void
7990 init_process_emacs (int sockfd)
7992 #ifdef subprocesses
7993 int i;
7995 inhibit_sentinels = 0;
7997 #ifndef CANNOT_DUMP
7998 if (! noninteractive || initialized)
7999 #endif
8001 #if defined HAVE_GLIB && !defined WINDOWSNT
8002 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8003 this should always fail, but is enough to initialize glib's
8004 private SIGCHLD handler, allowing catch_child_signal to copy
8005 it into lib_child_handler. */
8006 g_source_unref (g_child_watch_source_new (getpid ()));
8007 #endif
8008 catch_child_signal ();
8011 #ifdef HAVE_SETRLIMIT
8012 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8013 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
8014 nofile_limit.rlim_cur = 0;
8015 else if (FD_SETSIZE < nofile_limit.rlim_cur)
8017 struct rlimit rlim = nofile_limit;
8018 rlim.rlim_cur = FD_SETSIZE;
8019 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
8020 nofile_limit.rlim_cur = 0;
8022 #endif
8024 external_sock_fd = sockfd;
8025 max_desc = -1;
8026 memset (fd_callback_info, 0, sizeof (fd_callback_info));
8028 num_pending_connects = 0;
8030 process_output_delay_count = 0;
8031 process_output_skip = 0;
8033 /* Don't do this, it caused infinite select loops. The display
8034 method should call add_keyboard_wait_descriptor on stdin if it
8035 needs that. */
8036 #if 0
8037 FD_SET (0, &input_wait_mask);
8038 #endif
8040 Vprocess_alist = Qnil;
8041 deleted_pid_list = Qnil;
8042 for (i = 0; i < FD_SETSIZE; i++)
8044 chan_process[i] = Qnil;
8045 proc_buffered_char[i] = -1;
8047 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
8048 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
8049 #ifdef DATAGRAM_SOCKETS
8050 memset (datagram_address, 0, sizeof datagram_address);
8051 #endif
8053 #if defined (DARWIN_OS)
8054 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8055 processes. As such, we only change the default value. */
8056 if (initialized)
8058 char const *release = (STRINGP (Voperating_system_release)
8059 ? SSDATA (Voperating_system_release)
8060 : 0);
8061 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
8062 Vprocess_connection_type = Qnil;
8065 #endif
8066 #endif /* subprocesses */
8067 kbd_is_on_hold = 0;
8070 void
8071 syms_of_process (void)
8073 #ifdef subprocesses
8075 DEFSYM (Qprocessp, "processp");
8076 DEFSYM (Qrun, "run");
8077 DEFSYM (Qstop, "stop");
8078 DEFSYM (Qsignal, "signal");
8080 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8081 here again. */
8083 DEFSYM (Qopen, "open");
8084 DEFSYM (Qclosed, "closed");
8085 DEFSYM (Qconnect, "connect");
8086 DEFSYM (Qfailed, "failed");
8087 DEFSYM (Qlisten, "listen");
8088 DEFSYM (Qlocal, "local");
8089 DEFSYM (Qipv4, "ipv4");
8090 #ifdef AF_INET6
8091 DEFSYM (Qipv6, "ipv6");
8092 #endif
8093 DEFSYM (Qdatagram, "datagram");
8094 DEFSYM (Qseqpacket, "seqpacket");
8096 DEFSYM (QCport, ":port");
8097 DEFSYM (QCspeed, ":speed");
8098 DEFSYM (QCprocess, ":process");
8100 DEFSYM (QCbytesize, ":bytesize");
8101 DEFSYM (QCstopbits, ":stopbits");
8102 DEFSYM (QCparity, ":parity");
8103 DEFSYM (Qodd, "odd");
8104 DEFSYM (Qeven, "even");
8105 DEFSYM (QCflowcontrol, ":flowcontrol");
8106 DEFSYM (Qhw, "hw");
8107 DEFSYM (Qsw, "sw");
8108 DEFSYM (QCsummary, ":summary");
8110 DEFSYM (Qreal, "real");
8111 DEFSYM (Qnetwork, "network");
8112 DEFSYM (Qserial, "serial");
8113 DEFSYM (QCbuffer, ":buffer");
8114 DEFSYM (QChost, ":host");
8115 DEFSYM (QCservice, ":service");
8116 DEFSYM (QClocal, ":local");
8117 DEFSYM (QCremote, ":remote");
8118 DEFSYM (QCcoding, ":coding");
8119 DEFSYM (QCserver, ":server");
8120 DEFSYM (QCnowait, ":nowait");
8121 DEFSYM (QCsentinel, ":sentinel");
8122 DEFSYM (QCuse_external_socket, ":use-external-socket");
8123 DEFSYM (QCtls_parameters, ":tls-parameters");
8124 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8125 DEFSYM (QClog, ":log");
8126 DEFSYM (QCnoquery, ":noquery");
8127 DEFSYM (QCstop, ":stop");
8128 DEFSYM (QCplist, ":plist");
8129 DEFSYM (QCcommand, ":command");
8130 DEFSYM (QCconnection_type, ":connection-type");
8131 DEFSYM (QCstderr, ":stderr");
8132 DEFSYM (Qpty, "pty");
8133 DEFSYM (Qpipe, "pipe");
8135 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8137 staticpro (&Vprocess_alist);
8138 staticpro (&deleted_pid_list);
8140 #endif /* subprocesses */
8142 DEFSYM (QCname, ":name");
8143 DEFSYM (QCtype, ":type");
8145 DEFSYM (Qeuid, "euid");
8146 DEFSYM (Qegid, "egid");
8147 DEFSYM (Quser, "user");
8148 DEFSYM (Qgroup, "group");
8149 DEFSYM (Qcomm, "comm");
8150 DEFSYM (Qstate, "state");
8151 DEFSYM (Qppid, "ppid");
8152 DEFSYM (Qpgrp, "pgrp");
8153 DEFSYM (Qsess, "sess");
8154 DEFSYM (Qttname, "ttname");
8155 DEFSYM (Qtpgid, "tpgid");
8156 DEFSYM (Qminflt, "minflt");
8157 DEFSYM (Qmajflt, "majflt");
8158 DEFSYM (Qcminflt, "cminflt");
8159 DEFSYM (Qcmajflt, "cmajflt");
8160 DEFSYM (Qutime, "utime");
8161 DEFSYM (Qstime, "stime");
8162 DEFSYM (Qtime, "time");
8163 DEFSYM (Qcutime, "cutime");
8164 DEFSYM (Qcstime, "cstime");
8165 DEFSYM (Qctime, "ctime");
8166 #ifdef subprocesses
8167 DEFSYM (Qinternal_default_process_sentinel,
8168 "internal-default-process-sentinel");
8169 DEFSYM (Qinternal_default_process_filter,
8170 "internal-default-process-filter");
8171 #endif
8172 DEFSYM (Qpri, "pri");
8173 DEFSYM (Qnice, "nice");
8174 DEFSYM (Qthcount, "thcount");
8175 DEFSYM (Qstart, "start");
8176 DEFSYM (Qvsize, "vsize");
8177 DEFSYM (Qrss, "rss");
8178 DEFSYM (Qetime, "etime");
8179 DEFSYM (Qpcpu, "pcpu");
8180 DEFSYM (Qpmem, "pmem");
8181 DEFSYM (Qargs, "args");
8183 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8184 doc: /* Non-nil means delete processes immediately when they exit.
8185 A value of nil means don't delete them until `list-processes' is run. */);
8187 delete_exited_processes = 1;
8189 #ifdef subprocesses
8190 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8191 doc: /* Control type of device used to communicate with subprocesses.
8192 Values are nil to use a pipe, or t or `pty' to use a pty.
8193 The value has no effect if the system has no ptys or if all ptys are busy:
8194 then a pipe is used in any case.
8195 The value takes effect when `start-process' is called. */);
8196 Vprocess_connection_type = Qt;
8198 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8199 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8200 On some systems, when Emacs reads the output from a subprocess, the output data
8201 is read in very small blocks, potentially resulting in very poor performance.
8202 This behavior can be remedied to some extent by setting this variable to a
8203 non-nil value, as it will automatically delay reading from such processes, to
8204 allow them to produce more output before Emacs tries to read it.
8205 If the value is t, the delay is reset after each write to the process; any other
8206 non-nil value means that the delay is not reset on write.
8207 The variable takes effect when `start-process' is called. */);
8208 Vprocess_adaptive_read_buffering = Qt;
8210 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions,
8211 doc: /* List of functions to be called for `interrupt-process'.
8212 The arguments of the functions are the same as for `interrupt-process'.
8213 These functions are called in the order of the list, until one of them
8214 returns non-`nil'. */);
8215 Vinterrupt_process_functions = list1 (Qinternal_default_interrupt_process);
8217 DEFSYM (Qinternal_default_interrupt_process,
8218 "internal-default-interrupt-process");
8219 DEFSYM (Qinterrupt_process_functions, "interrupt-process-functions");
8221 defsubr (&Sprocessp);
8222 defsubr (&Sget_process);
8223 defsubr (&Sdelete_process);
8224 defsubr (&Sprocess_status);
8225 defsubr (&Sprocess_exit_status);
8226 defsubr (&Sprocess_id);
8227 defsubr (&Sprocess_name);
8228 defsubr (&Sprocess_tty_name);
8229 defsubr (&Sprocess_command);
8230 defsubr (&Sset_process_buffer);
8231 defsubr (&Sprocess_buffer);
8232 defsubr (&Sprocess_mark);
8233 defsubr (&Sset_process_filter);
8234 defsubr (&Sprocess_filter);
8235 defsubr (&Sset_process_sentinel);
8236 defsubr (&Sprocess_sentinel);
8237 defsubr (&Sset_process_thread);
8238 defsubr (&Sprocess_thread);
8239 defsubr (&Sset_process_window_size);
8240 defsubr (&Sset_process_inherit_coding_system_flag);
8241 defsubr (&Sset_process_query_on_exit_flag);
8242 defsubr (&Sprocess_query_on_exit_flag);
8243 defsubr (&Sprocess_contact);
8244 defsubr (&Sprocess_plist);
8245 defsubr (&Sset_process_plist);
8246 defsubr (&Sprocess_list);
8247 defsubr (&Smake_process);
8248 defsubr (&Smake_pipe_process);
8249 defsubr (&Sserial_process_configure);
8250 defsubr (&Smake_serial_process);
8251 defsubr (&Sset_network_process_option);
8252 defsubr (&Smake_network_process);
8253 defsubr (&Sformat_network_address);
8254 defsubr (&Snetwork_interface_list);
8255 defsubr (&Snetwork_interface_info);
8256 #ifdef DATAGRAM_SOCKETS
8257 defsubr (&Sprocess_datagram_address);
8258 defsubr (&Sset_process_datagram_address);
8259 #endif
8260 defsubr (&Saccept_process_output);
8261 defsubr (&Sprocess_send_region);
8262 defsubr (&Sprocess_send_string);
8263 defsubr (&Sinternal_default_interrupt_process);
8264 defsubr (&Sinterrupt_process);
8265 defsubr (&Skill_process);
8266 defsubr (&Squit_process);
8267 defsubr (&Sstop_process);
8268 defsubr (&Scontinue_process);
8269 defsubr (&Sprocess_running_child_p);
8270 defsubr (&Sprocess_send_eof);
8271 defsubr (&Ssignal_process);
8272 defsubr (&Swaiting_for_user_input_p);
8273 defsubr (&Sprocess_type);
8274 defsubr (&Sinternal_default_process_sentinel);
8275 defsubr (&Sinternal_default_process_filter);
8276 defsubr (&Sset_process_coding_system);
8277 defsubr (&Sprocess_coding_system);
8278 defsubr (&Sset_process_filter_multibyte);
8279 defsubr (&Sprocess_filter_multibyte_p);
8282 Lisp_Object subfeatures = Qnil;
8283 const struct socket_options *sopt;
8285 #define ADD_SUBFEATURE(key, val) \
8286 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8288 ADD_SUBFEATURE (QCnowait, Qt);
8289 #ifdef DATAGRAM_SOCKETS
8290 ADD_SUBFEATURE (QCtype, Qdatagram);
8291 #endif
8292 #ifdef HAVE_SEQPACKET
8293 ADD_SUBFEATURE (QCtype, Qseqpacket);
8294 #endif
8295 #ifdef HAVE_LOCAL_SOCKETS
8296 ADD_SUBFEATURE (QCfamily, Qlocal);
8297 #endif
8298 ADD_SUBFEATURE (QCfamily, Qipv4);
8299 #ifdef AF_INET6
8300 ADD_SUBFEATURE (QCfamily, Qipv6);
8301 #endif
8302 #ifdef HAVE_GETSOCKNAME
8303 ADD_SUBFEATURE (QCservice, Qt);
8304 #endif
8305 ADD_SUBFEATURE (QCserver, Qt);
8307 for (sopt = socket_options; sopt->name; sopt++)
8308 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8310 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8313 #endif /* subprocesses */
8315 defsubr (&Sget_buffer_process);
8316 defsubr (&Sprocess_inherit_coding_system_flag);
8317 defsubr (&Slist_system_processes);
8318 defsubr (&Sprocess_attributes);