CC Mode: Fix the fontification of a spuriously recognised enum member.
[emacs.git] / src / process.c
blobc0c52c232b93868d6598c0f8fca7ebd63742939b
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 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 <http://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 #ifdef HAVE_SETRLIMIT
44 # include <sys/resource.h>
46 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
47 NOFILE_LIMIT is the initial limit on the number of open files,
48 which should be restored in child processes. */
49 static struct rlimit nofile_limit;
50 #endif
52 /* Are local (unix) sockets supported? */
53 #if defined (HAVE_SYS_UN_H)
54 #if !defined (AF_LOCAL) && defined (AF_UNIX)
55 #define AF_LOCAL AF_UNIX
56 #endif
57 #ifdef AF_LOCAL
58 #define HAVE_LOCAL_SOCKETS
59 #include <sys/un.h>
60 #endif
61 #endif
63 #include <sys/ioctl.h>
64 #if defined (HAVE_NET_IF_H)
65 #include <net/if.h>
66 #endif /* HAVE_NET_IF_H */
68 #if defined (HAVE_IFADDRS_H)
69 /* Must be after net/if.h */
70 #include <ifaddrs.h>
72 /* We only use structs from this header when we use getifaddrs. */
73 #if defined (HAVE_NET_IF_DL_H)
74 #include <net/if_dl.h>
75 #endif
77 #endif
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
83 #ifdef USG5_4
84 # include <sys/stream.h>
85 # include <sys/stropts.h>
86 #endif
88 #ifdef HAVE_UTIL_H
89 #include <util.h>
90 #endif
92 #ifdef HAVE_PTY_H
93 #include <pty.h>
94 #endif
96 #include <c-ctype.h>
97 #include <flexmember.h>
98 #include <sig2str.h>
99 #include <verify.h>
101 #endif /* subprocesses */
103 #include "systime.h"
104 #include "systty.h"
106 #include "window.h"
107 #include "character.h"
108 #include "buffer.h"
109 #include "coding.h"
110 #include "process.h"
111 #include "frame.h"
112 #include "termopts.h"
113 #include "keyboard.h"
114 #include "blockinput.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
127 #ifdef HAVE_GLIB
128 #include "xgselect.h"
129 #ifndef WINDOWSNT
130 #include <glib.h>
131 #endif
132 #endif
134 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
135 /* This is 0.1s in nanoseconds. */
136 #define ASYNC_RETRY_NSEC 100000000
137 #endif
139 #ifdef WINDOWSNT
140 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
141 const struct timespec *, const sigset_t *);
142 #endif
144 /* Work around GCC 4.3.0 bug with strict overflow checking; see
145 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
146 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
147 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
148 # pragma GCC diagnostic ignored "-Wstrict-overflow"
149 #endif
151 /* True if keyboard input is on hold, zero otherwise. */
153 static bool kbd_is_on_hold;
155 /* Nonzero means don't run process sentinels. This is used
156 when exiting. */
157 bool inhibit_sentinels;
159 #ifdef subprocesses
161 #ifndef SOCK_CLOEXEC
162 # define SOCK_CLOEXEC 0
163 #endif
164 #ifndef SOCK_NONBLOCK
165 # define SOCK_NONBLOCK 0
166 #endif
168 /* True if ERRNUM represents an error where the system call would
169 block if a blocking variant were used. */
170 static bool
171 would_block (int errnum)
173 #ifdef EWOULDBLOCK
174 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
175 return true;
176 #endif
177 return errnum == EAGAIN;
180 #ifndef HAVE_ACCEPT4
182 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
184 static int
185 close_on_exec (int fd)
187 if (0 <= fd)
188 fcntl (fd, F_SETFD, FD_CLOEXEC);
189 return fd;
192 # undef accept4
193 # define accept4(sockfd, addr, addrlen, flags) \
194 process_accept4 (sockfd, addr, addrlen, flags)
195 static int
196 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
198 return close_on_exec (accept (sockfd, addr, addrlen));
201 static int
202 process_socket (int domain, int type, int protocol)
204 return close_on_exec (socket (domain, type, protocol));
206 # undef socket
207 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
208 #endif
210 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
211 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
212 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
213 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
214 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
215 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick;
222 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
223 this system. We need to read full packets, so we need a
224 "non-destructive" select. So we require either native select,
225 or emulation of select using FIONREAD. */
227 #ifndef BROKEN_DATAGRAM_SOCKETS
228 # if defined HAVE_SELECT || defined USABLE_FIONREAD
229 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
230 # define DATAGRAM_SOCKETS
231 # endif
232 # endif
233 #endif
235 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
236 # define HAVE_SEQPACKET
237 #endif
239 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
240 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
241 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
243 /* Number of processes which have a non-zero read_output_delay,
244 and therefore might be delayed for adaptive read buffering. */
246 static int process_output_delay_count;
248 /* True if any process has non-nil read_output_skip. */
250 static bool process_output_skip;
252 static void start_process_unwind (Lisp_Object);
253 static void create_process (Lisp_Object, char **, Lisp_Object);
254 #ifdef USABLE_SIGIO
255 static bool keyboard_bit_set (fd_set *);
256 #endif
257 static void deactivate_process (Lisp_Object);
258 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
259 static int read_process_output (Lisp_Object, int);
260 static void create_pty (Lisp_Object);
261 static void exec_sentinel (Lisp_Object, Lisp_Object);
263 /* Number of bits set in connect_wait_mask. */
264 static int num_pending_connects;
266 /* The largest descriptor currently in use; -1 if none. */
267 static int max_desc;
269 /* Set the external socket descriptor for Emacs to use when
270 `make-network-process' is called with a non-nil
271 `:use-external-socket' option. The value should be either -1, or
272 the file descriptor of a socket that is already bound. */
273 static int external_sock_fd;
275 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
276 static Lisp_Object chan_process[FD_SETSIZE];
277 static void wait_for_socket_fds (Lisp_Object, char const *);
279 /* Alist of elements (NAME . PROCESS). */
280 static Lisp_Object Vprocess_alist;
282 /* Buffered-ahead input char from process, indexed by channel.
283 -1 means empty (no char is buffered).
284 Used on sys V where the only way to tell if there is any
285 output from the process is to read at least one char.
286 Always -1 on systems that support FIONREAD. */
288 static int proc_buffered_char[FD_SETSIZE];
290 /* Table of `struct coding-system' for each process. */
291 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
292 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
294 #ifdef DATAGRAM_SOCKETS
295 /* Table of `partner address' for datagram sockets. */
296 static struct sockaddr_and_len {
297 struct sockaddr *sa;
298 ptrdiff_t len;
299 } datagram_address[FD_SETSIZE];
300 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
301 #define DATAGRAM_CONN_P(proc) \
302 (PROCESSP (proc) && \
303 XPROCESS (proc)->infd >= 0 && \
304 datagram_address[XPROCESS (proc)->infd].sa != 0)
305 #else
306 #define DATAGRAM_CONN_P(proc) (0)
307 #endif
309 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
310 a `for' loop which iterates over processes from Vprocess_alist. */
312 #define FOR_EACH_PROCESS(list_var, proc_var) \
313 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
315 /* These setters are used only in this file, so they can be private. */
316 static void
317 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
319 p->buffer = val;
321 static void
322 pset_command (struct Lisp_Process *p, Lisp_Object val)
324 p->command = val;
326 static void
327 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
329 p->decode_coding_system = val;
331 static void
332 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
334 p->decoding_buf = val;
336 static void
337 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
339 p->encode_coding_system = val;
341 static void
342 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
344 p->encoding_buf = val;
346 static void
347 pset_filter (struct Lisp_Process *p, Lisp_Object val)
349 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
351 static void
352 pset_log (struct Lisp_Process *p, Lisp_Object val)
354 p->log = val;
356 static void
357 pset_mark (struct Lisp_Process *p, Lisp_Object val)
359 p->mark = val;
361 static void
362 pset_thread (struct Lisp_Process *p, Lisp_Object val)
364 p->thread = val;
366 static void
367 pset_name (struct Lisp_Process *p, Lisp_Object val)
369 p->name = val;
371 static void
372 pset_plist (struct Lisp_Process *p, Lisp_Object val)
374 p->plist = val;
376 static void
377 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
379 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
381 static void
382 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
384 p->tty_name = val;
386 static void
387 pset_type (struct Lisp_Process *p, Lisp_Object val)
389 p->type = val;
391 static void
392 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
394 p->write_queue = val;
396 static void
397 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
399 p->stderrproc = val;
403 static Lisp_Object
404 make_lisp_proc (struct Lisp_Process *p)
406 return make_lisp_ptr (p, Lisp_Vectorlike);
409 enum fd_bits
411 /* Read from file descriptor. */
412 FOR_READ = 1,
413 /* Write to file descriptor. */
414 FOR_WRITE = 2,
415 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
416 set. */
417 KEYBOARD_FD = 4,
418 /* This descriptor refers to a process. */
419 PROCESS_FD = 8,
420 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
421 NON_BLOCKING_CONNECT_FD = 16
424 static struct fd_callback_data
426 fd_callback func;
427 void *data;
428 /* Flags from enum fd_bits. */
429 int flags;
430 /* If this fd is locked to a certain thread, this points to it.
431 Otherwise, this is NULL. If an fd is locked to a thread, then
432 only that thread is permitted to wait on it. */
433 struct thread_state *thread;
434 /* If this fd is currently being selected on by a thread, this
435 points to the thread. Otherwise it is NULL. */
436 struct thread_state *waiting_thread;
437 } fd_callback_info[FD_SETSIZE];
440 /* Add a file descriptor FD to be monitored for when read is possible.
441 When read is possible, call FUNC with argument DATA. */
443 void
444 add_read_fd (int fd, fd_callback func, void *data)
446 add_keyboard_wait_descriptor (fd);
448 fd_callback_info[fd].func = func;
449 fd_callback_info[fd].data = data;
452 static void
453 add_non_keyboard_read_fd (int fd)
455 eassert (fd >= 0 && fd < FD_SETSIZE);
456 eassert (fd_callback_info[fd].func == NULL);
458 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
459 fd_callback_info[fd].flags |= FOR_READ;
460 if (fd > max_desc)
461 max_desc = fd;
464 static void
465 add_process_read_fd (int fd)
467 add_non_keyboard_read_fd (fd);
468 fd_callback_info[fd].flags |= PROCESS_FD;
471 /* Stop monitoring file descriptor FD for when read is possible. */
473 void
474 delete_read_fd (int fd)
476 delete_keyboard_wait_descriptor (fd);
478 if (fd_callback_info[fd].flags == 0)
480 fd_callback_info[fd].func = 0;
481 fd_callback_info[fd].data = 0;
485 /* Add a file descriptor FD to be monitored for when write is possible.
486 When write is possible, call FUNC with argument DATA. */
488 void
489 add_write_fd (int fd, fd_callback func, void *data)
491 eassert (fd >= 0 && fd < FD_SETSIZE);
493 fd_callback_info[fd].func = func;
494 fd_callback_info[fd].data = data;
495 fd_callback_info[fd].flags |= FOR_WRITE;
496 if (fd > max_desc)
497 max_desc = fd;
500 static void
501 add_non_blocking_write_fd (int fd)
503 eassert (fd >= 0 && fd < FD_SETSIZE);
504 eassert (fd_callback_info[fd].func == NULL);
506 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
507 if (fd > max_desc)
508 max_desc = fd;
509 ++num_pending_connects;
512 static void
513 recompute_max_desc (void)
515 int fd;
517 for (fd = max_desc; fd >= 0; --fd)
519 if (fd_callback_info[fd].flags != 0)
521 max_desc = fd;
522 break;
527 /* Stop monitoring file descriptor FD for when write is possible. */
529 void
530 delete_write_fd (int fd)
532 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
534 if (--num_pending_connects < 0)
535 emacs_abort ();
537 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
538 if (fd_callback_info[fd].flags == 0)
540 fd_callback_info[fd].func = 0;
541 fd_callback_info[fd].data = 0;
543 if (fd == max_desc)
544 recompute_max_desc ();
548 static void
549 compute_input_wait_mask (fd_set *mask)
551 int fd;
553 FD_ZERO (mask);
554 for (fd = 0; fd <= max_desc; ++fd)
556 if (fd_callback_info[fd].thread != NULL
557 && fd_callback_info[fd].thread != current_thread)
558 continue;
559 if (fd_callback_info[fd].waiting_thread != NULL
560 && fd_callback_info[fd].waiting_thread != current_thread)
561 continue;
562 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
564 FD_SET (fd, mask);
565 fd_callback_info[fd].waiting_thread = current_thread;
570 static void
571 compute_non_process_wait_mask (fd_set *mask)
573 int fd;
575 FD_ZERO (mask);
576 for (fd = 0; fd <= max_desc; ++fd)
578 if (fd_callback_info[fd].thread != NULL
579 && fd_callback_info[fd].thread != current_thread)
580 continue;
581 if (fd_callback_info[fd].waiting_thread != NULL
582 && fd_callback_info[fd].waiting_thread != current_thread)
583 continue;
584 if ((fd_callback_info[fd].flags & FOR_READ) != 0
585 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
587 FD_SET (fd, mask);
588 fd_callback_info[fd].waiting_thread = current_thread;
593 static void
594 compute_non_keyboard_wait_mask (fd_set *mask)
596 int fd;
598 FD_ZERO (mask);
599 for (fd = 0; fd <= max_desc; ++fd)
601 if (fd_callback_info[fd].thread != NULL
602 && fd_callback_info[fd].thread != current_thread)
603 continue;
604 if (fd_callback_info[fd].waiting_thread != NULL
605 && fd_callback_info[fd].waiting_thread != current_thread)
606 continue;
607 if ((fd_callback_info[fd].flags & FOR_READ) != 0
608 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
610 FD_SET (fd, mask);
611 fd_callback_info[fd].waiting_thread = current_thread;
616 static void
617 compute_write_mask (fd_set *mask)
619 int fd;
621 FD_ZERO (mask);
622 for (fd = 0; fd <= max_desc; ++fd)
624 if (fd_callback_info[fd].thread != NULL
625 && fd_callback_info[fd].thread != current_thread)
626 continue;
627 if (fd_callback_info[fd].waiting_thread != NULL
628 && fd_callback_info[fd].waiting_thread != current_thread)
629 continue;
630 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
632 FD_SET (fd, mask);
633 fd_callback_info[fd].waiting_thread = current_thread;
638 static void
639 clear_waiting_thread_info (void)
641 int fd;
643 for (fd = 0; fd <= max_desc; ++fd)
645 if (fd_callback_info[fd].waiting_thread == current_thread)
646 fd_callback_info[fd].waiting_thread = NULL;
651 /* Compute the Lisp form of the process status, p->status, from
652 the numeric status that was returned by `wait'. */
654 static Lisp_Object status_convert (int);
656 static void
657 update_status (struct Lisp_Process *p)
659 eassert (p->raw_status_new);
660 pset_status (p, status_convert (p->raw_status));
661 p->raw_status_new = 0;
664 /* Convert a process status word in Unix format to
665 the list that we use internally. */
667 static Lisp_Object
668 status_convert (int w)
670 if (WIFSTOPPED (w))
671 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
672 else if (WIFEXITED (w))
673 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
674 WCOREDUMP (w) ? Qt : Qnil));
675 else if (WIFSIGNALED (w))
676 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
677 WCOREDUMP (w) ? Qt : Qnil));
678 else
679 return Qrun;
682 /* True if STATUS is that of a process attempting connection. */
684 static bool
685 connecting_status (Lisp_Object status)
687 return CONSP (status) && EQ (XCAR (status), Qconnect);
690 /* Given a status-list, extract the three pieces of information
691 and store them individually through the three pointers. */
693 static void
694 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
695 bool *coredump)
697 Lisp_Object tem;
699 if (connecting_status (l))
700 l = XCAR (l);
702 if (SYMBOLP (l))
704 *symbol = l;
705 *code = make_number (0);
706 *coredump = 0;
708 else
710 *symbol = XCAR (l);
711 tem = XCDR (l);
712 *code = XCAR (tem);
713 tem = XCDR (tem);
714 *coredump = !NILP (tem);
718 /* Return a string describing a process status list. */
720 static Lisp_Object
721 status_message (struct Lisp_Process *p)
723 Lisp_Object status = p->status;
724 Lisp_Object symbol, code;
725 bool coredump;
726 Lisp_Object string;
728 decode_status (status, &symbol, &code, &coredump);
730 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
732 char const *signame;
733 synchronize_system_messages_locale ();
734 signame = strsignal (XFASTINT (code));
735 if (signame == 0)
736 string = build_string ("unknown");
737 else
739 int c1, c2;
741 string = build_unibyte_string (signame);
742 if (! NILP (Vlocale_coding_system))
743 string = (code_convert_string_norecord
744 (string, Vlocale_coding_system, 0));
745 c1 = STRING_CHAR (SDATA (string));
746 c2 = downcase (c1);
747 if (c1 != c2)
748 Faset (string, make_number (0), make_number (c2));
750 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
751 return concat2 (string, suffix);
753 else if (EQ (symbol, Qexit))
755 if (NETCONN1_P (p))
756 return build_string (XFASTINT (code) == 0
757 ? "deleted\n"
758 : "connection broken by remote peer\n");
759 if (XFASTINT (code) == 0)
760 return build_string ("finished\n");
761 AUTO_STRING (prefix, "exited abnormally with code ");
762 string = Fnumber_to_string (code);
763 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
764 return concat3 (prefix, string, suffix);
766 else if (EQ (symbol, Qfailed))
768 AUTO_STRING (format, "failed with code %s\n");
769 return CALLN (Fformat, format, code);
771 else
772 return Fcopy_sequence (Fsymbol_name (symbol));
775 enum { PTY_NAME_SIZE = 24 };
777 /* Open an available pty, returning a file descriptor.
778 Store into PTY_NAME the file name of the terminal corresponding to the pty.
779 Return -1 on failure. */
781 static int
782 allocate_pty (char pty_name[PTY_NAME_SIZE])
784 #ifdef HAVE_PTYS
785 int fd;
787 #ifdef PTY_ITERATION
788 PTY_ITERATION
789 #else
790 register int c, i;
791 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
792 for (i = 0; i < 16; i++)
793 #endif
795 #ifdef PTY_NAME_SPRINTF
796 PTY_NAME_SPRINTF
797 #else
798 sprintf (pty_name, "/dev/pty%c%x", c, i);
799 #endif /* no PTY_NAME_SPRINTF */
801 #ifdef PTY_OPEN
802 PTY_OPEN;
803 #else /* no PTY_OPEN */
804 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
805 #endif /* no PTY_OPEN */
807 if (fd >= 0)
809 #ifdef PTY_TTY_NAME_SPRINTF
810 PTY_TTY_NAME_SPRINTF
811 #else
812 sprintf (pty_name, "/dev/tty%c%x", c, i);
813 #endif /* no PTY_TTY_NAME_SPRINTF */
815 /* Set FD's close-on-exec flag. This is needed even if
816 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
817 doesn't require support for that combination.
818 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
819 doesn't work if the close-on-exec flag is set (Bug#20555).
820 Multithreaded platforms where posix_openpt ignores
821 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
822 have a race condition between the PTY_OPEN and here. */
823 fcntl (fd, F_SETFD, FD_CLOEXEC);
825 /* Check to make certain that both sides are available.
826 This avoids a nasty yet stupid bug in rlogins. */
827 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
829 emacs_close (fd);
830 continue;
832 setup_pty (fd);
833 return fd;
836 #endif /* HAVE_PTYS */
837 return -1;
840 /* Allocate basically initialized process. */
842 static struct Lisp_Process *
843 allocate_process (void)
845 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
848 static Lisp_Object
849 make_process (Lisp_Object name)
851 struct Lisp_Process *p = allocate_process ();
852 /* Initialize Lisp data. Note that allocate_process initializes all
853 Lisp data to nil, so do it only for slots which should not be nil. */
854 pset_status (p, Qrun);
855 pset_mark (p, Fmake_marker ());
856 pset_thread (p, Fcurrent_thread ());
858 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
859 non-Lisp data, so do it only for slots which should not be zero. */
860 p->infd = -1;
861 p->outfd = -1;
862 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
863 p->open_fd[i] = -1;
865 #ifdef HAVE_GNUTLS
866 verify (GNUTLS_STAGE_EMPTY == 0);
867 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
868 eassert (NILP (p->gnutls_boot_parameters));
869 #endif
871 /* If name is already in use, modify it until it is unused. */
873 Lisp_Object name1 = name;
874 for (printmax_t i = 1; ; i++)
876 Lisp_Object tem = Fget_process (name1);
877 if (NILP (tem))
878 break;
879 char const suffix_fmt[] = "<%"pMd">";
880 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
881 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
882 name1 = concat2 (name, lsuffix);
884 name = name1;
885 pset_name (p, name);
886 pset_sentinel (p, Qinternal_default_process_sentinel);
887 pset_filter (p, Qinternal_default_process_filter);
888 Lisp_Object val;
889 XSETPROCESS (val, p);
890 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
891 return val;
894 static void
895 remove_process (register Lisp_Object proc)
897 register Lisp_Object pair;
899 pair = Frassq (proc, Vprocess_alist);
900 Vprocess_alist = Fdelq (pair, Vprocess_alist);
902 deactivate_process (proc);
905 void
906 update_processes_for_thread_death (Lisp_Object dying_thread)
908 Lisp_Object pair;
910 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
912 Lisp_Object process = XCDR (XCAR (pair));
913 if (EQ (XPROCESS (process)->thread, dying_thread))
915 struct Lisp_Process *proc = XPROCESS (process);
917 pset_thread (proc, Qnil);
918 if (proc->infd >= 0)
919 fd_callback_info[proc->infd].thread = NULL;
920 if (proc->outfd >= 0)
921 fd_callback_info[proc->outfd].thread = NULL;
926 #ifdef HAVE_GETADDRINFO_A
927 static void
928 free_dns_request (Lisp_Object proc)
930 struct Lisp_Process *p = XPROCESS (proc);
932 if (p->dns_request->ar_result)
933 freeaddrinfo (p->dns_request->ar_result);
934 xfree (p->dns_request);
935 p->dns_request = NULL;
937 #endif
940 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
941 doc: /* Return t if OBJECT is a process. */)
942 (Lisp_Object object)
944 return PROCESSP (object) ? Qt : Qnil;
947 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
948 doc: /* Return the process named NAME, or nil if there is none. */)
949 (register Lisp_Object name)
951 if (PROCESSP (name))
952 return name;
953 CHECK_STRING (name);
954 return Fcdr (Fassoc (name, Vprocess_alist));
957 /* This is how commands for the user decode process arguments. It
958 accepts a process, a process name, a buffer, a buffer name, or nil.
959 Buffers denote the first process in the buffer, and nil denotes the
960 current buffer. */
962 static Lisp_Object
963 get_process (register Lisp_Object name)
965 register Lisp_Object proc, obj;
966 if (STRINGP (name))
968 obj = Fget_process (name);
969 if (NILP (obj))
970 obj = Fget_buffer (name);
971 if (NILP (obj))
972 error ("Process %s does not exist", SDATA (name));
974 else if (NILP (name))
975 obj = Fcurrent_buffer ();
976 else
977 obj = name;
979 /* Now obj should be either a buffer object or a process object. */
980 if (BUFFERP (obj))
982 if (NILP (BVAR (XBUFFER (obj), name)))
983 error ("Attempt to get process for a dead buffer");
984 proc = Fget_buffer_process (obj);
985 if (NILP (proc))
986 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
988 else
990 CHECK_PROCESS (obj);
991 proc = obj;
993 return proc;
997 /* Fdelete_process promises to immediately forget about the process, but in
998 reality, Emacs needs to remember those processes until they have been
999 treated by the SIGCHLD handler and waitpid has been invoked on them;
1000 otherwise they might fill up the kernel's process table.
1002 Some processes created by call-process are also put onto this list.
1004 Members of this list are (process-ID . filename) pairs. The
1005 process-ID is a number; the filename, if a string, is a file that
1006 needs to be removed after the process exits. */
1007 static Lisp_Object deleted_pid_list;
1009 void
1010 record_deleted_pid (pid_t pid, Lisp_Object filename)
1012 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1013 /* GC treated elements set to nil. */
1014 Fdelq (Qnil, deleted_pid_list));
1018 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1019 doc: /* Delete PROCESS: kill it and forget about it immediately.
1020 PROCESS may be a process, a buffer, the name of a process or buffer, or
1021 nil, indicating the current buffer's process. */)
1022 (register Lisp_Object process)
1024 register struct Lisp_Process *p;
1026 process = get_process (process);
1027 p = XPROCESS (process);
1029 #ifdef HAVE_GETADDRINFO_A
1030 if (p->dns_request)
1032 /* Cancel the request. Unless shutting down, wait until
1033 completion. Free the request if completely canceled. */
1035 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
1036 if (!canceled && !inhibit_sentinels)
1038 struct gaicb const *req = p->dns_request;
1039 while (gai_suspend (&req, 1, NULL) != 0)
1040 continue;
1041 canceled = true;
1043 if (canceled)
1044 free_dns_request (process);
1046 #endif
1048 p->raw_status_new = 0;
1049 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1051 pset_status (p, list2 (Qexit, make_number (0)));
1052 p->tick = ++process_tick;
1053 status_notify (p, NULL);
1054 redisplay_preserve_echo_area (13);
1056 else
1058 if (p->alive)
1059 record_kill_process (p, Qnil);
1061 if (p->infd >= 0)
1063 /* Update P's status, since record_kill_process will make the
1064 SIGCHLD handler update deleted_pid_list, not *P. */
1065 Lisp_Object symbol;
1066 if (p->raw_status_new)
1067 update_status (p);
1068 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1069 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1070 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1072 p->tick = ++process_tick;
1073 status_notify (p, NULL);
1074 redisplay_preserve_echo_area (13);
1077 remove_process (process);
1078 return Qnil;
1081 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1082 doc: /* Return the status of PROCESS.
1083 The returned value is one of the following symbols:
1084 run -- for a process that is running.
1085 stop -- for a process stopped but continuable.
1086 exit -- for a process that has exited.
1087 signal -- for a process that has got a fatal signal.
1088 open -- for a network stream connection that is open.
1089 listen -- for a network stream server that is listening.
1090 closed -- for a network stream connection that is closed.
1091 connect -- when waiting for a non-blocking connection to complete.
1092 failed -- when a non-blocking connection has failed.
1093 nil -- if arg is a process name and no such process exists.
1094 PROCESS may be a process, a buffer, the name of a process, or
1095 nil, indicating the current buffer's process. */)
1096 (register Lisp_Object process)
1098 register struct Lisp_Process *p;
1099 register Lisp_Object status;
1101 if (STRINGP (process))
1102 process = Fget_process (process);
1103 else
1104 process = get_process (process);
1106 if (NILP (process))
1107 return process;
1109 p = XPROCESS (process);
1110 if (p->raw_status_new)
1111 update_status (p);
1112 status = p->status;
1113 if (CONSP (status))
1114 status = XCAR (status);
1115 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1117 if (EQ (status, Qexit))
1118 status = Qclosed;
1119 else if (EQ (p->command, Qt))
1120 status = Qstop;
1121 else if (EQ (status, Qrun))
1122 status = Qopen;
1124 return status;
1127 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1128 1, 1, 0,
1129 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1130 If PROCESS has not yet exited or died, return 0. */)
1131 (register Lisp_Object process)
1133 CHECK_PROCESS (process);
1134 if (XPROCESS (process)->raw_status_new)
1135 update_status (XPROCESS (process));
1136 if (CONSP (XPROCESS (process)->status))
1137 return XCAR (XCDR (XPROCESS (process)->status));
1138 return make_number (0);
1141 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1142 doc: /* Return the process id of PROCESS.
1143 This is the pid of the external process which PROCESS uses or talks to.
1144 For a network, serial, and pipe connections, this value is nil. */)
1145 (register Lisp_Object process)
1147 pid_t pid;
1149 CHECK_PROCESS (process);
1150 pid = XPROCESS (process)->pid;
1151 return (pid ? make_fixnum_or_float (pid) : Qnil);
1154 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1155 doc: /* Return the name of PROCESS, as a string.
1156 This is the name of the program invoked in PROCESS,
1157 possibly modified to make it unique among process names. */)
1158 (register Lisp_Object process)
1160 CHECK_PROCESS (process);
1161 return XPROCESS (process)->name;
1164 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1165 doc: /* Return the command that was executed to start PROCESS.
1166 This is a list of strings, the first string being the program executed
1167 and the rest of the strings being the arguments given to it.
1168 For a network or serial or pipe connection, this is nil (process is running)
1169 or t (process is stopped). */)
1170 (register Lisp_Object process)
1172 CHECK_PROCESS (process);
1173 return XPROCESS (process)->command;
1176 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1177 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1178 This is the terminal that the process itself reads and writes on,
1179 not the name of the pty that Emacs uses to talk with that terminal. */)
1180 (register Lisp_Object process)
1182 CHECK_PROCESS (process);
1183 return XPROCESS (process)->tty_name;
1186 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1187 2, 2, 0,
1188 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1189 Return BUFFER. */)
1190 (register Lisp_Object process, Lisp_Object buffer)
1192 struct Lisp_Process *p;
1194 CHECK_PROCESS (process);
1195 if (!NILP (buffer))
1196 CHECK_BUFFER (buffer);
1197 p = XPROCESS (process);
1198 pset_buffer (p, buffer);
1199 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1200 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1201 setup_process_coding_systems (process);
1202 return buffer;
1205 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1206 1, 1, 0,
1207 doc: /* Return the buffer PROCESS is associated with.
1208 The default process filter inserts output from PROCESS into this buffer. */)
1209 (register Lisp_Object process)
1211 CHECK_PROCESS (process);
1212 return XPROCESS (process)->buffer;
1215 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1216 1, 1, 0,
1217 doc: /* Return the marker for the end of the last output from PROCESS. */)
1218 (register Lisp_Object process)
1220 CHECK_PROCESS (process);
1221 return XPROCESS (process)->mark;
1224 static void
1225 set_process_filter_masks (struct Lisp_Process *p)
1227 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1228 delete_read_fd (p->infd);
1229 else if (EQ (p->filter, Qt)
1230 /* Network or serial process not stopped: */
1231 && !EQ (p->command, Qt))
1232 add_process_read_fd (p->infd);
1235 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1236 2, 2, 0,
1237 doc: /* Give PROCESS the filter function FILTER; nil means default.
1238 A value of t means stop accepting output from the process.
1240 When a process has a non-default filter, its buffer is not used for output.
1241 Instead, each time it does output, the entire string of output is
1242 passed to the filter.
1244 The filter gets two arguments: the process and the string of output.
1245 The string argument is normally a multibyte string, except:
1246 - if the process's input coding system is no-conversion or raw-text,
1247 it is a unibyte string (the non-converted input), or else
1248 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1249 string (the result of converting the decoded input multibyte
1250 string to unibyte with `string-make-unibyte'). */)
1251 (Lisp_Object process, Lisp_Object filter)
1253 CHECK_PROCESS (process);
1254 struct Lisp_Process *p = XPROCESS (process);
1256 /* Don't signal an error if the process's input file descriptor
1257 is closed. This could make debugging Lisp more difficult,
1258 for example when doing something like
1260 (setq process (start-process ...))
1261 (debug)
1262 (set-process-filter process ...) */
1264 if (NILP (filter))
1265 filter = Qinternal_default_process_filter;
1267 pset_filter (p, filter);
1269 if (p->infd >= 0)
1270 set_process_filter_masks (p);
1272 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1273 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1274 setup_process_coding_systems (process);
1275 return filter;
1278 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1279 1, 1, 0,
1280 doc: /* Return the filter function of PROCESS.
1281 See `set-process-filter' for more info on filter functions. */)
1282 (register Lisp_Object process)
1284 CHECK_PROCESS (process);
1285 return XPROCESS (process)->filter;
1288 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1289 2, 2, 0,
1290 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1291 The sentinel is called as a function when the process changes state.
1292 It gets two arguments: the process, and a string describing the change. */)
1293 (register Lisp_Object process, Lisp_Object sentinel)
1295 struct Lisp_Process *p;
1297 CHECK_PROCESS (process);
1298 p = XPROCESS (process);
1300 if (NILP (sentinel))
1301 sentinel = Qinternal_default_process_sentinel;
1303 pset_sentinel (p, sentinel);
1304 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1305 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1306 return sentinel;
1309 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1310 1, 1, 0,
1311 doc: /* Return the sentinel of PROCESS.
1312 See `set-process-sentinel' for more info on sentinels. */)
1313 (register Lisp_Object process)
1315 CHECK_PROCESS (process);
1316 return XPROCESS (process)->sentinel;
1319 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1320 2, 2, 0,
1321 doc: /* Set the locking thread of PROCESS to be THREAD.
1322 If THREAD is nil, the process is unlocked. */)
1323 (Lisp_Object process, Lisp_Object thread)
1325 struct Lisp_Process *proc;
1326 struct thread_state *tstate;
1328 CHECK_PROCESS (process);
1329 if (NILP (thread))
1330 tstate = NULL;
1331 else
1333 CHECK_THREAD (thread);
1334 tstate = XTHREAD (thread);
1337 proc = XPROCESS (process);
1338 pset_thread (proc, thread);
1339 if (proc->infd >= 0)
1340 fd_callback_info[proc->infd].thread = tstate;
1341 if (proc->outfd >= 0)
1342 fd_callback_info[proc->outfd].thread = tstate;
1344 return thread;
1347 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1348 1, 1, 0,
1349 doc: /* Ret the locking thread of PROCESS.
1350 If PROCESS is unlocked, this function returns nil. */)
1351 (Lisp_Object process)
1353 CHECK_PROCESS (process);
1354 return XPROCESS (process)->thread;
1357 DEFUN ("set-process-window-size", Fset_process_window_size,
1358 Sset_process_window_size, 3, 3, 0,
1359 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1360 Value is t if PROCESS was successfully told about the window size,
1361 nil otherwise. */)
1362 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1364 CHECK_PROCESS (process);
1366 /* All known platforms store window sizes as 'unsigned short'. */
1367 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1368 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1370 if (NETCONN_P (process)
1371 || XPROCESS (process)->infd < 0
1372 || (set_window_size (XPROCESS (process)->infd,
1373 XINT (height), XINT (width))
1374 < 0))
1375 return Qnil;
1376 else
1377 return Qt;
1380 DEFUN ("set-process-inherit-coding-system-flag",
1381 Fset_process_inherit_coding_system_flag,
1382 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1383 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1384 If the second argument FLAG is non-nil, then the variable
1385 `buffer-file-coding-system' of the buffer associated with PROCESS
1386 will be bound to the value of the coding system used to decode
1387 the process output.
1389 This is useful when the coding system specified for the process buffer
1390 leaves either the character code conversion or the end-of-line conversion
1391 unspecified, or if the coding system used to decode the process output
1392 is more appropriate for saving the process buffer.
1394 Binding the variable `inherit-process-coding-system' to non-nil before
1395 starting the process is an alternative way of setting the inherit flag
1396 for the process which will run.
1398 This function returns FLAG. */)
1399 (register Lisp_Object process, Lisp_Object flag)
1401 CHECK_PROCESS (process);
1402 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1403 return flag;
1406 DEFUN ("set-process-query-on-exit-flag",
1407 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1408 2, 2, 0,
1409 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1410 If the second argument FLAG is non-nil, Emacs will query the user before
1411 exiting or killing a buffer if PROCESS is running. This function
1412 returns FLAG. */)
1413 (register Lisp_Object process, Lisp_Object flag)
1415 CHECK_PROCESS (process);
1416 XPROCESS (process)->kill_without_query = NILP (flag);
1417 return flag;
1420 DEFUN ("process-query-on-exit-flag",
1421 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1422 1, 1, 0,
1423 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1424 (register Lisp_Object process)
1426 CHECK_PROCESS (process);
1427 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1430 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1431 1, 2, 0,
1432 doc: /* Return the contact info of PROCESS; t for a real child.
1433 For a network or serial or pipe connection, the value depends on the
1434 optional KEY arg. If KEY is nil, value is a cons cell of the form
1435 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1436 connection; it is t for a pipe connection. If KEY is t, the complete
1437 contact information for the connection is returned, else the specific
1438 value for the keyword KEY is returned. See `make-network-process',
1439 `make-serial-process', or `make pipe-process' for the list of keywords.
1440 If PROCESS is a non-blocking network process that hasn't been fully
1441 set up yet, this function will block until socket setup has completed. */)
1442 (Lisp_Object process, Lisp_Object key)
1444 Lisp_Object contact;
1446 CHECK_PROCESS (process);
1447 contact = XPROCESS (process)->childp;
1449 #ifdef DATAGRAM_SOCKETS
1451 if (NETCONN_P (process))
1452 wait_for_socket_fds (process, "process-contact");
1454 if (DATAGRAM_CONN_P (process)
1455 && (EQ (key, Qt) || EQ (key, QCremote)))
1456 contact = Fplist_put (contact, QCremote,
1457 Fprocess_datagram_address (process));
1458 #endif
1460 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1461 || EQ (key, Qt))
1462 return contact;
1463 if (NILP (key) && NETCONN_P (process))
1464 return list2 (Fplist_get (contact, QChost),
1465 Fplist_get (contact, QCservice));
1466 if (NILP (key) && SERIALCONN_P (process))
1467 return list2 (Fplist_get (contact, QCport),
1468 Fplist_get (contact, QCspeed));
1469 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1470 if the pipe process is useful for purposes other than receiving
1471 stderr. */
1472 if (NILP (key) && PIPECONN_P (process))
1473 return Qt;
1474 return Fplist_get (contact, key);
1477 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1478 1, 1, 0,
1479 doc: /* Return the plist of PROCESS. */)
1480 (register Lisp_Object process)
1482 CHECK_PROCESS (process);
1483 return XPROCESS (process)->plist;
1486 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1487 2, 2, 0,
1488 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1489 (Lisp_Object process, Lisp_Object plist)
1491 CHECK_PROCESS (process);
1492 CHECK_LIST (plist);
1494 pset_plist (XPROCESS (process), plist);
1495 return plist;
1498 #if 0 /* Turned off because we don't currently record this info
1499 in the process. Perhaps add it. */
1500 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1501 doc: /* Return the connection type of PROCESS.
1502 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1503 a socket connection. */)
1504 (Lisp_Object process)
1506 return XPROCESS (process)->type;
1508 #endif
1510 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1511 doc: /* Return the connection type of PROCESS.
1512 The value is either the symbol `real', `network', `serial', or `pipe'.
1513 PROCESS may be a process, a buffer, the name of a process or buffer, or
1514 nil, indicating the current buffer's process. */)
1515 (Lisp_Object process)
1517 Lisp_Object proc;
1518 proc = get_process (process);
1519 return XPROCESS (proc)->type;
1522 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1523 1, 2, 0,
1524 doc: /* Convert network ADDRESS from internal format to a string.
1525 A 4 or 5 element vector represents an IPv4 address (with port number).
1526 An 8 or 9 element vector represents an IPv6 address (with port number).
1527 If optional second argument OMIT-PORT is non-nil, don't include a port
1528 number in the string, even when present in ADDRESS.
1529 Return nil if format of ADDRESS is invalid. */)
1530 (Lisp_Object address, Lisp_Object omit_port)
1532 if (NILP (address))
1533 return Qnil;
1535 if (STRINGP (address)) /* AF_LOCAL */
1536 return address;
1538 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1540 register struct Lisp_Vector *p = XVECTOR (address);
1541 ptrdiff_t size = p->header.size;
1542 Lisp_Object args[10];
1543 int nargs, i;
1544 char const *format;
1546 if (size == 4 || (size == 5 && !NILP (omit_port)))
1548 format = "%d.%d.%d.%d";
1549 nargs = 4;
1551 else if (size == 5)
1553 format = "%d.%d.%d.%d:%d";
1554 nargs = 5;
1556 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1558 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1559 nargs = 8;
1561 else if (size == 9)
1563 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1564 nargs = 9;
1566 else
1567 return Qnil;
1569 AUTO_STRING (format_obj, format);
1570 args[0] = format_obj;
1572 for (i = 0; i < nargs; i++)
1574 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1575 return Qnil;
1577 if (nargs <= 5 /* IPv4 */
1578 && i < 4 /* host, not port */
1579 && XINT (p->contents[i]) > 255)
1580 return Qnil;
1582 args[i + 1] = p->contents[i];
1585 return Fformat (nargs + 1, args);
1588 if (CONSP (address))
1590 AUTO_STRING (format, "<Family %d>");
1591 return CALLN (Fformat, format, Fcar (address));
1594 return Qnil;
1597 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1598 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1599 (void)
1601 return Fmapcar (Qcdr, Vprocess_alist);
1604 /* Starting asynchronous inferior processes. */
1606 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1607 doc: /* Start a program in a subprocess. Return the process object for it.
1609 This is similar to `start-process', but arguments are specified as
1610 keyword/argument pairs. The following arguments are defined:
1612 :name NAME -- NAME is name for process. It is modified if necessary
1613 to make it unique.
1615 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1616 with the process. Process output goes at end of that buffer, unless
1617 you specify an output stream or filter function to handle the output.
1618 BUFFER may be also nil, meaning that this process is not associated
1619 with any buffer.
1621 :command COMMAND -- COMMAND is a list starting with the program file
1622 name, followed by strings to give to the program as arguments.
1624 :coding CODING -- If CODING is a symbol, it specifies the coding
1625 system used for both reading and writing for this process. If CODING
1626 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1627 ENCODING is used for writing.
1629 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1630 the process is running. If BOOL is not given, query before exiting.
1632 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1633 In the stopped state, a process does not accept incoming data, but you
1634 can send outgoing data. The stopped state is cleared by
1635 `continue-process' and set by `stop-process'.
1637 :connection-type TYPE -- TYPE is control type of device used to
1638 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1639 to use a pty, or nil to use the default specified through
1640 `process-connection-type'.
1642 :filter FILTER -- Install FILTER as the process filter.
1644 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1646 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1647 to the standard error of subprocess. Specifying this implies
1648 `:connection-type' is set to `pipe'.
1650 usage: (make-process &rest ARGS) */)
1651 (ptrdiff_t nargs, Lisp_Object *args)
1653 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1654 Lisp_Object xstderr, stderrproc;
1655 ptrdiff_t count = SPECPDL_INDEX ();
1657 if (nargs == 0)
1658 return Qnil;
1660 /* Save arguments for process-contact and clone-process. */
1661 contact = Flist (nargs, args);
1663 buffer = Fplist_get (contact, QCbuffer);
1664 if (!NILP (buffer))
1665 buffer = Fget_buffer_create (buffer);
1667 /* Make sure that the child will be able to chdir to the current
1668 buffer's current directory, or its unhandled equivalent. We
1669 can't just have the child check for an error when it does the
1670 chdir, since it's in a vfork. */
1671 current_dir = encode_current_directory ();
1673 name = Fplist_get (contact, QCname);
1674 CHECK_STRING (name);
1676 command = Fplist_get (contact, QCcommand);
1677 if (CONSP (command))
1678 program = XCAR (command);
1679 else
1680 program = Qnil;
1682 if (!NILP (program))
1683 CHECK_STRING (program);
1685 stderrproc = Qnil;
1686 xstderr = Fplist_get (contact, QCstderr);
1687 if (PROCESSP (xstderr))
1689 if (!PIPECONN_P (xstderr))
1690 error ("Process is not a pipe process");
1691 stderrproc = xstderr;
1693 else if (!NILP (xstderr))
1695 CHECK_STRING (program);
1696 stderrproc = CALLN (Fmake_pipe_process,
1697 QCname,
1698 concat2 (name, build_string (" stderr")),
1699 QCbuffer,
1700 Fget_buffer_create (xstderr));
1703 proc = make_process (name);
1704 record_unwind_protect (start_process_unwind, proc);
1706 pset_childp (XPROCESS (proc), Qt);
1707 eassert (NILP (XPROCESS (proc)->plist));
1708 pset_type (XPROCESS (proc), Qreal);
1709 pset_buffer (XPROCESS (proc), buffer);
1710 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1711 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1712 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1714 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1715 XPROCESS (proc)->kill_without_query = 1;
1716 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1717 pset_command (XPROCESS (proc), Qt);
1719 tem = Fplist_get (contact, QCconnection_type);
1720 if (EQ (tem, Qpty))
1721 XPROCESS (proc)->pty_flag = true;
1722 else if (EQ (tem, Qpipe))
1723 XPROCESS (proc)->pty_flag = false;
1724 else if (NILP (tem))
1725 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1726 else
1727 report_file_error ("Unknown connection type", tem);
1729 if (!NILP (stderrproc))
1731 pset_stderrproc (XPROCESS (proc), stderrproc);
1733 XPROCESS (proc)->pty_flag = false;
1736 #ifdef HAVE_GNUTLS
1737 /* AKA GNUTLS_INITSTAGE(proc). */
1738 verify (GNUTLS_STAGE_EMPTY == 0);
1739 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1740 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1741 #endif
1743 XPROCESS (proc)->adaptive_read_buffering
1744 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1745 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1747 /* Make the process marker point into the process buffer (if any). */
1748 if (BUFFERP (buffer))
1749 set_marker_both (XPROCESS (proc)->mark, buffer,
1750 BUF_ZV (XBUFFER (buffer)),
1751 BUF_ZV_BYTE (XBUFFER (buffer)));
1753 USE_SAFE_ALLOCA;
1756 /* Decide coding systems for communicating with the process. Here
1757 we don't setup the structure coding_system nor pay attention to
1758 unibyte mode. They are done in create_process. */
1760 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1761 Lisp_Object coding_systems = Qt;
1762 Lisp_Object val, *args2;
1764 tem = Fplist_get (contact, QCcoding);
1765 if (!NILP (tem))
1767 val = tem;
1768 if (CONSP (val))
1769 val = XCAR (val);
1771 else
1772 val = Vcoding_system_for_read;
1773 if (NILP (val))
1775 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1776 Lisp_Object tem2;
1777 SAFE_ALLOCA_LISP (args2, nargs2);
1778 ptrdiff_t i = 0;
1779 args2[i++] = Qstart_process;
1780 args2[i++] = name;
1781 args2[i++] = buffer;
1782 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1783 args2[i++] = XCAR (tem2);
1784 if (!NILP (program))
1785 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1786 if (CONSP (coding_systems))
1787 val = XCAR (coding_systems);
1788 else if (CONSP (Vdefault_process_coding_system))
1789 val = XCAR (Vdefault_process_coding_system);
1791 pset_decode_coding_system (XPROCESS (proc), val);
1793 if (!NILP (tem))
1795 val = tem;
1796 if (CONSP (val))
1797 val = XCDR (val);
1799 else
1800 val = Vcoding_system_for_write;
1801 if (NILP (val))
1803 if (EQ (coding_systems, Qt))
1805 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1806 Lisp_Object tem2;
1807 SAFE_ALLOCA_LISP (args2, nargs2);
1808 ptrdiff_t i = 0;
1809 args2[i++] = Qstart_process;
1810 args2[i++] = name;
1811 args2[i++] = buffer;
1812 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1813 args2[i++] = XCAR (tem2);
1814 if (!NILP (program))
1815 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1817 if (CONSP (coding_systems))
1818 val = XCDR (coding_systems);
1819 else if (CONSP (Vdefault_process_coding_system))
1820 val = XCDR (Vdefault_process_coding_system);
1822 pset_encode_coding_system (XPROCESS (proc), val);
1823 /* Note: At this moment, the above coding system may leave
1824 text-conversion or eol-conversion unspecified. They will be
1825 decided after we read output from the process and decode it by
1826 some coding system, or just before we actually send a text to
1827 the process. */
1831 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1832 eassert (XPROCESS (proc)->decoding_carryover == 0);
1833 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1835 XPROCESS (proc)->inherit_coding_system_flag
1836 = !(NILP (buffer) || !inherit_process_coding_system);
1838 if (!NILP (program))
1840 Lisp_Object program_args = XCDR (command);
1842 /* If program file name is not absolute, search our path for it.
1843 Put the name we will really use in TEM. */
1844 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1845 && !(SCHARS (program) > 1
1846 && IS_DEVICE_SEP (SREF (program, 1))))
1848 tem = Qnil;
1849 openp (Vexec_path, program, Vexec_suffixes, &tem,
1850 make_number (X_OK), false);
1851 if (NILP (tem))
1852 report_file_error ("Searching for program", program);
1853 tem = Fexpand_file_name (tem, Qnil);
1855 else
1857 if (!NILP (Ffile_directory_p (program)))
1858 error ("Specified program for new process is a directory");
1859 tem = program;
1862 /* Remove "/:" from TEM. */
1863 tem = remove_slash_colon (tem);
1865 Lisp_Object arg_encoding = Qnil;
1867 /* Encode the file name and put it in NEW_ARGV.
1868 That's where the child will use it to execute the program. */
1869 tem = list1 (ENCODE_FILE (tem));
1870 ptrdiff_t new_argc = 1;
1872 /* Here we encode arguments by the coding system used for sending
1873 data to the process. We don't support using different coding
1874 systems for encoding arguments and for encoding data sent to the
1875 process. */
1877 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1879 Lisp_Object arg = XCAR (tem2);
1880 CHECK_STRING (arg);
1881 if (STRING_MULTIBYTE (arg))
1883 if (NILP (arg_encoding))
1884 arg_encoding = (complement_process_encoding_system
1885 (XPROCESS (proc)->encode_coding_system));
1886 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1888 tem = Fcons (arg, tem);
1889 new_argc++;
1892 /* Now that everything is encoded we can collect the strings into
1893 NEW_ARGV. */
1894 char **new_argv;
1895 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1896 new_argv[new_argc] = 0;
1898 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1900 new_argv[i] = SSDATA (XCAR (tem));
1901 tem = XCDR (tem);
1904 create_process (proc, new_argv, current_dir);
1906 else
1907 create_pty (proc);
1909 SAFE_FREE ();
1910 return unbind_to (count, proc);
1913 /* If PROC doesn't have its pid set, then an error was signaled and
1914 the process wasn't started successfully, so remove it. */
1915 static void
1916 start_process_unwind (Lisp_Object proc)
1918 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1919 remove_process (proc);
1922 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1924 static void
1925 close_process_fd (int *fd_addr)
1927 int fd = *fd_addr;
1928 if (0 <= fd)
1930 *fd_addr = -1;
1931 emacs_close (fd);
1935 /* Indexes of file descriptors in open_fds. */
1936 enum
1938 /* The pipe from Emacs to its subprocess. */
1939 SUBPROCESS_STDIN,
1940 WRITE_TO_SUBPROCESS,
1942 /* The main pipe from the subprocess to Emacs. */
1943 READ_FROM_SUBPROCESS,
1944 SUBPROCESS_STDOUT,
1946 /* The pipe from the subprocess to Emacs that is closed when the
1947 subprocess execs. */
1948 READ_FROM_EXEC_MONITOR,
1949 EXEC_MONITOR_OUTPUT
1952 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1954 static void
1955 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1957 struct Lisp_Process *p = XPROCESS (process);
1958 int inchannel, outchannel;
1959 pid_t pid;
1960 int vfork_errno;
1961 int forkin, forkout, forkerr = -1;
1962 bool pty_flag = 0;
1963 char pty_name[PTY_NAME_SIZE];
1964 Lisp_Object lisp_pty_name = Qnil;
1965 sigset_t oldset;
1967 inchannel = outchannel = -1;
1969 if (p->pty_flag)
1970 outchannel = inchannel = allocate_pty (pty_name);
1972 if (inchannel >= 0)
1974 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1975 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1976 /* On most USG systems it does not work to open the pty's tty here,
1977 then close it and reopen it in the child. */
1978 /* Don't let this terminal become our controlling terminal
1979 (in case we don't have one). */
1980 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1981 if (forkin < 0)
1982 report_file_error ("Opening pty", Qnil);
1983 p->open_fd[SUBPROCESS_STDIN] = forkin;
1984 #else
1985 forkin = forkout = -1;
1986 #endif /* not USG, or USG_SUBTTY_WORKS */
1987 pty_flag = 1;
1988 lisp_pty_name = build_string (pty_name);
1990 else
1992 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1993 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1994 report_file_error ("Creating pipe", Qnil);
1995 forkin = p->open_fd[SUBPROCESS_STDIN];
1996 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1997 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1998 forkout = p->open_fd[SUBPROCESS_STDOUT];
2000 if (!NILP (p->stderrproc))
2002 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2004 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
2006 /* Close unnecessary file descriptors. */
2007 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
2008 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
2012 #ifndef WINDOWSNT
2013 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
2014 report_file_error ("Creating pipe", Qnil);
2015 #endif
2017 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2018 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2020 /* Record this as an active process, with its channels. */
2021 chan_process[inchannel] = process;
2022 p->infd = inchannel;
2023 p->outfd = outchannel;
2025 /* Previously we recorded the tty descriptor used in the subprocess.
2026 It was only used for getting the foreground tty process, so now
2027 we just reopen the device (see emacs_get_tty_pgrp) as this is
2028 more portable (see USG_SUBTTY_WORKS above). */
2030 p->pty_flag = pty_flag;
2031 pset_status (p, Qrun);
2033 if (!EQ (p->command, Qt))
2034 add_process_read_fd (inchannel);
2036 /* This may signal an error. */
2037 setup_process_coding_systems (process);
2039 block_input ();
2040 block_child_signal (&oldset);
2042 #ifndef WINDOWSNT
2043 /* vfork, and prevent local vars from being clobbered by the vfork. */
2044 Lisp_Object volatile current_dir_volatile = current_dir;
2045 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
2046 char **volatile new_argv_volatile = new_argv;
2047 int volatile forkin_volatile = forkin;
2048 int volatile forkout_volatile = forkout;
2049 int volatile forkerr_volatile = forkerr;
2050 struct Lisp_Process *p_volatile = p;
2052 pid = vfork ();
2054 current_dir = current_dir_volatile;
2055 lisp_pty_name = lisp_pty_name_volatile;
2056 new_argv = new_argv_volatile;
2057 forkin = forkin_volatile;
2058 forkout = forkout_volatile;
2059 forkerr = forkerr_volatile;
2060 p = p_volatile;
2062 pty_flag = p->pty_flag;
2064 if (pid == 0)
2065 #endif /* not WINDOWSNT */
2067 /* Make the pty be the controlling terminal of the process. */
2068 #ifdef HAVE_PTYS
2069 /* First, disconnect its current controlling terminal. */
2070 if (pty_flag)
2071 setsid ();
2072 /* Make the pty's terminal the controlling terminal. */
2073 if (pty_flag && forkin >= 0)
2075 #ifdef TIOCSCTTY
2076 /* We ignore the return value
2077 because faith@cs.unc.edu says that is necessary on Linux. */
2078 ioctl (forkin, TIOCSCTTY, 0);
2079 #endif
2081 #if defined (LDISC1)
2082 if (pty_flag && forkin >= 0)
2084 struct termios t;
2085 tcgetattr (forkin, &t);
2086 t.c_lflag = LDISC1;
2087 if (tcsetattr (forkin, TCSANOW, &t) < 0)
2088 emacs_perror ("create_process/tcsetattr LDISC1");
2090 #else
2091 #if defined (NTTYDISC) && defined (TIOCSETD)
2092 if (pty_flag && forkin >= 0)
2094 /* Use new line discipline. */
2095 int ldisc = NTTYDISC;
2096 ioctl (forkin, TIOCSETD, &ldisc);
2098 #endif
2099 #endif
2100 #ifdef TIOCNOTTY
2101 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2102 can do TIOCSPGRP only to the process's controlling tty. */
2103 if (pty_flag)
2105 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2106 I can't test it since I don't have 4.3. */
2107 int j = emacs_open (DEV_TTY, O_RDWR, 0);
2108 if (j >= 0)
2110 ioctl (j, TIOCNOTTY, 0);
2111 emacs_close (j);
2114 #endif /* TIOCNOTTY */
2116 #if !defined (DONT_REOPEN_PTY)
2117 /*** There is a suggestion that this ought to be a
2118 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2119 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2120 that system does seem to need this code, even though
2121 both TIOCSCTTY is defined. */
2122 /* Now close the pty (if we had it open) and reopen it.
2123 This makes the pty the controlling terminal of the subprocess. */
2124 if (pty_flag)
2127 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2128 would work? */
2129 if (forkin >= 0)
2130 emacs_close (forkin);
2131 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2133 if (forkin < 0)
2135 emacs_perror (SSDATA (lisp_pty_name));
2136 _exit (EXIT_CANCELED);
2140 #endif /* not DONT_REOPEN_PTY */
2142 #ifdef SETUP_SLAVE_PTY
2143 if (pty_flag)
2145 SETUP_SLAVE_PTY;
2147 #endif /* SETUP_SLAVE_PTY */
2148 #endif /* HAVE_PTYS */
2150 signal (SIGINT, SIG_DFL);
2151 signal (SIGQUIT, SIG_DFL);
2152 #ifdef SIGPROF
2153 signal (SIGPROF, SIG_DFL);
2154 #endif
2156 /* Emacs ignores SIGPIPE, but the child should not. */
2157 signal (SIGPIPE, SIG_DFL);
2159 /* Stop blocking SIGCHLD in the child. */
2160 unblock_child_signal (&oldset);
2162 if (pty_flag)
2163 child_setup_tty (forkout);
2165 if (forkerr < 0)
2166 forkerr = forkout;
2167 #ifdef WINDOWSNT
2168 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2169 #else /* not WINDOWSNT */
2170 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2171 #endif /* not WINDOWSNT */
2174 /* Back in the parent process. */
2176 vfork_errno = errno;
2177 p->pid = pid;
2178 if (pid >= 0)
2179 p->alive = 1;
2181 /* Stop blocking in the parent. */
2182 unblock_child_signal (&oldset);
2183 unblock_input ();
2185 if (pid < 0)
2186 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2187 else
2189 /* vfork succeeded. */
2191 /* Close the pipe ends that the child uses, or the child's pty. */
2192 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2193 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2195 #ifdef WINDOWSNT
2196 register_child (pid, inchannel);
2197 #endif /* WINDOWSNT */
2199 pset_tty_name (p, lisp_pty_name);
2201 #ifndef WINDOWSNT
2202 /* Wait for child_setup to complete in case that vfork is
2203 actually defined as fork. The descriptor
2204 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2205 of a pipe is closed at the child side either by close-on-exec
2206 on successful execve or the _exit call in child_setup. */
2208 char dummy;
2210 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2211 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2212 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2214 #endif
2215 if (!NILP (p->stderrproc))
2217 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2218 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2223 static void
2224 create_pty (Lisp_Object process)
2226 struct Lisp_Process *p = XPROCESS (process);
2227 char pty_name[PTY_NAME_SIZE];
2228 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2230 if (pty_fd >= 0)
2232 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2233 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2234 /* On most USG systems it does not work to open the pty's tty here,
2235 then close it and reopen it in the child. */
2236 /* Don't let this terminal become our controlling terminal
2237 (in case we don't have one). */
2238 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2239 if (forkout < 0)
2240 report_file_error ("Opening pty", Qnil);
2241 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2242 #if defined (DONT_REOPEN_PTY)
2243 /* In the case that vfork is defined as fork, the parent process
2244 (Emacs) may send some data before the child process completes
2245 tty options setup. So we setup tty before forking. */
2246 child_setup_tty (forkout);
2247 #endif /* DONT_REOPEN_PTY */
2248 #endif /* not USG, or USG_SUBTTY_WORKS */
2250 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2252 /* Record this as an active process, with its channels.
2253 As a result, child_setup will close Emacs's side of the pipes. */
2254 chan_process[pty_fd] = process;
2255 p->infd = pty_fd;
2256 p->outfd = pty_fd;
2258 /* Previously we recorded the tty descriptor used in the subprocess.
2259 It was only used for getting the foreground tty process, so now
2260 we just reopen the device (see emacs_get_tty_pgrp) as this is
2261 more portable (see USG_SUBTTY_WORKS above). */
2263 p->pty_flag = 1;
2264 pset_status (p, Qrun);
2265 setup_process_coding_systems (process);
2267 add_process_read_fd (pty_fd);
2269 pset_tty_name (p, build_string (pty_name));
2272 p->pid = -2;
2275 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2276 0, MANY, 0,
2277 doc: /* Create and return a bidirectional pipe process.
2279 In Emacs, pipes are represented by process objects, so input and
2280 output work as for subprocesses, and `delete-process' closes a pipe.
2281 However, a pipe process has no process id, it cannot be signaled,
2282 and the status codes are different from normal processes.
2284 Arguments are specified as keyword/argument pairs. The following
2285 arguments are defined:
2287 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2289 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2290 with the process. Process output goes at the end of that buffer,
2291 unless you specify an output stream or filter function to handle the
2292 output. If BUFFER is not given, the value of NAME is used.
2294 :coding CODING -- If CODING is a symbol, it specifies the coding
2295 system used for both reading and writing for this process. If CODING
2296 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2297 ENCODING is used for writing.
2299 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2300 the process is running. If BOOL is not given, query before exiting.
2302 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2303 In the stopped state, a pipe process does not accept incoming data,
2304 but you can send outgoing data. The stopped state is cleared by
2305 `continue-process' and set by `stop-process'.
2307 :filter FILTER -- Install FILTER as the process filter.
2309 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2311 usage: (make-pipe-process &rest ARGS) */)
2312 (ptrdiff_t nargs, Lisp_Object *args)
2314 Lisp_Object proc, contact;
2315 struct Lisp_Process *p;
2316 Lisp_Object name, buffer;
2317 Lisp_Object tem;
2318 ptrdiff_t specpdl_count;
2319 int inchannel, outchannel;
2321 if (nargs == 0)
2322 return Qnil;
2324 contact = Flist (nargs, args);
2326 name = Fplist_get (contact, QCname);
2327 CHECK_STRING (name);
2328 proc = make_process (name);
2329 specpdl_count = SPECPDL_INDEX ();
2330 record_unwind_protect (remove_process, proc);
2331 p = XPROCESS (proc);
2333 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2334 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2335 report_file_error ("Creating pipe", Qnil);
2336 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2337 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2339 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2340 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2342 #ifdef WINDOWSNT
2343 register_aux_fd (inchannel);
2344 #endif
2346 /* Record this as an active process, with its channels. */
2347 chan_process[inchannel] = proc;
2348 p->infd = inchannel;
2349 p->outfd = outchannel;
2351 if (inchannel > max_desc)
2352 max_desc = inchannel;
2354 buffer = Fplist_get (contact, QCbuffer);
2355 if (NILP (buffer))
2356 buffer = name;
2357 buffer = Fget_buffer_create (buffer);
2358 pset_buffer (p, buffer);
2360 pset_childp (p, contact);
2361 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2362 pset_type (p, Qpipe);
2363 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2364 pset_filter (p, Fplist_get (contact, QCfilter));
2365 eassert (NILP (p->log));
2366 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2367 p->kill_without_query = 1;
2368 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2369 pset_command (p, Qt);
2370 eassert (! p->pty_flag);
2372 if (!EQ (p->command, Qt))
2373 add_process_read_fd (inchannel);
2374 p->adaptive_read_buffering
2375 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2376 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2378 /* Make the process marker point into the process buffer (if any). */
2379 if (BUFFERP (buffer))
2380 set_marker_both (p->mark, buffer,
2381 BUF_ZV (XBUFFER (buffer)),
2382 BUF_ZV_BYTE (XBUFFER (buffer)));
2385 /* Setup coding systems for communicating with the network stream. */
2387 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2388 Lisp_Object coding_systems = Qt;
2389 Lisp_Object val;
2391 tem = Fplist_get (contact, QCcoding);
2392 val = Qnil;
2393 if (!NILP (tem))
2395 val = tem;
2396 if (CONSP (val))
2397 val = XCAR (val);
2399 else if (!NILP (Vcoding_system_for_read))
2400 val = Vcoding_system_for_read;
2401 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2402 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2403 /* We dare not decode end-of-line format by setting VAL to
2404 Qraw_text, because the existing Emacs Lisp libraries
2405 assume that they receive bare code including a sequence of
2406 CR LF. */
2407 val = Qnil;
2408 else
2410 if (CONSP (coding_systems))
2411 val = XCAR (coding_systems);
2412 else if (CONSP (Vdefault_process_coding_system))
2413 val = XCAR (Vdefault_process_coding_system);
2414 else
2415 val = Qnil;
2417 pset_decode_coding_system (p, val);
2419 if (!NILP (tem))
2421 val = tem;
2422 if (CONSP (val))
2423 val = XCDR (val);
2425 else if (!NILP (Vcoding_system_for_write))
2426 val = Vcoding_system_for_write;
2427 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2428 val = Qnil;
2429 else
2431 if (CONSP (coding_systems))
2432 val = XCDR (coding_systems);
2433 else if (CONSP (Vdefault_process_coding_system))
2434 val = XCDR (Vdefault_process_coding_system);
2435 else
2436 val = Qnil;
2438 pset_encode_coding_system (p, val);
2440 /* This may signal an error. */
2441 setup_process_coding_systems (proc);
2443 specpdl_ptr = specpdl + specpdl_count;
2445 return proc;
2449 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2450 The address family of sa is not included in the result. */
2452 Lisp_Object
2453 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2455 Lisp_Object address;
2456 ptrdiff_t i;
2457 unsigned char *cp;
2458 struct Lisp_Vector *p;
2460 /* Workaround for a bug in getsockname on BSD: Names bound to
2461 sockets in the UNIX domain are inaccessible; getsockname returns
2462 a zero length name. */
2463 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2464 return empty_unibyte_string;
2466 switch (sa->sa_family)
2468 case AF_INET:
2470 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2471 len = sizeof (sin->sin_addr) + 1;
2472 address = Fmake_vector (make_number (len), Qnil);
2473 p = XVECTOR (address);
2474 p->contents[--len] = make_number (ntohs (sin->sin_port));
2475 cp = (unsigned char *) &sin->sin_addr;
2476 break;
2478 #ifdef AF_INET6
2479 case AF_INET6:
2481 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2482 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2483 len = sizeof (sin6->sin6_addr) / 2 + 1;
2484 address = Fmake_vector (make_number (len), Qnil);
2485 p = XVECTOR (address);
2486 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2487 for (i = 0; i < len; i++)
2488 p->contents[i] = make_number (ntohs (ip6[i]));
2489 return address;
2491 #endif
2492 #ifdef HAVE_LOCAL_SOCKETS
2493 case AF_LOCAL:
2495 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2496 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2497 /* If the first byte is NUL, the name is a Linux abstract
2498 socket name, and the name can contain embedded NULs. If
2499 it's not, we have a NUL-terminated string. Be careful not
2500 to walk past the end of the object looking for the name
2501 terminator, however. */
2502 if (name_length > 0 && sockun->sun_path[0] != '\0')
2504 const char *terminator
2505 = memchr (sockun->sun_path, '\0', name_length);
2507 if (terminator)
2508 name_length = terminator - (const char *) sockun->sun_path;
2511 return make_unibyte_string (sockun->sun_path, name_length);
2513 #endif
2514 default:
2515 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2516 address = Fcons (make_number (sa->sa_family),
2517 Fmake_vector (make_number (len), Qnil));
2518 p = XVECTOR (XCDR (address));
2519 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2520 break;
2523 i = 0;
2524 while (i < len)
2525 p->contents[i++] = make_number (*cp++);
2527 return address;
2530 /* Convert an internal struct addrinfo to a Lisp object. */
2532 static Lisp_Object
2533 conv_addrinfo_to_lisp (struct addrinfo *res)
2535 Lisp_Object protocol = make_number (res->ai_protocol);
2536 eassert (XINT (protocol) == res->ai_protocol);
2537 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2541 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2543 static ptrdiff_t
2544 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2546 struct Lisp_Vector *p;
2548 if (VECTORP (address))
2550 p = XVECTOR (address);
2551 if (p->header.size == 5)
2553 *familyp = AF_INET;
2554 return sizeof (struct sockaddr_in);
2556 #ifdef AF_INET6
2557 else if (p->header.size == 9)
2559 *familyp = AF_INET6;
2560 return sizeof (struct sockaddr_in6);
2562 #endif
2564 #ifdef HAVE_LOCAL_SOCKETS
2565 else if (STRINGP (address))
2567 *familyp = AF_LOCAL;
2568 return sizeof (struct sockaddr_un);
2570 #endif
2571 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2572 && VECTORP (XCDR (address)))
2574 struct sockaddr *sa;
2575 p = XVECTOR (XCDR (address));
2576 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2577 return 0;
2578 *familyp = XINT (XCAR (address));
2579 return p->header.size + sizeof (sa->sa_family);
2581 return 0;
2584 /* Convert an address object (vector or string) to an internal sockaddr.
2586 The address format has been basically validated by
2587 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2588 it could have come from user data. So if FAMILY is not valid,
2589 we return after zeroing *SA. */
2591 static void
2592 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2594 register struct Lisp_Vector *p;
2595 register unsigned char *cp = NULL;
2596 register int i;
2597 EMACS_INT hostport;
2599 memset (sa, 0, len);
2601 if (VECTORP (address))
2603 p = XVECTOR (address);
2604 if (family == AF_INET)
2606 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2607 len = sizeof (sin->sin_addr) + 1;
2608 hostport = XINT (p->contents[--len]);
2609 sin->sin_port = htons (hostport);
2610 cp = (unsigned char *)&sin->sin_addr;
2611 sa->sa_family = family;
2613 #ifdef AF_INET6
2614 else if (family == AF_INET6)
2616 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2617 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2618 len = sizeof (sin6->sin6_addr) / 2 + 1;
2619 hostport = XINT (p->contents[--len]);
2620 sin6->sin6_port = htons (hostport);
2621 for (i = 0; i < len; i++)
2622 if (INTEGERP (p->contents[i]))
2624 int j = XFASTINT (p->contents[i]) & 0xffff;
2625 ip6[i] = ntohs (j);
2627 sa->sa_family = family;
2628 return;
2630 #endif
2631 else
2632 return;
2634 else if (STRINGP (address))
2636 #ifdef HAVE_LOCAL_SOCKETS
2637 if (family == AF_LOCAL)
2639 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2640 cp = SDATA (address);
2641 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2642 sockun->sun_path[i] = *cp++;
2643 sa->sa_family = family;
2645 #endif
2646 return;
2648 else
2650 p = XVECTOR (XCDR (address));
2651 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2654 for (i = 0; i < len; i++)
2655 if (INTEGERP (p->contents[i]))
2656 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2659 #ifdef DATAGRAM_SOCKETS
2660 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2661 1, 1, 0,
2662 doc: /* Get the current datagram address associated with PROCESS.
2663 If PROCESS is a non-blocking network process that hasn't been fully
2664 set up yet, this function will block until socket setup has completed. */)
2665 (Lisp_Object process)
2667 int channel;
2669 CHECK_PROCESS (process);
2671 if (NETCONN_P (process))
2672 wait_for_socket_fds (process, "process-datagram-address");
2674 if (!DATAGRAM_CONN_P (process))
2675 return Qnil;
2677 channel = XPROCESS (process)->infd;
2678 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2679 datagram_address[channel].len);
2682 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2683 2, 2, 0,
2684 doc: /* Set the datagram address for PROCESS to ADDRESS.
2685 Return nil upon error setting address, ADDRESS otherwise.
2687 If PROCESS is a non-blocking network process that hasn't been fully
2688 set up yet, this function will block until socket setup has completed. */)
2689 (Lisp_Object process, Lisp_Object address)
2691 int channel;
2692 int family;
2693 ptrdiff_t len;
2695 CHECK_PROCESS (process);
2697 if (NETCONN_P (process))
2698 wait_for_socket_fds (process, "set-process-datagram-address");
2700 if (!DATAGRAM_CONN_P (process))
2701 return Qnil;
2703 channel = XPROCESS (process)->infd;
2705 len = get_lisp_to_sockaddr_size (address, &family);
2706 if (len == 0 || datagram_address[channel].len != len)
2707 return Qnil;
2708 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2709 return address;
2711 #endif
2714 static const struct socket_options {
2715 /* The name of this option. Should be lowercase version of option
2716 name without SO_ prefix. */
2717 const char *name;
2718 /* Option level SOL_... */
2719 int optlevel;
2720 /* Option number SO_... */
2721 int optnum;
2722 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2723 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2724 } socket_options[] =
2726 #ifdef SO_BINDTODEVICE
2727 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2728 #endif
2729 #ifdef SO_BROADCAST
2730 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2731 #endif
2732 #ifdef SO_DONTROUTE
2733 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2734 #endif
2735 #ifdef SO_KEEPALIVE
2736 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2737 #endif
2738 #ifdef SO_LINGER
2739 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2740 #endif
2741 #ifdef SO_OOBINLINE
2742 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2743 #endif
2744 #ifdef SO_PRIORITY
2745 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2746 #endif
2747 #ifdef SO_REUSEADDR
2748 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2749 #endif
2750 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2753 /* Set option OPT to value VAL on socket S.
2755 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2756 Signals an error if setting a known option fails.
2759 static int
2760 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2762 char *name;
2763 const struct socket_options *sopt;
2764 int ret = 0;
2766 CHECK_SYMBOL (opt);
2768 name = SSDATA (SYMBOL_NAME (opt));
2769 for (sopt = socket_options; sopt->name; sopt++)
2770 if (strcmp (name, sopt->name) == 0)
2771 break;
2773 switch (sopt->opttype)
2775 case SOPT_BOOL:
2777 int optval;
2778 optval = NILP (val) ? 0 : 1;
2779 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2780 &optval, sizeof (optval));
2781 break;
2784 case SOPT_INT:
2786 int optval;
2787 if (TYPE_RANGED_INTEGERP (int, val))
2788 optval = XINT (val);
2789 else
2790 error ("Bad option value for %s", name);
2791 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2792 &optval, sizeof (optval));
2793 break;
2796 #ifdef SO_BINDTODEVICE
2797 case SOPT_IFNAME:
2799 char devname[IFNAMSIZ + 1];
2801 /* This is broken, at least in the Linux 2.4 kernel.
2802 To unbind, the arg must be a zero integer, not the empty string.
2803 This should work on all systems. KFS. 2003-09-23. */
2804 memset (devname, 0, sizeof devname);
2805 if (STRINGP (val))
2807 char *arg = SSDATA (val);
2808 int len = min (strlen (arg), IFNAMSIZ);
2809 memcpy (devname, arg, len);
2811 else if (!NILP (val))
2812 error ("Bad option value for %s", name);
2813 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2814 devname, IFNAMSIZ);
2815 break;
2817 #endif
2819 #ifdef SO_LINGER
2820 case SOPT_LINGER:
2822 struct linger linger;
2824 linger.l_onoff = 1;
2825 linger.l_linger = 0;
2826 if (TYPE_RANGED_INTEGERP (int, val))
2827 linger.l_linger = XINT (val);
2828 else
2829 linger.l_onoff = NILP (val) ? 0 : 1;
2830 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2831 &linger, sizeof (linger));
2832 break;
2834 #endif
2836 default:
2837 return 0;
2840 if (ret < 0)
2842 int setsockopt_errno = errno;
2843 report_file_errno ("Cannot set network option", list2 (opt, val),
2844 setsockopt_errno);
2847 return (1 << sopt->optbit);
2851 DEFUN ("set-network-process-option",
2852 Fset_network_process_option, Sset_network_process_option,
2853 3, 4, 0,
2854 doc: /* For network process PROCESS set option OPTION to value VALUE.
2855 See `make-network-process' for a list of options and values.
2856 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2857 OPTION is not a supported option, return nil instead; otherwise return t.
2859 If PROCESS is a non-blocking network process that hasn't been fully
2860 set up yet, this function will block until socket setup has completed. */)
2861 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2863 int s;
2864 struct Lisp_Process *p;
2866 CHECK_PROCESS (process);
2867 p = XPROCESS (process);
2868 if (!NETCONN1_P (p))
2869 error ("Process is not a network process");
2871 wait_for_socket_fds (process, "set-network-process-option");
2873 s = p->infd;
2874 if (s < 0)
2875 error ("Process is not running");
2877 if (set_socket_option (s, option, value))
2879 pset_childp (p, Fplist_put (p->childp, option, value));
2880 return Qt;
2883 if (NILP (no_error))
2884 error ("Unknown or unsupported option");
2886 return Qnil;
2890 DEFUN ("serial-process-configure",
2891 Fserial_process_configure,
2892 Sserial_process_configure,
2893 0, MANY, 0,
2894 doc: /* Configure speed, bytesize, etc. of a serial process.
2896 Arguments are specified as keyword/argument pairs. Attributes that
2897 are not given are re-initialized from the process's current
2898 configuration (available via the function `process-contact') or set to
2899 reasonable default values. The following arguments are defined:
2901 :process PROCESS
2902 :name NAME
2903 :buffer BUFFER
2904 :port PORT
2905 -- Any of these arguments can be given to identify the process that is
2906 to be configured. If none of these arguments is given, the current
2907 buffer's process is used.
2909 :speed SPEED -- SPEED is the speed of the serial port in bits per
2910 second, also called baud rate. Any value can be given for SPEED, but
2911 most serial ports work only at a few defined values between 1200 and
2912 115200, with 9600 being the most common value. If SPEED is nil, the
2913 serial port is not configured any further, i.e., all other arguments
2914 are ignored. This may be useful for special serial ports such as
2915 Bluetooth-to-serial converters which can only be configured through AT
2916 commands. A value of nil for SPEED can be used only when passed
2917 through `make-serial-process' or `serial-term'.
2919 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2920 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2922 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2923 `odd' (use odd parity), or the symbol `even' (use even parity). If
2924 PARITY is not given, no parity is used.
2926 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2927 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2928 is not given or nil, 1 stopbit is used.
2930 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2931 flowcontrol to be used, which is either nil (don't use flowcontrol),
2932 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2933 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2934 flowcontrol is used.
2936 `serial-process-configure' is called by `make-serial-process' for the
2937 initial configuration of the serial port.
2939 Examples:
2941 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2943 \(serial-process-configure
2944 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2946 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2948 usage: (serial-process-configure &rest ARGS) */)
2949 (ptrdiff_t nargs, Lisp_Object *args)
2951 struct Lisp_Process *p;
2952 Lisp_Object contact = Qnil;
2953 Lisp_Object proc = Qnil;
2955 contact = Flist (nargs, args);
2957 proc = Fplist_get (contact, QCprocess);
2958 if (NILP (proc))
2959 proc = Fplist_get (contact, QCname);
2960 if (NILP (proc))
2961 proc = Fplist_get (contact, QCbuffer);
2962 if (NILP (proc))
2963 proc = Fplist_get (contact, QCport);
2964 proc = get_process (proc);
2965 p = XPROCESS (proc);
2966 if (!EQ (p->type, Qserial))
2967 error ("Not a serial process");
2969 if (NILP (Fplist_get (p->childp, QCspeed)))
2970 return Qnil;
2972 serial_configure (p, contact);
2973 return Qnil;
2976 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2977 0, MANY, 0,
2978 doc: /* Create and return a serial port process.
2980 In Emacs, serial port connections are represented by process objects,
2981 so input and output work as for subprocesses, and `delete-process'
2982 closes a serial port connection. However, a serial process has no
2983 process id, it cannot be signaled, and the status codes are different
2984 from normal processes.
2986 `make-serial-process' creates a process and a buffer, on which you
2987 probably want to use `process-send-string'. Try \\[serial-term] for
2988 an interactive terminal. See below for examples.
2990 Arguments are specified as keyword/argument pairs. The following
2991 arguments are defined:
2993 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2994 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2995 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2996 the backslashes in strings).
2998 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2999 which this function calls.
3001 :name NAME -- NAME is the name of the process. If NAME is not given,
3002 the value of PORT is used.
3004 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3005 with the process. Process output goes at the end of that buffer,
3006 unless you specify an output stream or filter function to handle the
3007 output. If BUFFER is not given, the value of NAME is used.
3009 :coding CODING -- If CODING is a symbol, it specifies the coding
3010 system used for both reading and writing for this process. If CODING
3011 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3012 ENCODING is used for writing.
3014 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3015 the process is running. If BOOL is not given, query before exiting.
3017 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3018 In the stopped state, a serial process does not accept incoming data,
3019 but you can send outgoing data. The stopped state is cleared by
3020 `continue-process' and set by `stop-process'.
3022 :filter FILTER -- Install FILTER as the process filter.
3024 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3026 :plist PLIST -- Install PLIST as the initial plist of the process.
3028 :bytesize
3029 :parity
3030 :stopbits
3031 :flowcontrol
3032 -- This function calls `serial-process-configure' to handle these
3033 arguments.
3035 The original argument list, possibly modified by later configuration,
3036 is available via the function `process-contact'.
3038 Examples:
3040 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3042 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3044 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3046 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3048 usage: (make-serial-process &rest ARGS) */)
3049 (ptrdiff_t nargs, Lisp_Object *args)
3051 int fd = -1;
3052 Lisp_Object proc, contact, port;
3053 struct Lisp_Process *p;
3054 Lisp_Object name, buffer;
3055 Lisp_Object tem, val;
3056 ptrdiff_t specpdl_count;
3058 if (nargs == 0)
3059 return Qnil;
3061 contact = Flist (nargs, args);
3063 port = Fplist_get (contact, QCport);
3064 if (NILP (port))
3065 error ("No port specified");
3066 CHECK_STRING (port);
3068 if (NILP (Fplist_member (contact, QCspeed)))
3069 error (":speed not specified");
3070 if (!NILP (Fplist_get (contact, QCspeed)))
3071 CHECK_NUMBER (Fplist_get (contact, QCspeed));
3073 name = Fplist_get (contact, QCname);
3074 if (NILP (name))
3075 name = port;
3076 CHECK_STRING (name);
3077 proc = make_process (name);
3078 specpdl_count = SPECPDL_INDEX ();
3079 record_unwind_protect (remove_process, proc);
3080 p = XPROCESS (proc);
3082 fd = serial_open (port);
3083 p->open_fd[SUBPROCESS_STDIN] = fd;
3084 p->infd = fd;
3085 p->outfd = fd;
3086 if (fd > max_desc)
3087 max_desc = fd;
3088 chan_process[fd] = proc;
3090 buffer = Fplist_get (contact, QCbuffer);
3091 if (NILP (buffer))
3092 buffer = name;
3093 buffer = Fget_buffer_create (buffer);
3094 pset_buffer (p, buffer);
3096 pset_childp (p, contact);
3097 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3098 pset_type (p, Qserial);
3099 pset_sentinel (p, Fplist_get (contact, QCsentinel));
3100 pset_filter (p, Fplist_get (contact, QCfilter));
3101 eassert (NILP (p->log));
3102 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3103 p->kill_without_query = 1;
3104 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3105 pset_command (p, Qt);
3106 eassert (! p->pty_flag);
3108 if (!EQ (p->command, Qt))
3109 add_process_read_fd (fd);
3111 if (BUFFERP (buffer))
3113 set_marker_both (p->mark, buffer,
3114 BUF_ZV (XBUFFER (buffer)),
3115 BUF_ZV_BYTE (XBUFFER (buffer)));
3118 tem = Fplist_member (contact, QCcoding);
3119 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3120 tem = Qnil;
3122 val = Qnil;
3123 if (!NILP (tem))
3125 val = XCAR (XCDR (tem));
3126 if (CONSP (val))
3127 val = XCAR (val);
3129 else if (!NILP (Vcoding_system_for_read))
3130 val = Vcoding_system_for_read;
3131 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3132 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3133 val = Qnil;
3134 pset_decode_coding_system (p, val);
3136 val = Qnil;
3137 if (!NILP (tem))
3139 val = XCAR (XCDR (tem));
3140 if (CONSP (val))
3141 val = XCDR (val);
3143 else if (!NILP (Vcoding_system_for_write))
3144 val = Vcoding_system_for_write;
3145 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3146 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3147 val = Qnil;
3148 pset_encode_coding_system (p, val);
3150 setup_process_coding_systems (proc);
3151 pset_decoding_buf (p, empty_unibyte_string);
3152 eassert (p->decoding_carryover == 0);
3153 pset_encoding_buf (p, empty_unibyte_string);
3154 p->inherit_coding_system_flag
3155 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3157 Fserial_process_configure (nargs, args);
3159 specpdl_ptr = specpdl + specpdl_count;
3161 return proc;
3164 static void
3165 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
3166 Lisp_Object service, Lisp_Object name)
3168 Lisp_Object tem;
3169 struct Lisp_Process *p = XPROCESS (proc);
3170 Lisp_Object contact = p->childp;
3171 Lisp_Object coding_systems = Qt;
3172 Lisp_Object val;
3174 tem = Fplist_member (contact, QCcoding);
3175 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3176 tem = Qnil; /* No error message (too late!). */
3178 /* Setup coding systems for communicating with the network stream. */
3179 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3181 if (!NILP (tem))
3183 val = XCAR (XCDR (tem));
3184 if (CONSP (val))
3185 val = XCAR (val);
3187 else if (!NILP (Vcoding_system_for_read))
3188 val = Vcoding_system_for_read;
3189 else if ((!NILP (p->buffer)
3190 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3191 || (NILP (p->buffer)
3192 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3193 /* We dare not decode end-of-line format by setting VAL to
3194 Qraw_text, because the existing Emacs Lisp libraries
3195 assume that they receive bare code including a sequence of
3196 CR LF. */
3197 val = Qnil;
3198 else
3200 if (NILP (host) || NILP (service))
3201 coding_systems = Qnil;
3202 else
3203 coding_systems = CALLN (Ffind_operation_coding_system,
3204 Qopen_network_stream, name, p->buffer,
3205 host, service);
3206 if (CONSP (coding_systems))
3207 val = XCAR (coding_systems);
3208 else if (CONSP (Vdefault_process_coding_system))
3209 val = XCAR (Vdefault_process_coding_system);
3210 else
3211 val = Qnil;
3213 pset_decode_coding_system (p, val);
3215 if (!NILP (tem))
3217 val = XCAR (XCDR (tem));
3218 if (CONSP (val))
3219 val = XCDR (val);
3221 else if (!NILP (Vcoding_system_for_write))
3222 val = Vcoding_system_for_write;
3223 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3224 val = Qnil;
3225 else
3227 if (EQ (coding_systems, Qt))
3229 if (NILP (host) || NILP (service))
3230 coding_systems = Qnil;
3231 else
3232 coding_systems = CALLN (Ffind_operation_coding_system,
3233 Qopen_network_stream, name, p->buffer,
3234 host, service);
3236 if (CONSP (coding_systems))
3237 val = XCDR (coding_systems);
3238 else if (CONSP (Vdefault_process_coding_system))
3239 val = XCDR (Vdefault_process_coding_system);
3240 else
3241 val = Qnil;
3243 pset_encode_coding_system (p, val);
3245 pset_decoding_buf (p, empty_unibyte_string);
3246 p->decoding_carryover = 0;
3247 pset_encoding_buf (p, empty_unibyte_string);
3249 p->inherit_coding_system_flag
3250 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3253 #ifdef HAVE_GNUTLS
3254 static void
3255 finish_after_tls_connection (Lisp_Object proc)
3257 struct Lisp_Process *p = XPROCESS (proc);
3258 Lisp_Object contact = p->childp;
3259 Lisp_Object result = Qt;
3261 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3262 result = call3 (Qnsm_verify_connection,
3263 proc,
3264 Fplist_get (contact, QChost),
3265 Fplist_get (contact, QCservice));
3267 if (NILP (result))
3269 pset_status (p, list2 (Qfailed,
3270 build_string ("The Network Security Manager stopped the connections")));
3271 deactivate_process (proc);
3273 else if (p->outfd < 0)
3275 /* The counterparty may have closed the connection (especially
3276 if the NSM prompt above take a long time), so recheck the file
3277 descriptor here. */
3278 pset_status (p, Qfailed);
3279 deactivate_process (proc);
3281 else if ((fd_callback_info[p->outfd].flags & NON_BLOCKING_CONNECT_FD) == 0)
3283 /* If we cleared the connection wait mask before we did the TLS
3284 setup, then we have to say that the process is finally "open"
3285 here. */
3286 pset_status (p, Qrun);
3287 /* Execute the sentinel here. If we had relied on status_notify
3288 to do it later, it will read input from the process before
3289 calling the sentinel. */
3290 exec_sentinel (proc, build_string ("open\n"));
3293 #endif
3295 static void
3296 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3297 Lisp_Object use_external_socket_p)
3299 ptrdiff_t count = SPECPDL_INDEX ();
3300 int s = -1, outch, inch;
3301 int xerrno = 0;
3302 int family;
3303 struct sockaddr *sa = NULL;
3304 int ret;
3305 ptrdiff_t addrlen;
3306 struct Lisp_Process *p = XPROCESS (proc);
3307 Lisp_Object contact = p->childp;
3308 int optbits = 0;
3309 int socket_to_use = -1;
3311 if (!NILP (use_external_socket_p))
3313 socket_to_use = external_sock_fd;
3315 /* Ensure we don't consume the external socket twice. */
3316 external_sock_fd = -1;
3319 /* Do this in case we never enter the while-loop below. */
3320 s = -1;
3322 while (!NILP (addrinfos))
3324 Lisp_Object addrinfo = XCAR (addrinfos);
3325 addrinfos = XCDR (addrinfos);
3326 int protocol = XINT (XCAR (addrinfo));
3327 Lisp_Object ip_address = XCDR (addrinfo);
3329 #ifdef WINDOWSNT
3330 retry_connect:
3331 #endif
3333 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3334 if (sa)
3335 free (sa);
3336 sa = xmalloc (addrlen);
3337 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3339 s = socket_to_use;
3340 if (s < 0)
3342 int socktype = p->socktype | SOCK_CLOEXEC;
3343 if (p->is_non_blocking_client)
3344 socktype |= SOCK_NONBLOCK;
3345 s = socket (family, socktype, protocol);
3346 if (s < 0)
3348 xerrno = errno;
3349 continue;
3353 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3355 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3356 if (ret < 0)
3358 xerrno = errno;
3359 emacs_close (s);
3360 s = -1;
3361 if (0 <= socket_to_use)
3362 break;
3363 continue;
3367 #ifdef DATAGRAM_SOCKETS
3368 if (!p->is_server && p->socktype == SOCK_DGRAM)
3369 break;
3370 #endif /* DATAGRAM_SOCKETS */
3372 /* Make us close S if quit. */
3373 record_unwind_protect_int (close_file_unwind, s);
3375 /* Parse network options in the arg list. We simply ignore anything
3376 which isn't a known option (including other keywords). An error
3377 is signaled if setting a known option fails. */
3379 Lisp_Object params = contact, key, val;
3381 while (!NILP (params))
3383 key = XCAR (params);
3384 params = XCDR (params);
3385 val = XCAR (params);
3386 params = XCDR (params);
3387 optbits |= set_socket_option (s, key, val);
3391 if (p->is_server)
3393 /* Configure as a server socket. */
3395 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3396 explicit :reuseaddr key to override this. */
3397 #ifdef HAVE_LOCAL_SOCKETS
3398 if (family != AF_LOCAL)
3399 #endif
3400 if (!(optbits & (1 << OPIX_REUSEADDR)))
3402 int optval = 1;
3403 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3404 report_file_error ("Cannot set reuse option on server socket", Qnil);
3407 /* If passed a socket descriptor, it should be already bound. */
3408 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3409 report_file_error ("Cannot bind server socket", Qnil);
3411 #ifdef HAVE_GETSOCKNAME
3412 if (p->port == 0)
3414 struct sockaddr_in sa1;
3415 socklen_t len1 = sizeof (sa1);
3416 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3418 Lisp_Object service;
3419 service = make_number (ntohs (sa1.sin_port));
3420 contact = Fplist_put (contact, QCservice, service);
3421 /* Save the port number so that we can stash it in
3422 the process object later. */
3423 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3426 #endif
3428 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3429 report_file_error ("Cannot listen on server socket", Qnil);
3431 break;
3434 immediate_quit = 1;
3435 QUIT;
3437 ret = connect (s, sa, addrlen);
3438 xerrno = errno;
3440 if (ret == 0 || xerrno == EISCONN)
3442 /* The unwind-protect will be discarded afterwards.
3443 Likewise for immediate_quit. */
3444 break;
3447 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3448 break;
3450 #ifndef WINDOWSNT
3451 if (xerrno == EINTR)
3453 /* Unlike most other syscalls connect() cannot be called
3454 again. (That would return EALREADY.) The proper way to
3455 wait for completion is pselect(). */
3456 int sc;
3457 socklen_t len;
3458 fd_set fdset;
3459 retry_select:
3460 FD_ZERO (&fdset);
3461 FD_SET (s, &fdset);
3462 QUIT;
3463 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3464 if (sc == -1)
3466 if (errno == EINTR)
3467 goto retry_select;
3468 else
3469 report_file_error ("Failed select", Qnil);
3471 eassert (sc > 0);
3473 len = sizeof xerrno;
3474 eassert (FD_ISSET (s, &fdset));
3475 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3476 report_file_error ("Failed getsockopt", Qnil);
3477 if (xerrno == 0)
3478 break;
3479 if (NILP (addrinfos))
3480 report_file_errno ("Failed connect", Qnil, xerrno);
3482 #endif /* !WINDOWSNT */
3484 immediate_quit = 0;
3486 /* Discard the unwind protect closing S. */
3487 specpdl_ptr = specpdl + count;
3488 emacs_close (s);
3489 s = -1;
3490 if (0 <= socket_to_use)
3491 break;
3493 #ifdef WINDOWSNT
3494 if (xerrno == EINTR)
3495 goto retry_connect;
3496 #endif
3499 if (s >= 0)
3501 #ifdef DATAGRAM_SOCKETS
3502 if (p->socktype == SOCK_DGRAM)
3504 if (datagram_address[s].sa)
3505 emacs_abort ();
3507 datagram_address[s].sa = xmalloc (addrlen);
3508 datagram_address[s].len = addrlen;
3509 if (p->is_server)
3511 Lisp_Object remote;
3512 memset (datagram_address[s].sa, 0, addrlen);
3513 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3515 int rfamily;
3516 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3517 if (rlen != 0 && rfamily == family
3518 && rlen == addrlen)
3519 conv_lisp_to_sockaddr (rfamily, remote,
3520 datagram_address[s].sa, rlen);
3523 else
3524 memcpy (datagram_address[s].sa, sa, addrlen);
3526 #endif
3528 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3529 conv_sockaddr_to_lisp (sa, addrlen));
3530 #ifdef HAVE_GETSOCKNAME
3531 if (!p->is_server)
3533 struct sockaddr_in sa1;
3534 socklen_t len1 = sizeof (sa1);
3535 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3536 contact = Fplist_put (contact, QClocal,
3537 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3539 #endif
3542 immediate_quit = 0;
3544 if (s < 0)
3546 /* If non-blocking got this far - and failed - assume non-blocking is
3547 not supported after all. This is probably a wrong assumption, but
3548 the normal blocking calls to open-network-stream handles this error
3549 better. */
3550 if (p->is_non_blocking_client)
3551 return;
3553 report_file_errno ((p->is_server
3554 ? "make server process failed"
3555 : "make client process failed"),
3556 contact, xerrno);
3559 inch = s;
3560 outch = s;
3562 chan_process[inch] = proc;
3564 fcntl (inch, F_SETFL, O_NONBLOCK);
3566 p = XPROCESS (proc);
3567 p->open_fd[SUBPROCESS_STDIN] = inch;
3568 p->infd = inch;
3569 p->outfd = outch;
3571 /* Discard the unwind protect for closing S, if any. */
3572 specpdl_ptr = specpdl + count;
3574 if (p->is_server && p->socktype != SOCK_DGRAM)
3575 pset_status (p, Qlisten);
3577 /* Make the process marker point into the process buffer (if any). */
3578 if (BUFFERP (p->buffer))
3579 set_marker_both (p->mark, p->buffer,
3580 BUF_ZV (XBUFFER (p->buffer)),
3581 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3583 if (p->is_non_blocking_client)
3585 /* We may get here if connect did succeed immediately. However,
3586 in that case, we still need to signal this like a non-blocking
3587 connection. */
3588 if (! (connecting_status (p->status)
3589 && EQ (XCDR (p->status), addrinfos)))
3590 pset_status (p, Fcons (Qconnect, addrinfos));
3591 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3592 add_non_blocking_write_fd (inch);
3594 else
3595 /* A server may have a client filter setting of Qt, but it must
3596 still listen for incoming connects unless it is stopped. */
3597 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3598 || (EQ (p->status, Qlisten) && NILP (p->command)))
3599 add_process_read_fd (inch);
3601 if (inch > max_desc)
3602 max_desc = inch;
3604 /* Set up the masks based on the process filter. */
3605 set_process_filter_masks (p);
3607 setup_process_coding_systems (proc);
3609 #ifdef HAVE_GNUTLS
3610 /* Continue the asynchronous connection. */
3611 if (!NILP (p->gnutls_boot_parameters))
3613 Lisp_Object boot, params = p->gnutls_boot_parameters;
3615 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3616 p->gnutls_boot_parameters = Qnil;
3618 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3619 /* Run sentinels, etc. */
3620 finish_after_tls_connection (proc);
3621 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3623 deactivate_process (proc);
3624 if (NILP (boot))
3625 pset_status (p, list2 (Qfailed,
3626 build_string ("TLS negotiation failed")));
3627 else
3628 pset_status (p, list2 (Qfailed, boot));
3631 #endif
3635 /* Create a network stream/datagram client/server process. Treated
3636 exactly like a normal process when reading and writing. Primary
3637 differences are in status display and process deletion. A network
3638 connection has no PID; you cannot signal it. All you can do is
3639 stop/continue it and deactivate/close it via delete-process. */
3641 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3642 0, MANY, 0,
3643 doc: /* Create and return a network server or client process.
3645 In Emacs, network connections are represented by process objects, so
3646 input and output work as for subprocesses and `delete-process' closes
3647 a network connection. However, a network process has no process id,
3648 it cannot be signaled, and the status codes are different from normal
3649 processes.
3651 Arguments are specified as keyword/argument pairs. The following
3652 arguments are defined:
3654 :name NAME -- NAME is name for process. It is modified if necessary
3655 to make it unique.
3657 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3658 with the process. Process output goes at end of that buffer, unless
3659 you specify an output stream or filter function to handle the output.
3660 BUFFER may be also nil, meaning that this process is not associated
3661 with any buffer.
3663 :host HOST -- HOST is name of the host to connect to, or its IP
3664 address. The symbol `local' specifies the local host. If specified
3665 for a server process, it must be a valid name or address for the local
3666 host, and only clients connecting to that address will be accepted.
3668 :service SERVICE -- SERVICE is name of the service desired, or an
3669 integer specifying a port number to connect to. If SERVICE is t,
3670 a random port number is selected for the server. A port number can
3671 be specified as an integer string, e.g., "80", as well as an integer.
3673 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3674 stream type connection, `datagram' creates a datagram type connection,
3675 `seqpacket' creates a reliable datagram connection.
3677 :family FAMILY -- FAMILY is the address (and protocol) family for the
3678 service specified by HOST and SERVICE. The default (nil) is to use
3679 whatever address family (IPv4 or IPv6) that is defined for the host
3680 and port number specified by HOST and SERVICE. Other address families
3681 supported are:
3682 local -- for a local (i.e. UNIX) address specified by SERVICE.
3683 ipv4 -- use IPv4 address family only.
3684 ipv6 -- use IPv6 address family only.
3686 :local ADDRESS -- ADDRESS is the local address used for the connection.
3687 This parameter is ignored when opening a client process. When specified
3688 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3690 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3691 connection. This parameter is ignored when opening a stream server
3692 process. For a datagram server process, it specifies the initial
3693 setting of the remote datagram address. When specified for a client
3694 process, the FAMILY, HOST, and SERVICE args are ignored.
3696 The format of ADDRESS depends on the address family:
3697 - An IPv4 address is represented as an vector of integers [A B C D P]
3698 corresponding to numeric IP address A.B.C.D and port number P.
3699 - A local address is represented as a string with the address in the
3700 local address space.
3701 - An "unsupported family" address is represented by a cons (F . AV)
3702 where F is the family number and AV is a vector containing the socket
3703 address data with one element per address data byte. Do not rely on
3704 this format in portable code, as it may depend on implementation
3705 defined constants, data sizes, and data structure alignment.
3707 :coding CODING -- If CODING is a symbol, it specifies the coding
3708 system used for both reading and writing for this process. If CODING
3709 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3710 ENCODING is used for writing.
3712 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3713 process, return without waiting for the connection to complete;
3714 instead, the sentinel function will be called with second arg matching
3715 "open" (if successful) or "failed" when the connect completes.
3716 Default is to use a blocking connect (i.e. wait) for stream type
3717 connections.
3719 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3720 running when Emacs is exited.
3722 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3723 In the stopped state, a server process does not accept new
3724 connections, and a client process does not handle incoming traffic.
3725 The stopped state is cleared by `continue-process' and set by
3726 `stop-process'.
3728 :filter FILTER -- Install FILTER as the process filter.
3730 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3731 process filter are multibyte, otherwise they are unibyte.
3732 If this keyword is not specified, the strings are multibyte if
3733 the default value of `enable-multibyte-characters' is non-nil.
3735 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3737 :log LOG -- Install LOG as the server process log function. This
3738 function is called when the server accepts a network connection from a
3739 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3740 is the server process, CLIENT is the new process for the connection,
3741 and MESSAGE is a string.
3743 :plist PLIST -- Install PLIST as the new process's initial plist.
3745 :tls-parameters LIST -- is a list that should be supplied if you're
3746 opening a TLS connection. The first element is the TLS type (either
3747 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3748 be a keyword list accepted by gnutls-boot (as returned by
3749 `gnutls-boot-parameters').
3751 :server QLEN -- if QLEN is non-nil, create a server process for the
3752 specified FAMILY, SERVICE, and connection type (stream or datagram).
3753 If QLEN is an integer, it is used as the max. length of the server's
3754 pending connection queue (also known as the backlog); the default
3755 queue length is 5. Default is to create a client process.
3757 The following network options can be specified for this connection:
3759 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3760 :dontroute BOOL -- Only send to directly connected hosts.
3761 :keepalive BOOL -- Send keep-alive messages on network stream.
3762 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3763 :oobinline BOOL -- Place out-of-band data in receive data stream.
3764 :priority INT -- Set protocol defined priority for sent packets.
3765 :reuseaddr BOOL -- Allow reusing a recently used local address
3766 (this is allowed by default for a server process).
3767 :bindtodevice NAME -- bind to interface NAME. Using this may require
3768 special privileges on some systems.
3769 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3770 been passed to Emacs. If Emacs wasn't
3771 passed a socket, this option is silently
3772 ignored.
3775 Consult the relevant system programmer's manual pages for more
3776 information on using these options.
3779 A server process will listen for and accept connections from clients.
3780 When a client connection is accepted, a new network process is created
3781 for the connection with the following parameters:
3783 - The client's process name is constructed by concatenating the server
3784 process's NAME and a client identification string.
3785 - If the FILTER argument is non-nil, the client process will not get a
3786 separate process buffer; otherwise, the client's process buffer is a newly
3787 created buffer named after the server process's BUFFER name or process
3788 NAME concatenated with the client identification string.
3789 - The connection type and the process filter and sentinel parameters are
3790 inherited from the server process's TYPE, FILTER and SENTINEL.
3791 - The client process's contact info is set according to the client's
3792 addressing information (typically an IP address and a port number).
3793 - The client process's plist is initialized from the server's plist.
3795 Notice that the FILTER and SENTINEL args are never used directly by
3796 the server process. Also, the BUFFER argument is not used directly by
3797 the server process, but via the optional :log function, accepted (and
3798 failed) connections may be logged in the server process's buffer.
3800 The original argument list, modified with the actual connection
3801 information, is available via the `process-contact' function.
3803 usage: (make-network-process &rest ARGS) */)
3804 (ptrdiff_t nargs, Lisp_Object *args)
3806 Lisp_Object proc;
3807 Lisp_Object contact;
3808 struct Lisp_Process *p;
3809 const char *portstring;
3810 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3811 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3812 #ifdef HAVE_LOCAL_SOCKETS
3813 struct sockaddr_un address_un;
3814 #endif
3815 EMACS_INT port = 0;
3816 Lisp_Object tem;
3817 Lisp_Object name, buffer, host, service, address;
3818 Lisp_Object filter, sentinel, use_external_socket_p;
3819 Lisp_Object addrinfos = Qnil;
3820 int socktype;
3821 int family = -1;
3822 enum { any_protocol = 0 };
3823 #ifdef HAVE_GETADDRINFO_A
3824 struct gaicb *dns_request = NULL;
3825 #endif
3826 ptrdiff_t count = SPECPDL_INDEX ();
3828 if (nargs == 0)
3829 return Qnil;
3831 /* Save arguments for process-contact and clone-process. */
3832 contact = Flist (nargs, args);
3834 #ifdef WINDOWSNT
3835 /* Ensure socket support is loaded if available. */
3836 init_winsock (TRUE);
3837 #endif
3839 /* :type TYPE (nil: stream, datagram */
3840 tem = Fplist_get (contact, QCtype);
3841 if (NILP (tem))
3842 socktype = SOCK_STREAM;
3843 #ifdef DATAGRAM_SOCKETS
3844 else if (EQ (tem, Qdatagram))
3845 socktype = SOCK_DGRAM;
3846 #endif
3847 #ifdef HAVE_SEQPACKET
3848 else if (EQ (tem, Qseqpacket))
3849 socktype = SOCK_SEQPACKET;
3850 #endif
3851 else
3852 error ("Unsupported connection type");
3854 name = Fplist_get (contact, QCname);
3855 buffer = Fplist_get (contact, QCbuffer);
3856 filter = Fplist_get (contact, QCfilter);
3857 sentinel = Fplist_get (contact, QCsentinel);
3858 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3860 CHECK_STRING (name);
3862 /* :local ADDRESS or :remote ADDRESS */
3863 tem = Fplist_get (contact, QCserver);
3864 if (NILP (tem))
3865 address = Fplist_get (contact, QCremote);
3866 else
3867 address = Fplist_get (contact, QClocal);
3868 if (!NILP (address))
3870 host = service = Qnil;
3872 if (!get_lisp_to_sockaddr_size (address, &family))
3873 error ("Malformed :address");
3875 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3876 goto open_socket;
3879 /* :family FAMILY -- nil (for Inet), local, or integer. */
3880 tem = Fplist_get (contact, QCfamily);
3881 if (NILP (tem))
3883 #ifdef AF_INET6
3884 family = AF_UNSPEC;
3885 #else
3886 family = AF_INET;
3887 #endif
3889 #ifdef HAVE_LOCAL_SOCKETS
3890 else if (EQ (tem, Qlocal))
3891 family = AF_LOCAL;
3892 #endif
3893 #ifdef AF_INET6
3894 else if (EQ (tem, Qipv6))
3895 family = AF_INET6;
3896 #endif
3897 else if (EQ (tem, Qipv4))
3898 family = AF_INET;
3899 else if (TYPE_RANGED_INTEGERP (int, tem))
3900 family = XINT (tem);
3901 else
3902 error ("Unknown address family");
3904 /* :service SERVICE -- string, integer (port number), or t (random port). */
3905 service = Fplist_get (contact, QCservice);
3907 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3908 host = Fplist_get (contact, QChost);
3909 if (NILP (host))
3911 /* The "connection" function gets it bind info from the address we're
3912 given, so use this dummy address if nothing is specified. */
3913 #ifdef HAVE_LOCAL_SOCKETS
3914 if (family != AF_LOCAL)
3915 #endif
3916 host = build_string ("127.0.0.1");
3918 else
3920 if (EQ (host, Qlocal))
3921 /* Depending on setup, "localhost" may map to different IPv4 and/or
3922 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3923 host = build_string ("127.0.0.1");
3924 CHECK_STRING (host);
3927 #ifdef HAVE_LOCAL_SOCKETS
3928 if (family == AF_LOCAL)
3930 if (!NILP (host))
3932 message (":family local ignores the :host property");
3933 contact = Fplist_put (contact, QChost, Qnil);
3934 host = Qnil;
3936 CHECK_STRING (service);
3937 if (sizeof address_un.sun_path <= SBYTES (service))
3938 error ("Service name too long");
3939 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3940 goto open_socket;
3942 #endif
3944 /* Slow down polling to every ten seconds.
3945 Some kernels have a bug which causes retrying connect to fail
3946 after a connect. Polling can interfere with gethostbyname too. */
3947 #ifdef POLL_FOR_INPUT
3948 if (socktype != SOCK_DGRAM)
3950 record_unwind_protect_void (run_all_atimers);
3951 bind_polling_period (10);
3953 #endif
3955 if (!NILP (host))
3957 /* SERVICE can either be a string or int.
3958 Convert to a C string for later use by getaddrinfo. */
3959 if (EQ (service, Qt))
3961 portstring = "0";
3962 portstringlen = 1;
3964 else if (INTEGERP (service))
3966 portstring = portbuf;
3967 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3969 else
3971 CHECK_STRING (service);
3972 portstring = SSDATA (service);
3973 portstringlen = SBYTES (service);
3977 #ifdef HAVE_GETADDRINFO_A
3978 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3980 ptrdiff_t hostlen = SBYTES (host);
3981 struct req
3983 struct gaicb gaicb;
3984 struct addrinfo hints;
3985 char str[FLEXIBLE_ARRAY_MEMBER];
3986 } *req = xmalloc (FLEXSIZEOF (struct req, str,
3987 hostlen + 1 + portstringlen + 1));
3988 dns_request = &req->gaicb;
3989 dns_request->ar_name = req->str;
3990 dns_request->ar_service = req->str + hostlen + 1;
3991 dns_request->ar_request = &req->hints;
3992 dns_request->ar_result = NULL;
3993 memset (&req->hints, 0, sizeof req->hints);
3994 req->hints.ai_family = family;
3995 req->hints.ai_socktype = socktype;
3996 strcpy (req->str, SSDATA (host));
3997 strcpy (req->str + hostlen + 1, portstring);
3999 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4000 if (ret)
4001 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
4003 goto open_socket;
4005 #endif /* HAVE_GETADDRINFO_A */
4007 /* If we have a host, use getaddrinfo to resolve both host and service.
4008 Otherwise, use getservbyname to lookup the service. */
4010 if (!NILP (host))
4012 struct addrinfo *res, *lres;
4013 int ret;
4015 immediate_quit = 1;
4016 QUIT;
4018 struct addrinfo hints;
4019 memset (&hints, 0, sizeof hints);
4020 hints.ai_family = family;
4021 hints.ai_socktype = socktype;
4023 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4024 if (ret)
4025 #ifdef HAVE_GAI_STRERROR
4027 synchronize_system_messages_locale ();
4028 char const *str = gai_strerror (ret);
4029 if (! NILP (Vlocale_coding_system))
4030 str = SSDATA (code_convert_string_norecord
4031 (build_string (str), Vlocale_coding_system, 0));
4032 error ("%s/%s %s", SSDATA (host), portstring, str);
4034 #else
4035 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4036 #endif
4037 immediate_quit = 0;
4039 for (lres = res; lres; lres = lres->ai_next)
4040 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4042 addrinfos = Fnreverse (addrinfos);
4044 freeaddrinfo (res);
4046 goto open_socket;
4049 /* No hostname has been specified (e.g., a local server process). */
4051 if (EQ (service, Qt))
4052 port = 0;
4053 else if (INTEGERP (service))
4054 port = XINT (service);
4055 else
4057 CHECK_STRING (service);
4059 port = -1;
4060 if (SBYTES (service) != 0)
4062 /* Allow the service to be a string containing the port number,
4063 because that's allowed if you have getaddrbyname. */
4064 char *service_end;
4065 long int lport = strtol (SSDATA (service), &service_end, 10);
4066 if (service_end == SSDATA (service) + SBYTES (service))
4067 port = lport;
4068 else
4070 struct servent *svc_info
4071 = getservbyname (SSDATA (service),
4072 socktype == SOCK_DGRAM ? "udp" : "tcp");
4073 if (svc_info)
4074 port = ntohs (svc_info->s_port);
4079 if (! (0 <= port && port < 1 << 16))
4081 AUTO_STRING (unknown_service, "Unknown service: %s");
4082 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4085 open_socket:
4087 if (!NILP (buffer))
4088 buffer = Fget_buffer_create (buffer);
4090 /* Unwind bind_polling_period. */
4091 unbind_to (count, Qnil);
4093 proc = make_process (name);
4094 record_unwind_protect (remove_process, proc);
4095 p = XPROCESS (proc);
4096 pset_childp (p, contact);
4097 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4098 pset_type (p, Qnetwork);
4100 pset_buffer (p, buffer);
4101 pset_sentinel (p, sentinel);
4102 pset_filter (p, filter);
4103 pset_log (p, Fplist_get (contact, QClog));
4104 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4105 p->kill_without_query = 1;
4106 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4107 pset_command (p, Qt);
4108 eassert (p->pid == 0);
4109 p->backlog = 5;
4110 eassert (! p->is_non_blocking_client);
4111 eassert (! p->is_server);
4112 p->port = port;
4113 p->socktype = socktype;
4114 #ifdef HAVE_GETADDRINFO_A
4115 eassert (! p->dns_request);
4116 #endif
4117 #ifdef HAVE_GNUTLS
4118 tem = Fplist_get (contact, QCtls_parameters);
4119 CHECK_LIST (tem);
4120 p->gnutls_boot_parameters = tem;
4121 #endif
4123 set_network_socket_coding_system (proc, host, service, name);
4125 /* :server BOOL */
4126 tem = Fplist_get (contact, QCserver);
4127 if (!NILP (tem))
4129 /* Don't support network sockets when non-blocking mode is
4130 not available, since a blocked Emacs is not useful. */
4131 p->is_server = true;
4132 if (TYPE_RANGED_INTEGERP (int, tem))
4133 p->backlog = XINT (tem);
4136 /* :nowait BOOL */
4137 if (!p->is_server && socktype != SOCK_DGRAM
4138 && !NILP (Fplist_get (contact, QCnowait)))
4139 p->is_non_blocking_client = true;
4141 bool postpone_connection = false;
4142 #ifdef HAVE_GETADDRINFO_A
4143 /* With async address resolution, the list of addresses is empty, so
4144 postpone connecting to the server. */
4145 if (!p->is_server && NILP (addrinfos))
4147 p->dns_request = dns_request;
4148 p->status = list1 (Qconnect);
4149 postpone_connection = true;
4151 #endif
4152 if (! postpone_connection)
4153 connect_network_socket (proc, addrinfos, use_external_socket_p);
4155 specpdl_ptr = specpdl + count;
4156 return proc;
4160 #ifdef HAVE_NET_IF_H
4162 #ifdef SIOCGIFCONF
4163 static Lisp_Object
4164 network_interface_list (void)
4166 struct ifconf ifconf;
4167 struct ifreq *ifreq;
4168 void *buf = NULL;
4169 ptrdiff_t buf_size = 512;
4170 int s;
4171 Lisp_Object res;
4172 ptrdiff_t count;
4174 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4175 if (s < 0)
4176 return Qnil;
4177 count = SPECPDL_INDEX ();
4178 record_unwind_protect_int (close_file_unwind, s);
4182 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4183 ifconf.ifc_buf = buf;
4184 ifconf.ifc_len = buf_size;
4185 if (ioctl (s, SIOCGIFCONF, &ifconf))
4187 emacs_close (s);
4188 xfree (buf);
4189 return Qnil;
4192 while (ifconf.ifc_len == buf_size);
4194 res = unbind_to (count, Qnil);
4195 ifreq = ifconf.ifc_req;
4196 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4198 struct ifreq *ifq = ifreq;
4199 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4200 #define SIZEOF_IFREQ(sif) \
4201 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4202 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4204 int len = SIZEOF_IFREQ (ifq);
4205 #else
4206 int len = sizeof (*ifreq);
4207 #endif
4208 char namebuf[sizeof (ifq->ifr_name) + 1];
4209 ifreq = (struct ifreq *) ((char *) ifreq + len);
4211 if (ifq->ifr_addr.sa_family != AF_INET)
4212 continue;
4214 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4215 namebuf[sizeof (ifq->ifr_name)] = 0;
4216 res = Fcons (Fcons (build_string (namebuf),
4217 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4218 sizeof (struct sockaddr))),
4219 res);
4222 xfree (buf);
4223 return res;
4225 #endif /* SIOCGIFCONF */
4227 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4229 struct ifflag_def {
4230 int flag_bit;
4231 const char *flag_sym;
4234 static const struct ifflag_def ifflag_table[] = {
4235 #ifdef IFF_UP
4236 { IFF_UP, "up" },
4237 #endif
4238 #ifdef IFF_BROADCAST
4239 { IFF_BROADCAST, "broadcast" },
4240 #endif
4241 #ifdef IFF_DEBUG
4242 { IFF_DEBUG, "debug" },
4243 #endif
4244 #ifdef IFF_LOOPBACK
4245 { IFF_LOOPBACK, "loopback" },
4246 #endif
4247 #ifdef IFF_POINTOPOINT
4248 { IFF_POINTOPOINT, "pointopoint" },
4249 #endif
4250 #ifdef IFF_RUNNING
4251 { IFF_RUNNING, "running" },
4252 #endif
4253 #ifdef IFF_NOARP
4254 { IFF_NOARP, "noarp" },
4255 #endif
4256 #ifdef IFF_PROMISC
4257 { IFF_PROMISC, "promisc" },
4258 #endif
4259 #ifdef IFF_NOTRAILERS
4260 #ifdef NS_IMPL_COCOA
4261 /* Really means smart, notrailers is obsolete. */
4262 { IFF_NOTRAILERS, "smart" },
4263 #else
4264 { IFF_NOTRAILERS, "notrailers" },
4265 #endif
4266 #endif
4267 #ifdef IFF_ALLMULTI
4268 { IFF_ALLMULTI, "allmulti" },
4269 #endif
4270 #ifdef IFF_MASTER
4271 { IFF_MASTER, "master" },
4272 #endif
4273 #ifdef IFF_SLAVE
4274 { IFF_SLAVE, "slave" },
4275 #endif
4276 #ifdef IFF_MULTICAST
4277 { IFF_MULTICAST, "multicast" },
4278 #endif
4279 #ifdef IFF_PORTSEL
4280 { IFF_PORTSEL, "portsel" },
4281 #endif
4282 #ifdef IFF_AUTOMEDIA
4283 { IFF_AUTOMEDIA, "automedia" },
4284 #endif
4285 #ifdef IFF_DYNAMIC
4286 { IFF_DYNAMIC, "dynamic" },
4287 #endif
4288 #ifdef IFF_OACTIVE
4289 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4290 #endif
4291 #ifdef IFF_SIMPLEX
4292 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4293 #endif
4294 #ifdef IFF_LINK0
4295 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4296 #endif
4297 #ifdef IFF_LINK1
4298 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4299 #endif
4300 #ifdef IFF_LINK2
4301 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4302 #endif
4303 { 0, 0 }
4306 static Lisp_Object
4307 network_interface_info (Lisp_Object ifname)
4309 struct ifreq rq;
4310 Lisp_Object res = Qnil;
4311 Lisp_Object elt;
4312 int s;
4313 bool any = 0;
4314 ptrdiff_t count;
4315 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4316 && defined HAVE_GETIFADDRS && defined LLADDR)
4317 struct ifaddrs *ifap;
4318 #endif
4320 CHECK_STRING (ifname);
4322 if (sizeof rq.ifr_name <= SBYTES (ifname))
4323 error ("interface name too long");
4324 lispstpcpy (rq.ifr_name, ifname);
4326 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4327 if (s < 0)
4328 return Qnil;
4329 count = SPECPDL_INDEX ();
4330 record_unwind_protect_int (close_file_unwind, s);
4332 elt = Qnil;
4333 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4334 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4336 int flags = rq.ifr_flags;
4337 const struct ifflag_def *fp;
4338 int fnum;
4340 /* If flags is smaller than int (i.e. short) it may have the high bit set
4341 due to IFF_MULTICAST. In that case, sign extending it into
4342 an int is wrong. */
4343 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4344 flags = (unsigned short) rq.ifr_flags;
4346 any = 1;
4347 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4349 if (flags & fp->flag_bit)
4351 elt = Fcons (intern (fp->flag_sym), elt);
4352 flags -= fp->flag_bit;
4355 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4357 if (flags & 1)
4359 elt = Fcons (make_number (fnum), elt);
4363 #endif
4364 res = Fcons (elt, res);
4366 elt = Qnil;
4367 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4368 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4370 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4371 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4372 int n;
4374 any = 1;
4375 for (n = 0; n < 6; n++)
4376 p->contents[n] = make_number (((unsigned char *)
4377 &rq.ifr_hwaddr.sa_data[0])
4378 [n]);
4379 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4381 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4382 if (getifaddrs (&ifap) != -1)
4384 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4385 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4386 struct ifaddrs *it;
4388 for (it = ifap; it != NULL; it = it->ifa_next)
4390 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4391 unsigned char linkaddr[6];
4392 int n;
4394 if (it->ifa_addr->sa_family != AF_LINK
4395 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4396 || sdl->sdl_alen != 6)
4397 continue;
4399 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4400 for (n = 0; n < 6; n++)
4401 p->contents[n] = make_number (linkaddr[n]);
4403 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4404 break;
4407 #ifdef HAVE_FREEIFADDRS
4408 freeifaddrs (ifap);
4409 #endif
4411 #endif /* HAVE_GETIFADDRS && LLADDR */
4413 res = Fcons (elt, res);
4415 elt = Qnil;
4416 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4417 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4419 any = 1;
4420 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4421 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4422 #else
4423 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4424 #endif
4426 #endif
4427 res = Fcons (elt, res);
4429 elt = Qnil;
4430 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4431 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4433 any = 1;
4434 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4436 #endif
4437 res = Fcons (elt, res);
4439 elt = Qnil;
4440 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4441 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4443 any = 1;
4444 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4446 #endif
4447 res = Fcons (elt, res);
4449 return unbind_to (count, any ? res : Qnil);
4451 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4452 #endif /* defined (HAVE_NET_IF_H) */
4454 DEFUN ("network-interface-list", Fnetwork_interface_list,
4455 Snetwork_interface_list, 0, 0, 0,
4456 doc: /* Return an alist of all network interfaces and their network address.
4457 Each element is a cons, the car of which is a string containing the
4458 interface name, and the cdr is the network address in internal
4459 format; see the description of ADDRESS in `make-network-process'.
4461 If the information is not available, return nil. */)
4462 (void)
4464 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4465 return network_interface_list ();
4466 #else
4467 return Qnil;
4468 #endif
4471 DEFUN ("network-interface-info", Fnetwork_interface_info,
4472 Snetwork_interface_info, 1, 1, 0,
4473 doc: /* Return information about network interface named IFNAME.
4474 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4475 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4476 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4477 FLAGS is the current flags of the interface.
4479 Data that is unavailable is returned as nil. */)
4480 (Lisp_Object ifname)
4482 #if ((defined HAVE_NET_IF_H \
4483 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4484 || defined SIOCGIFFLAGS)) \
4485 || defined WINDOWSNT)
4486 return network_interface_info (ifname);
4487 #else
4488 return Qnil;
4489 #endif
4492 /* Turn off input and output for process PROC. */
4494 static void
4495 deactivate_process (Lisp_Object proc)
4497 int inchannel;
4498 struct Lisp_Process *p = XPROCESS (proc);
4499 int i;
4501 #ifdef HAVE_GNUTLS
4502 /* Delete GnuTLS structures in PROC, if any. */
4503 emacs_gnutls_deinit (proc);
4504 #endif /* HAVE_GNUTLS */
4506 if (p->read_output_delay > 0)
4508 if (--process_output_delay_count < 0)
4509 process_output_delay_count = 0;
4510 p->read_output_delay = 0;
4511 p->read_output_skip = 0;
4514 /* Beware SIGCHLD hereabouts. */
4516 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4517 close_process_fd (&p->open_fd[i]);
4519 inchannel = p->infd;
4520 if (inchannel >= 0)
4522 p->infd = -1;
4523 p->outfd = -1;
4524 #ifdef DATAGRAM_SOCKETS
4525 if (DATAGRAM_CHAN_P (inchannel))
4527 xfree (datagram_address[inchannel].sa);
4528 datagram_address[inchannel].sa = 0;
4529 datagram_address[inchannel].len = 0;
4531 #endif
4532 chan_process[inchannel] = Qnil;
4533 delete_read_fd (inchannel);
4534 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4535 delete_write_fd (inchannel);
4536 if (inchannel == max_desc)
4537 recompute_max_desc ();
4542 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4543 0, 4, 0,
4544 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4545 It is given to their filter functions.
4546 Optional argument PROCESS means do not return until output has been
4547 received from PROCESS.
4549 Optional second argument SECONDS and third argument MILLISEC
4550 specify a timeout; return after that much time even if there is
4551 no subprocess output. If SECONDS is a floating point number,
4552 it specifies a fractional number of seconds to wait.
4553 The MILLISEC argument is obsolete and should be avoided.
4555 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4556 from PROCESS only, suspending reading output from other processes.
4557 If JUST-THIS-ONE is an integer, don't run any timers either.
4558 Return non-nil if we received any output from PROCESS (or, if PROCESS
4559 is nil, from any process) before the timeout expired. */)
4560 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4561 Lisp_Object just_this_one)
4563 intmax_t secs;
4564 int nsecs;
4566 if (! NILP (process))
4568 CHECK_PROCESS (process);
4569 struct Lisp_Process *proc = XPROCESS (process);
4571 /* Can't wait for a process that is dedicated to a different
4572 thread. */
4573 if (!EQ (proc->thread, Qnil) && !EQ (proc->thread, Fcurrent_thread ()))
4574 error ("Attempt to accept output from process %s locked to thread %s",
4575 SDATA (proc->name), SDATA (XTHREAD (proc->thread)->name));
4577 else
4578 just_this_one = Qnil;
4580 if (!NILP (millisec))
4581 { /* Obsolete calling convention using integers rather than floats. */
4582 CHECK_NUMBER (millisec);
4583 if (NILP (seconds))
4584 seconds = make_float (XINT (millisec) / 1000.0);
4585 else
4587 CHECK_NUMBER (seconds);
4588 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4592 secs = 0;
4593 nsecs = -1;
4595 if (!NILP (seconds))
4597 if (INTEGERP (seconds))
4599 if (XINT (seconds) > 0)
4601 secs = XINT (seconds);
4602 nsecs = 0;
4605 else if (FLOATP (seconds))
4607 if (XFLOAT_DATA (seconds) > 0)
4609 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4610 secs = min (t.tv_sec, WAIT_READING_MAX);
4611 nsecs = t.tv_nsec;
4614 else
4615 wrong_type_argument (Qnumberp, seconds);
4617 else if (! NILP (process))
4618 nsecs = 0;
4620 return
4621 ((wait_reading_process_output (secs, nsecs, 0, 0,
4622 Qnil,
4623 !NILP (process) ? XPROCESS (process) : NULL,
4624 (NILP (just_this_one) ? 0
4625 : !INTEGERP (just_this_one) ? 1 : -1))
4626 <= 0)
4627 ? Qnil : Qt);
4630 /* Accept a connection for server process SERVER on CHANNEL. */
4632 static EMACS_INT connect_counter = 0;
4634 static void
4635 server_accept_connection (Lisp_Object server, int channel)
4637 Lisp_Object proc, caller, name, buffer;
4638 Lisp_Object contact, host, service;
4639 struct Lisp_Process *ps = XPROCESS (server);
4640 struct Lisp_Process *p;
4641 int s;
4642 union u_sockaddr {
4643 struct sockaddr sa;
4644 struct sockaddr_in in;
4645 #ifdef AF_INET6
4646 struct sockaddr_in6 in6;
4647 #endif
4648 #ifdef HAVE_LOCAL_SOCKETS
4649 struct sockaddr_un un;
4650 #endif
4651 } saddr;
4652 socklen_t len = sizeof saddr;
4653 ptrdiff_t count;
4655 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4657 if (s < 0)
4659 int code = errno;
4660 if (!would_block (code) && !NILP (ps->log))
4661 call3 (ps->log, server, Qnil,
4662 concat3 (build_string ("accept failed with code"),
4663 Fnumber_to_string (make_number (code)),
4664 build_string ("\n")));
4665 return;
4668 count = SPECPDL_INDEX ();
4669 record_unwind_protect_int (close_file_unwind, s);
4671 connect_counter++;
4673 /* Setup a new process to handle the connection. */
4675 /* Generate a unique identification of the caller, and build contact
4676 information for this process. */
4677 host = Qt;
4678 service = Qnil;
4679 switch (saddr.sa.sa_family)
4681 case AF_INET:
4683 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4685 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4686 host = CALLN (Fformat, ipv4_format,
4687 make_number (ip[0]), make_number (ip[1]),
4688 make_number (ip[2]), make_number (ip[3]));
4689 service = make_number (ntohs (saddr.in.sin_port));
4690 AUTO_STRING (caller_format, " <%s:%d>");
4691 caller = CALLN (Fformat, caller_format, host, service);
4693 break;
4695 #ifdef AF_INET6
4696 case AF_INET6:
4698 Lisp_Object args[9];
4699 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4700 int i;
4702 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4703 args[0] = ipv6_format;
4704 for (i = 0; i < 8; i++)
4705 args[i + 1] = make_number (ntohs (ip6[i]));
4706 host = CALLMANY (Fformat, args);
4707 service = make_number (ntohs (saddr.in.sin_port));
4708 AUTO_STRING (caller_format, " <[%s]:%d>");
4709 caller = CALLN (Fformat, caller_format, host, service);
4711 break;
4712 #endif
4714 #ifdef HAVE_LOCAL_SOCKETS
4715 case AF_LOCAL:
4716 #endif
4717 default:
4718 caller = Fnumber_to_string (make_number (connect_counter));
4719 AUTO_STRING (space_less_than, " <");
4720 AUTO_STRING (greater_than, ">");
4721 caller = concat3 (space_less_than, caller, greater_than);
4722 break;
4725 /* Create a new buffer name for this process if it doesn't have a
4726 filter. The new buffer name is based on the buffer name or
4727 process name of the server process concatenated with the caller
4728 identification. */
4730 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4731 || EQ (ps->filter, Qt)))
4732 buffer = Qnil;
4733 else
4735 buffer = ps->buffer;
4736 if (!NILP (buffer))
4737 buffer = Fbuffer_name (buffer);
4738 else
4739 buffer = ps->name;
4740 if (!NILP (buffer))
4742 buffer = concat2 (buffer, caller);
4743 buffer = Fget_buffer_create (buffer);
4747 /* Generate a unique name for the new server process. Combine the
4748 server process name with the caller identification. */
4750 name = concat2 (ps->name, caller);
4751 proc = make_process (name);
4753 chan_process[s] = proc;
4755 fcntl (s, F_SETFL, O_NONBLOCK);
4757 p = XPROCESS (proc);
4759 /* Build new contact information for this setup. */
4760 contact = Fcopy_sequence (ps->childp);
4761 contact = Fplist_put (contact, QCserver, Qnil);
4762 contact = Fplist_put (contact, QChost, host);
4763 if (!NILP (service))
4764 contact = Fplist_put (contact, QCservice, service);
4765 contact = Fplist_put (contact, QCremote,
4766 conv_sockaddr_to_lisp (&saddr.sa, len));
4767 #ifdef HAVE_GETSOCKNAME
4768 len = sizeof saddr;
4769 if (getsockname (s, &saddr.sa, &len) == 0)
4770 contact = Fplist_put (contact, QClocal,
4771 conv_sockaddr_to_lisp (&saddr.sa, len));
4772 #endif
4774 pset_childp (p, contact);
4775 pset_plist (p, Fcopy_sequence (ps->plist));
4776 pset_type (p, Qnetwork);
4778 pset_buffer (p, buffer);
4779 pset_sentinel (p, ps->sentinel);
4780 pset_filter (p, ps->filter);
4781 eassert (NILP (p->command));
4782 eassert (p->pid == 0);
4784 /* Discard the unwind protect for closing S. */
4785 specpdl_ptr = specpdl + count;
4787 p->open_fd[SUBPROCESS_STDIN] = s;
4788 p->infd = s;
4789 p->outfd = s;
4790 pset_status (p, Qrun);
4792 /* Client processes for accepted connections are not stopped initially. */
4793 if (!EQ (p->filter, Qt))
4794 add_process_read_fd (s);
4795 if (s > max_desc)
4796 max_desc = s;
4798 /* Setup coding system for new process based on server process.
4799 This seems to be the proper thing to do, as the coding system
4800 of the new process should reflect the settings at the time the
4801 server socket was opened; not the current settings. */
4803 pset_decode_coding_system (p, ps->decode_coding_system);
4804 pset_encode_coding_system (p, ps->encode_coding_system);
4805 setup_process_coding_systems (proc);
4807 pset_decoding_buf (p, empty_unibyte_string);
4808 eassert (p->decoding_carryover == 0);
4809 pset_encoding_buf (p, empty_unibyte_string);
4811 p->inherit_coding_system_flag
4812 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4814 AUTO_STRING (dash, "-");
4815 AUTO_STRING (nl, "\n");
4816 Lisp_Object host_string = STRINGP (host) ? host : dash;
4818 if (!NILP (ps->log))
4820 AUTO_STRING (accept_from, "accept from ");
4821 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4824 AUTO_STRING (open_from, "open from ");
4825 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4828 #ifdef HAVE_GETADDRINFO_A
4829 static Lisp_Object
4830 check_for_dns (Lisp_Object proc)
4832 struct Lisp_Process *p = XPROCESS (proc);
4833 Lisp_Object addrinfos = Qnil;
4835 /* Sanity check. */
4836 if (! p->dns_request)
4837 return Qnil;
4839 int ret = gai_error (p->dns_request);
4840 if (ret == EAI_INPROGRESS)
4841 return Qt;
4843 /* We got a response. */
4844 if (ret == 0)
4846 struct addrinfo *res;
4848 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4849 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4851 addrinfos = Fnreverse (addrinfos);
4853 /* The DNS lookup failed. */
4854 else if (connecting_status (p->status))
4856 deactivate_process (proc);
4857 pset_status (p, (list2
4858 (Qfailed,
4859 concat3 (build_string ("Name lookup of "),
4860 build_string (p->dns_request->ar_name),
4861 build_string (" failed")))));
4864 free_dns_request (proc);
4866 /* This process should not already be connected (or killed). */
4867 if (! connecting_status (p->status))
4868 return Qnil;
4870 return addrinfos;
4873 #endif /* HAVE_GETADDRINFO_A */
4875 static void
4876 wait_for_socket_fds (Lisp_Object process, char const *name)
4878 while (XPROCESS (process)->infd < 0
4879 && connecting_status (XPROCESS (process)->status))
4881 add_to_log ("Waiting for socket from %s...", build_string (name));
4882 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4886 static void
4887 wait_while_connecting (Lisp_Object process)
4889 while (connecting_status (XPROCESS (process)->status))
4891 add_to_log ("Waiting for connection...");
4892 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4896 static void
4897 wait_for_tls_negotiation (Lisp_Object process)
4899 #ifdef HAVE_GNUTLS
4900 while (XPROCESS (process)->gnutls_p
4901 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4903 add_to_log ("Waiting for TLS...");
4904 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4906 #endif
4909 static void
4910 wait_reading_process_output_unwind (int data)
4912 clear_waiting_thread_info ();
4913 waiting_for_user_input_p = data;
4916 /* This is here so breakpoints can be put on it. */
4917 static void
4918 wait_reading_process_output_1 (void)
4922 /* Read and dispose of subprocess output while waiting for timeout to
4923 elapse and/or keyboard input to be available.
4925 TIME_LIMIT is:
4926 timeout in seconds
4927 If negative, gobble data immediately available but don't wait for any.
4929 NSECS is:
4930 an additional duration to wait, measured in nanoseconds
4931 If TIME_LIMIT is zero, then:
4932 If NSECS == 0, there is no limit.
4933 If NSECS > 0, the timeout consists of NSECS only.
4934 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4936 READ_KBD is:
4937 0 to ignore keyboard input, or
4938 1 to return when input is available, or
4939 -1 meaning caller will actually read the input, so don't throw to
4940 the quit handler
4942 DO_DISPLAY means redisplay should be done to show subprocess
4943 output that arrives.
4945 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4946 (and gobble terminal input into the buffer if any arrives).
4948 If WAIT_PROC is specified, wait until something arrives from that
4949 process.
4951 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4952 (suspending output from other processes). A negative value
4953 means don't run any timers either.
4955 Return positive if we received input from WAIT_PROC (or from any
4956 process if WAIT_PROC is null), zero if we attempted to receive
4957 input but got none, and negative if we didn't even try. */
4960 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4961 bool do_display,
4962 Lisp_Object wait_for_cell,
4963 struct Lisp_Process *wait_proc, int just_wait_proc)
4965 int channel, nfds;
4966 fd_set Available;
4967 fd_set Writeok;
4968 bool check_write;
4969 int check_delay;
4970 bool no_avail;
4971 int xerrno;
4972 Lisp_Object proc;
4973 struct timespec timeout, end_time, timer_delay;
4974 struct timespec got_output_end_time = invalid_timespec ();
4975 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4976 int got_some_output = -1;
4977 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4978 bool retry_for_async;
4979 #endif
4980 ptrdiff_t count = SPECPDL_INDEX ();
4982 /* Close to the current time if known, an invalid timespec otherwise. */
4983 struct timespec now = invalid_timespec ();
4985 eassert (wait_proc == NULL
4986 || EQ (wait_proc->thread, Qnil)
4987 || XTHREAD (wait_proc->thread) == current_thread);
4989 FD_ZERO (&Available);
4990 FD_ZERO (&Writeok);
4992 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4993 && !(CONSP (wait_proc->status)
4994 && EQ (XCAR (wait_proc->status), Qexit)))
4995 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4997 record_unwind_protect_int (wait_reading_process_output_unwind,
4998 waiting_for_user_input_p);
4999 waiting_for_user_input_p = read_kbd;
5001 if (TYPE_MAXIMUM (time_t) < time_limit)
5002 time_limit = TYPE_MAXIMUM (time_t);
5004 if (time_limit < 0 || nsecs < 0)
5005 wait = MINIMUM;
5006 else if (time_limit > 0 || nsecs > 0)
5008 wait = TIMEOUT;
5009 now = current_timespec ();
5010 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5012 else
5013 wait = INFINITY;
5015 while (1)
5017 bool process_skipped = false;
5019 /* If calling from keyboard input, do not quit
5020 since we want to return C-g as an input character.
5021 Otherwise, do pending quit if requested. */
5022 if (read_kbd >= 0)
5023 QUIT;
5024 else if (pending_signals)
5025 process_pending_signals ();
5027 /* Exit now if the cell we're waiting for became non-nil. */
5028 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5029 break;
5031 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5033 Lisp_Object process_list_head, aproc;
5034 struct Lisp_Process *p;
5036 retry_for_async = false;
5037 FOR_EACH_PROCESS(process_list_head, aproc)
5039 p = XPROCESS (aproc);
5041 if (! wait_proc || p == wait_proc)
5043 #ifdef HAVE_GETADDRINFO_A
5044 /* Check for pending DNS requests. */
5045 if (p->dns_request)
5047 Lisp_Object addrinfos = check_for_dns (aproc);
5048 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5049 connect_network_socket (aproc, addrinfos, Qnil);
5050 else
5051 retry_for_async = true;
5053 #endif
5054 #ifdef HAVE_GNUTLS
5055 /* Continue TLS negotiation. */
5056 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5057 && p->is_non_blocking_client)
5059 gnutls_try_handshake (p);
5060 p->gnutls_handshakes_tried++;
5062 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5064 gnutls_verify_boot (aproc, Qnil);
5065 finish_after_tls_connection (aproc);
5067 else
5069 retry_for_async = true;
5070 if (p->gnutls_handshakes_tried
5071 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5073 deactivate_process (aproc);
5074 pset_status (p, list2 (Qfailed,
5075 build_string ("TLS negotiation failed")));
5079 #endif
5083 #endif /* GETADDRINFO_A or GNUTLS */
5085 /* Compute time from now till when time limit is up. */
5086 /* Exit if already run out. */
5087 if (wait == TIMEOUT)
5089 if (!timespec_valid_p (now))
5090 now = current_timespec ();
5091 if (timespec_cmp (end_time, now) <= 0)
5092 break;
5093 timeout = timespec_sub (end_time, now);
5095 else
5096 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5098 /* Normally we run timers here.
5099 But not if wait_for_cell; in those cases,
5100 the wait is supposed to be short,
5101 and those callers cannot handle running arbitrary Lisp code here. */
5102 if (NILP (wait_for_cell)
5103 && just_wait_proc >= 0)
5107 unsigned old_timers_run = timers_run;
5108 struct buffer *old_buffer = current_buffer;
5109 Lisp_Object old_window = selected_window;
5111 timer_delay = timer_check ();
5113 /* If a timer has run, this might have changed buffers
5114 an alike. Make read_key_sequence aware of that. */
5115 if (timers_run != old_timers_run
5116 && (old_buffer != current_buffer
5117 || !EQ (old_window, selected_window))
5118 && waiting_for_user_input_p == -1)
5119 record_asynch_buffer_change ();
5121 if (timers_run != old_timers_run && do_display)
5122 /* We must retry, since a timer may have requeued itself
5123 and that could alter the time_delay. */
5124 redisplay_preserve_echo_area (9);
5125 else
5126 break;
5128 while (!detect_input_pending ());
5130 /* If there is unread keyboard input, also return. */
5131 if (read_kbd != 0
5132 && requeued_events_pending_p ())
5133 break;
5135 /* This is so a breakpoint can be put here. */
5136 if (!timespec_valid_p (timer_delay))
5137 wait_reading_process_output_1 ();
5140 /* Cause C-g and alarm signals to take immediate action,
5141 and cause input available signals to zero out timeout.
5143 It is important that we do this before checking for process
5144 activity. If we get a SIGCHLD after the explicit checks for
5145 process activity, timeout is the only way we will know. */
5146 if (read_kbd < 0)
5147 set_waiting_for_input (&timeout);
5149 /* If status of something has changed, and no input is
5150 available, notify the user of the change right away. After
5151 this explicit check, we'll let the SIGCHLD handler zap
5152 timeout to get our attention. */
5153 if (update_tick != process_tick)
5155 fd_set Atemp;
5156 fd_set Ctemp;
5158 if (kbd_on_hold_p ())
5159 FD_ZERO (&Atemp);
5160 else
5161 compute_input_wait_mask (&Atemp);
5162 compute_write_mask (&Ctemp);
5164 timeout = make_timespec (0, 0);
5165 if ((thread_select (pselect, max_desc + 1,
5166 &Atemp,
5167 (num_pending_connects > 0 ? &Ctemp : NULL),
5168 NULL, &timeout, NULL)
5169 <= 0))
5171 /* It's okay for us to do this and then continue with
5172 the loop, since timeout has already been zeroed out. */
5173 clear_waiting_for_input ();
5174 got_some_output = status_notify (NULL, wait_proc);
5175 if (do_display) redisplay_preserve_echo_area (13);
5179 /* Don't wait for output from a non-running process. Just
5180 read whatever data has already been received. */
5181 if (wait_proc && wait_proc->raw_status_new)
5182 update_status (wait_proc);
5183 if (wait_proc
5184 && ! EQ (wait_proc->status, Qrun)
5185 && ! connecting_status (wait_proc->status))
5187 bool read_some_bytes = false;
5189 clear_waiting_for_input ();
5191 /* If data can be read from the process, do so until exhausted. */
5192 if (wait_proc->infd >= 0)
5194 XSETPROCESS (proc, wait_proc);
5196 while (true)
5198 int nread = read_process_output (proc, wait_proc->infd);
5199 if (nread < 0)
5201 if (errno == EIO || would_block (errno))
5202 break;
5204 else
5206 if (got_some_output < nread)
5207 got_some_output = nread;
5208 if (nread == 0)
5209 break;
5210 read_some_bytes = true;
5215 if (read_some_bytes && do_display)
5216 redisplay_preserve_echo_area (10);
5218 break;
5221 /* Wait till there is something to do. */
5223 if (wait_proc && just_wait_proc)
5225 if (wait_proc->infd < 0) /* Terminated. */
5226 break;
5227 FD_SET (wait_proc->infd, &Available);
5228 check_delay = 0;
5229 check_write = 0;
5231 else if (!NILP (wait_for_cell))
5233 compute_non_process_wait_mask (&Available);
5234 check_delay = 0;
5235 check_write = 0;
5237 else
5239 if (! read_kbd)
5240 compute_non_keyboard_wait_mask (&Available);
5241 else
5242 compute_input_wait_mask (&Available);
5243 compute_write_mask (&Writeok);
5244 check_delay = wait_proc ? 0 : process_output_delay_count;
5245 check_write = true;
5248 /* If frame size has changed or the window is newly mapped,
5249 redisplay now, before we start to wait. There is a race
5250 condition here; if a SIGIO arrives between now and the select
5251 and indicates that a frame is trashed, the select may block
5252 displaying a trashed screen. */
5253 if (frame_garbaged && do_display)
5255 clear_waiting_for_input ();
5256 redisplay_preserve_echo_area (11);
5257 if (read_kbd < 0)
5258 set_waiting_for_input (&timeout);
5261 /* Skip the `select' call if input is available and we're
5262 waiting for keyboard input or a cell change (which can be
5263 triggered by processing X events). In the latter case, set
5264 nfds to 1 to avoid breaking the loop. */
5265 no_avail = 0;
5266 if ((read_kbd || !NILP (wait_for_cell))
5267 && detect_input_pending ())
5269 nfds = read_kbd ? 0 : 1;
5270 no_avail = 1;
5271 FD_ZERO (&Available);
5273 else
5275 /* Set the timeout for adaptive read buffering if any
5276 process has non-zero read_output_skip and non-zero
5277 read_output_delay, and we are not reading output for a
5278 specific process. It is not executed if
5279 Vprocess_adaptive_read_buffering is nil. */
5280 if (process_output_skip && check_delay > 0)
5282 int adaptive_nsecs = timeout.tv_nsec;
5283 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5284 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5285 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5287 proc = chan_process[channel];
5288 if (NILP (proc))
5289 continue;
5290 /* Find minimum non-zero read_output_delay among the
5291 processes with non-zero read_output_skip. */
5292 if (XPROCESS (proc)->read_output_delay > 0)
5294 check_delay--;
5295 if (!XPROCESS (proc)->read_output_skip)
5296 continue;
5297 FD_CLR (channel, &Available);
5298 process_skipped = true;
5299 XPROCESS (proc)->read_output_skip = 0;
5300 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5301 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5304 timeout = make_timespec (0, adaptive_nsecs);
5305 process_output_skip = 0;
5308 /* If we've got some output and haven't limited our timeout
5309 with adaptive read buffering, limit it. */
5310 if (got_some_output > 0 && !process_skipped
5311 && (timeout.tv_sec
5312 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5313 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5316 if (NILP (wait_for_cell) && just_wait_proc >= 0
5317 && timespec_valid_p (timer_delay)
5318 && timespec_cmp (timer_delay, timeout) < 0)
5320 if (!timespec_valid_p (now))
5321 now = current_timespec ();
5322 struct timespec timeout_abs = timespec_add (now, timeout);
5323 if (!timespec_valid_p (got_output_end_time)
5324 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5325 got_output_end_time = timeout_abs;
5326 timeout = timer_delay;
5328 else
5329 got_output_end_time = invalid_timespec ();
5331 /* NOW can become inaccurate if time can pass during pselect. */
5332 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5333 now = invalid_timespec ();
5335 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5336 if (retry_for_async
5337 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5339 timeout.tv_sec = 0;
5340 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5342 #endif
5344 /* HAVE_GLIB builds call thread_select in xgselect.c. */
5345 #ifdef HAVE_GLIB
5346 nfds = xg_select (max_desc + 1,
5347 &Available, (check_write ? &Writeok : 0),
5348 NULL, &timeout, NULL);
5349 #else /* !HAVE_GLIB */
5350 nfds = thread_select (
5351 # ifdef HAVE_NS
5352 ns_select
5353 # else
5354 pselect
5355 # endif
5356 , max_desc + 1,
5357 &Available,
5358 (check_write ? &Writeok : 0),
5359 NULL, &timeout, NULL);
5360 #endif /* !HAVE_GLIB */
5362 #ifdef HAVE_GNUTLS
5363 /* GnuTLS buffers data internally. In lowat mode it leaves
5364 some data in the TCP buffers so that select works, but
5365 with custom pull/push functions we need to check if some
5366 data is available in the buffers manually. */
5367 if (nfds == 0)
5369 fd_set tls_available;
5370 int set = 0;
5372 FD_ZERO (&tls_available);
5373 if (! wait_proc)
5375 /* We're not waiting on a specific process, so loop
5376 through all the channels and check for data.
5377 This is a workaround needed for some versions of
5378 the gnutls library -- 2.12.14 has been confirmed
5379 to need it. See
5380 http://comments.gmane.org/gmane.emacs.devel/145074 */
5381 for (channel = 0; channel < FD_SETSIZE; ++channel)
5382 if (! NILP (chan_process[channel]))
5384 struct Lisp_Process *p =
5385 XPROCESS (chan_process[channel]);
5386 if (p && p->gnutls_p && p->gnutls_state
5387 && ((emacs_gnutls_record_check_pending
5388 (p->gnutls_state))
5389 > 0))
5391 nfds++;
5392 eassert (p->infd == channel);
5393 FD_SET (p->infd, &tls_available);
5394 set++;
5398 else
5400 /* Check this specific channel. */
5401 if (wait_proc->gnutls_p /* Check for valid process. */
5402 && wait_proc->gnutls_state
5403 /* Do we have pending data? */
5404 && ((emacs_gnutls_record_check_pending
5405 (wait_proc->gnutls_state))
5406 > 0))
5408 nfds = 1;
5409 eassert (0 <= wait_proc->infd);
5410 /* Set to Available. */
5411 FD_SET (wait_proc->infd, &tls_available);
5412 set++;
5415 if (set)
5416 Available = tls_available;
5418 #endif
5421 xerrno = errno;
5423 /* Make C-g and alarm signals set flags again. */
5424 clear_waiting_for_input ();
5426 /* If we woke up due to SIGWINCH, actually change size now. */
5427 do_pending_window_change (0);
5429 if (nfds == 0)
5431 /* Exit the main loop if we've passed the requested timeout,
5432 or aren't skipping processes and got some output and
5433 haven't lowered our timeout due to timers or SIGIO and
5434 have waited a long amount of time due to repeated
5435 timers. */
5436 struct timespec huge_timespec
5437 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5438 struct timespec cmp_time = huge_timespec;
5439 if (wait < TIMEOUT)
5440 break;
5441 if (wait == TIMEOUT)
5442 cmp_time = end_time;
5443 if (!process_skipped && got_some_output > 0
5444 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5446 if (!timespec_valid_p (got_output_end_time))
5447 break;
5448 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5449 cmp_time = got_output_end_time;
5451 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5453 now = current_timespec ();
5454 if (timespec_cmp (cmp_time, now) <= 0)
5455 break;
5459 if (nfds < 0)
5461 if (xerrno == EINTR)
5462 no_avail = 1;
5463 else if (xerrno == EBADF)
5464 emacs_abort ();
5465 else
5466 report_file_errno ("Failed select", Qnil, xerrno);
5469 /* Check for keyboard input. */
5470 /* If there is any, return immediately
5471 to give it higher priority than subprocesses. */
5473 if (read_kbd != 0)
5475 unsigned old_timers_run = timers_run;
5476 struct buffer *old_buffer = current_buffer;
5477 Lisp_Object old_window = selected_window;
5478 bool leave = false;
5480 if (detect_input_pending_run_timers (do_display))
5482 swallow_events (do_display);
5483 if (detect_input_pending_run_timers (do_display))
5484 leave = true;
5487 /* If a timer has run, this might have changed buffers
5488 an alike. Make read_key_sequence aware of that. */
5489 if (timers_run != old_timers_run
5490 && waiting_for_user_input_p == -1
5491 && (old_buffer != current_buffer
5492 || !EQ (old_window, selected_window)))
5493 record_asynch_buffer_change ();
5495 if (leave)
5496 break;
5499 /* If there is unread keyboard input, also return. */
5500 if (read_kbd != 0
5501 && requeued_events_pending_p ())
5502 break;
5504 /* If we are not checking for keyboard input now,
5505 do process events (but don't run any timers).
5506 This is so that X events will be processed.
5507 Otherwise they may have to wait until polling takes place.
5508 That would causes delays in pasting selections, for example.
5510 (We used to do this only if wait_for_cell.) */
5511 if (read_kbd == 0 && detect_input_pending ())
5513 swallow_events (do_display);
5514 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5515 if (detect_input_pending ())
5516 break;
5517 #endif
5520 /* Exit now if the cell we're waiting for became non-nil. */
5521 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5522 break;
5524 #ifdef USABLE_SIGIO
5525 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5526 go read it. This can happen with X on BSD after logging out.
5527 In that case, there really is no input and no SIGIO,
5528 but select says there is input. */
5530 if (read_kbd && interrupt_input
5531 && keyboard_bit_set (&Available) && ! noninteractive)
5532 handle_input_available_signal (SIGIO);
5533 #endif
5535 /* If checking input just got us a size-change event from X,
5536 obey it now if we should. */
5537 if (read_kbd || ! NILP (wait_for_cell))
5538 do_pending_window_change (0);
5540 /* Check for data from a process. */
5541 if (no_avail || nfds == 0)
5542 continue;
5544 for (channel = 0; channel <= max_desc; ++channel)
5546 struct fd_callback_data *d = &fd_callback_info[channel];
5547 if (d->func
5548 && ((d->flags & FOR_READ
5549 && FD_ISSET (channel, &Available))
5550 || ((d->flags & FOR_WRITE)
5551 && FD_ISSET (channel, &Writeok))))
5552 d->func (channel, d->data);
5555 for (channel = 0; channel <= max_desc; channel++)
5557 if (FD_ISSET (channel, &Available)
5558 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5559 == PROCESS_FD))
5561 int nread;
5563 /* If waiting for this channel, arrange to return as
5564 soon as no more input to be processed. No more
5565 waiting. */
5566 proc = chan_process[channel];
5567 if (NILP (proc))
5568 continue;
5570 /* If this is a server stream socket, accept connection. */
5571 if (EQ (XPROCESS (proc)->status, Qlisten))
5573 server_accept_connection (proc, channel);
5574 continue;
5577 /* Read data from the process, starting with our
5578 buffered-ahead character if we have one. */
5580 nread = read_process_output (proc, channel);
5581 if ((!wait_proc || wait_proc == XPROCESS (proc))
5582 && got_some_output < nread)
5583 got_some_output = nread;
5584 if (nread > 0)
5586 /* Vacuum up any leftovers without waiting. */
5587 if (wait_proc == XPROCESS (proc))
5588 wait = MINIMUM;
5589 /* Since read_process_output can run a filter,
5590 which can call accept-process-output,
5591 don't try to read from any other processes
5592 before doing the select again. */
5593 FD_ZERO (&Available);
5595 if (do_display)
5596 redisplay_preserve_echo_area (12);
5598 else if (nread == -1 && would_block (errno))
5600 #ifdef WINDOWSNT
5601 /* FIXME: Is this special case still needed? */
5602 /* Note that we cannot distinguish between no input
5603 available now and a closed pipe.
5604 With luck, a closed pipe will be accompanied by
5605 subprocess termination and SIGCHLD. */
5606 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5607 && !PIPECONN_P (proc))
5609 #endif
5610 #ifdef HAVE_PTYS
5611 /* On some OSs with ptys, when the process on one end of
5612 a pty exits, the other end gets an error reading with
5613 errno = EIO instead of getting an EOF (0 bytes read).
5614 Therefore, if we get an error reading and errno =
5615 EIO, just continue, because the child process has
5616 exited and should clean itself up soon (e.g. when we
5617 get a SIGCHLD). */
5618 else if (nread == -1 && errno == EIO)
5620 struct Lisp_Process *p = XPROCESS (proc);
5622 /* Clear the descriptor now, so we only raise the
5623 signal once. */
5624 delete_read_fd (channel);
5626 if (p->pid == -2)
5628 /* If the EIO occurs on a pty, the SIGCHLD handler's
5629 waitpid call will not find the process object to
5630 delete. Do it here. */
5631 p->tick = ++process_tick;
5632 pset_status (p, Qfailed);
5635 #endif /* HAVE_PTYS */
5636 /* If we can detect process termination, don't consider the
5637 process gone just because its pipe is closed. */
5638 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5639 && !PIPECONN_P (proc))
5641 else if (nread == 0 && PIPECONN_P (proc))
5643 /* Preserve status of processes already terminated. */
5644 XPROCESS (proc)->tick = ++process_tick;
5645 deactivate_process (proc);
5646 if (EQ (XPROCESS (proc)->status, Qrun))
5647 pset_status (XPROCESS (proc),
5648 list2 (Qexit, make_number (0)));
5650 else
5652 /* Preserve status of processes already terminated. */
5653 XPROCESS (proc)->tick = ++process_tick;
5654 deactivate_process (proc);
5655 if (XPROCESS (proc)->raw_status_new)
5656 update_status (XPROCESS (proc));
5657 if (EQ (XPROCESS (proc)->status, Qrun))
5658 pset_status (XPROCESS (proc),
5659 list2 (Qexit, make_number (256)));
5662 if (FD_ISSET (channel, &Writeok)
5663 && (fd_callback_info[channel].flags
5664 & NON_BLOCKING_CONNECT_FD) != 0)
5666 struct Lisp_Process *p;
5668 delete_write_fd (channel);
5670 proc = chan_process[channel];
5671 if (NILP (proc))
5672 continue;
5674 p = XPROCESS (proc);
5676 #ifndef WINDOWSNT
5678 socklen_t xlen = sizeof (xerrno);
5679 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5680 xerrno = errno;
5682 #else
5683 /* On MS-Windows, getsockopt clears the error for the
5684 entire process, which may not be the right thing; see
5685 w32.c. Use getpeername instead. */
5687 struct sockaddr pname;
5688 socklen_t pnamelen = sizeof (pname);
5690 /* If connection failed, getpeername will fail. */
5691 xerrno = 0;
5692 if (getpeername (channel, &pname, &pnamelen) < 0)
5694 /* Obtain connect failure code through error slippage. */
5695 char dummy;
5696 xerrno = errno;
5697 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5698 xerrno = errno;
5701 #endif
5702 if (xerrno)
5704 Lisp_Object addrinfos
5705 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5706 if (!NILP (addrinfos))
5707 XSETCDR (p->status, XCDR (addrinfos));
5708 else
5710 p->tick = ++process_tick;
5711 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5713 deactivate_process (proc);
5714 if (!NILP (addrinfos))
5715 connect_network_socket (proc, addrinfos, Qnil);
5717 else
5719 #ifdef HAVE_GNUTLS
5720 /* If we have an incompletely set up TLS connection,
5721 then defer the sentinel signaling until
5722 later. */
5723 if (NILP (p->gnutls_boot_parameters)
5724 && !p->gnutls_p)
5725 #endif
5727 pset_status (p, Qrun);
5728 /* Execute the sentinel here. If we had relied on
5729 status_notify to do it later, it will read input
5730 from the process before calling the sentinel. */
5731 exec_sentinel (proc, build_string ("open\n"));
5734 if (0 <= p->infd && !EQ (p->filter, Qt)
5735 && !EQ (p->command, Qt))
5736 add_process_read_fd (p->infd);
5739 } /* End for each file descriptor. */
5740 } /* End while exit conditions not met. */
5742 unbind_to (count, Qnil);
5744 /* If calling from keyboard input, do not quit
5745 since we want to return C-g as an input character.
5746 Otherwise, do pending quit if requested. */
5747 if (read_kbd >= 0)
5749 /* Prevent input_pending from remaining set if we quit. */
5750 clear_input_pending ();
5751 QUIT;
5754 return got_some_output;
5757 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5759 static Lisp_Object
5760 read_process_output_call (Lisp_Object fun_and_args)
5762 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5765 static Lisp_Object
5766 read_process_output_error_handler (Lisp_Object error_val)
5768 cmd_error_internal (error_val, "error in process filter: ");
5769 Vinhibit_quit = Qt;
5770 update_echo_area ();
5771 Fsleep_for (make_number (2), Qnil);
5772 return Qt;
5775 static void
5776 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5777 ssize_t nbytes,
5778 struct coding_system *coding);
5780 /* Read pending output from the process channel,
5781 starting with our buffered-ahead character if we have one.
5782 Yield number of decoded characters read.
5784 This function reads at most 4096 characters.
5785 If you want to read all available subprocess output,
5786 you must call it repeatedly until it returns zero.
5788 The characters read are decoded according to PROC's coding-system
5789 for decoding. */
5791 static int
5792 read_process_output (Lisp_Object proc, int channel)
5794 ssize_t nbytes;
5795 struct Lisp_Process *p = XPROCESS (proc);
5796 struct coding_system *coding = proc_decode_coding_system[channel];
5797 int carryover = p->decoding_carryover;
5798 enum { readmax = 4096 };
5799 ptrdiff_t count = SPECPDL_INDEX ();
5800 Lisp_Object odeactivate;
5801 char chars[sizeof coding->carryover + readmax];
5803 if (carryover)
5804 /* See the comment above. */
5805 memcpy (chars, SDATA (p->decoding_buf), carryover);
5807 #ifdef DATAGRAM_SOCKETS
5808 /* We have a working select, so proc_buffered_char is always -1. */
5809 if (DATAGRAM_CHAN_P (channel))
5811 socklen_t len = datagram_address[channel].len;
5812 nbytes = recvfrom (channel, chars + carryover, readmax,
5813 0, datagram_address[channel].sa, &len);
5815 else
5816 #endif
5818 bool buffered = proc_buffered_char[channel] >= 0;
5819 if (buffered)
5821 chars[carryover] = proc_buffered_char[channel];
5822 proc_buffered_char[channel] = -1;
5824 #ifdef HAVE_GNUTLS
5825 if (p->gnutls_p && p->gnutls_state)
5826 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5827 readmax - buffered);
5828 else
5829 #endif
5830 nbytes = emacs_read (channel, chars + carryover + buffered,
5831 readmax - buffered);
5832 if (nbytes > 0 && p->adaptive_read_buffering)
5834 int delay = p->read_output_delay;
5835 if (nbytes < 256)
5837 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5839 if (delay == 0)
5840 process_output_delay_count++;
5841 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5844 else if (delay > 0 && nbytes == readmax - buffered)
5846 delay -= READ_OUTPUT_DELAY_INCREMENT;
5847 if (delay == 0)
5848 process_output_delay_count--;
5850 p->read_output_delay = delay;
5851 if (delay)
5853 p->read_output_skip = 1;
5854 process_output_skip = 1;
5857 nbytes += buffered;
5858 nbytes += buffered && nbytes <= 0;
5861 p->decoding_carryover = 0;
5863 /* At this point, NBYTES holds number of bytes just received
5864 (including the one in proc_buffered_char[channel]). */
5865 if (nbytes <= 0)
5867 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5868 return nbytes;
5869 coding->mode |= CODING_MODE_LAST_BLOCK;
5872 /* Now set NBYTES how many bytes we must decode. */
5873 nbytes += carryover;
5875 odeactivate = Vdeactivate_mark;
5876 /* There's no good reason to let process filters change the current
5877 buffer, and many callers of accept-process-output, sit-for, and
5878 friends don't expect current-buffer to be changed from under them. */
5879 record_unwind_current_buffer ();
5881 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5883 /* Handling the process output should not deactivate the mark. */
5884 Vdeactivate_mark = odeactivate;
5886 unbind_to (count, Qnil);
5887 return nbytes;
5890 static void
5891 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5892 ssize_t nbytes,
5893 struct coding_system *coding)
5895 Lisp_Object outstream = p->filter;
5896 Lisp_Object text;
5897 bool outer_running_asynch_code = running_asynch_code;
5898 int waiting = waiting_for_user_input_p;
5900 #if 0
5901 Lisp_Object obuffer, okeymap;
5902 XSETBUFFER (obuffer, current_buffer);
5903 okeymap = BVAR (current_buffer, keymap);
5904 #endif
5906 /* We inhibit quit here instead of just catching it so that
5907 hitting ^G when a filter happens to be running won't screw
5908 it up. */
5909 specbind (Qinhibit_quit, Qt);
5910 specbind (Qlast_nonmenu_event, Qt);
5912 /* In case we get recursively called,
5913 and we already saved the match data nonrecursively,
5914 save the same match data in safely recursive fashion. */
5915 if (outer_running_asynch_code)
5917 Lisp_Object tem;
5918 /* Don't clobber the CURRENT match data, either! */
5919 tem = Fmatch_data (Qnil, Qnil, Qnil);
5920 restore_search_regs ();
5921 record_unwind_save_match_data ();
5922 Fset_match_data (tem, Qt);
5925 /* For speed, if a search happens within this code,
5926 save the match data in a special nonrecursive fashion. */
5927 running_asynch_code = 1;
5929 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5930 text = coding->dst_object;
5931 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5932 /* A new coding system might be found. */
5933 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5935 pset_decode_coding_system (p, Vlast_coding_system_used);
5937 /* Don't call setup_coding_system for
5938 proc_decode_coding_system[channel] here. It is done in
5939 detect_coding called via decode_coding above. */
5941 /* If a coding system for encoding is not yet decided, we set
5942 it as the same as coding-system for decoding.
5944 But, before doing that we must check if
5945 proc_encode_coding_system[p->outfd] surely points to a
5946 valid memory because p->outfd will be changed once EOF is
5947 sent to the process. */
5948 if (NILP (p->encode_coding_system) && p->outfd >= 0
5949 && proc_encode_coding_system[p->outfd])
5951 pset_encode_coding_system
5952 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5953 setup_coding_system (p->encode_coding_system,
5954 proc_encode_coding_system[p->outfd]);
5958 if (coding->carryover_bytes > 0)
5960 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5961 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5962 memcpy (SDATA (p->decoding_buf), coding->carryover,
5963 coding->carryover_bytes);
5964 p->decoding_carryover = coding->carryover_bytes;
5966 if (SBYTES (text) > 0)
5967 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5968 sometimes it's simply wrong to wrap (e.g. when called from
5969 accept-process-output). */
5970 internal_condition_case_1 (read_process_output_call,
5971 list3 (outstream, make_lisp_proc (p), text),
5972 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5973 read_process_output_error_handler);
5975 /* If we saved the match data nonrecursively, restore it now. */
5976 restore_search_regs ();
5977 running_asynch_code = outer_running_asynch_code;
5979 /* Restore waiting_for_user_input_p as it was
5980 when we were called, in case the filter clobbered it. */
5981 waiting_for_user_input_p = waiting;
5983 #if 0 /* Call record_asynch_buffer_change unconditionally,
5984 because we might have changed minor modes or other things
5985 that affect key bindings. */
5986 if (! EQ (Fcurrent_buffer (), obuffer)
5987 || ! EQ (current_buffer->keymap, okeymap))
5988 #endif
5989 /* But do it only if the caller is actually going to read events.
5990 Otherwise there's no need to make him wake up, and it could
5991 cause trouble (for example it would make sit_for return). */
5992 if (waiting_for_user_input_p == -1)
5993 record_asynch_buffer_change ();
5996 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5997 Sinternal_default_process_filter, 2, 2, 0,
5998 doc: /* Function used as default process filter.
5999 This inserts the process's output into its buffer, if there is one.
6000 Otherwise it discards the output. */)
6001 (Lisp_Object proc, Lisp_Object text)
6003 struct Lisp_Process *p;
6004 ptrdiff_t opoint;
6006 CHECK_PROCESS (proc);
6007 p = XPROCESS (proc);
6008 CHECK_STRING (text);
6010 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6012 Lisp_Object old_read_only;
6013 ptrdiff_t old_begv, old_zv;
6014 ptrdiff_t old_begv_byte, old_zv_byte;
6015 ptrdiff_t before, before_byte;
6016 ptrdiff_t opoint_byte;
6017 struct buffer *b;
6019 Fset_buffer (p->buffer);
6020 opoint = PT;
6021 opoint_byte = PT_BYTE;
6022 old_read_only = BVAR (current_buffer, read_only);
6023 old_begv = BEGV;
6024 old_zv = ZV;
6025 old_begv_byte = BEGV_BYTE;
6026 old_zv_byte = ZV_BYTE;
6028 bset_read_only (current_buffer, Qnil);
6030 /* Insert new output into buffer at the current end-of-output
6031 marker, thus preserving logical ordering of input and output. */
6032 if (XMARKER (p->mark)->buffer)
6033 set_point_from_marker (p->mark);
6034 else
6035 SET_PT_BOTH (ZV, ZV_BYTE);
6036 before = PT;
6037 before_byte = PT_BYTE;
6039 /* If the output marker is outside of the visible region, save
6040 the restriction and widen. */
6041 if (! (BEGV <= PT && PT <= ZV))
6042 Fwiden ();
6044 /* Adjust the multibyteness of TEXT to that of the buffer. */
6045 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6046 != ! STRING_MULTIBYTE (text))
6047 text = (STRING_MULTIBYTE (text)
6048 ? Fstring_as_unibyte (text)
6049 : Fstring_to_multibyte (text));
6050 /* Insert before markers in case we are inserting where
6051 the buffer's mark is, and the user's next command is Meta-y. */
6052 insert_from_string_before_markers (text, 0, 0,
6053 SCHARS (text), SBYTES (text), 0);
6055 /* Make sure the process marker's position is valid when the
6056 process buffer is changed in the signal_after_change above.
6057 W3 is known to do that. */
6058 if (BUFFERP (p->buffer)
6059 && (b = XBUFFER (p->buffer), b != current_buffer))
6060 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6061 else
6062 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6064 update_mode_lines = 23;
6066 /* Make sure opoint and the old restrictions
6067 float ahead of any new text just as point would. */
6068 if (opoint >= before)
6070 opoint += PT - before;
6071 opoint_byte += PT_BYTE - before_byte;
6073 if (old_begv > before)
6075 old_begv += PT - before;
6076 old_begv_byte += PT_BYTE - before_byte;
6078 if (old_zv >= before)
6080 old_zv += PT - before;
6081 old_zv_byte += PT_BYTE - before_byte;
6084 /* If the restriction isn't what it should be, set it. */
6085 if (old_begv != BEGV || old_zv != ZV)
6086 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
6088 bset_read_only (current_buffer, old_read_only);
6089 SET_PT_BOTH (opoint, opoint_byte);
6091 return Qnil;
6094 /* Sending data to subprocess. */
6096 /* In send_process, when a write fails temporarily,
6097 wait_reading_process_output is called. It may execute user code,
6098 e.g. timers, that attempts to write new data to the same process.
6099 We must ensure that data is sent in the right order, and not
6100 interspersed half-completed with other writes (Bug#10815). This is
6101 handled by the write_queue element of struct process. It is a list
6102 with each entry having the form
6104 (string . (offset . length))
6106 where STRING is a lisp string, OFFSET is the offset into the
6107 string's byte sequence from which we should begin to send, and
6108 LENGTH is the number of bytes left to send. */
6110 /* Create a new entry in write_queue.
6111 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6112 BUF is a pointer to the string sequence of the input_obj or a C
6113 string in case of Qt or Qnil. */
6115 static void
6116 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6117 const char *buf, ptrdiff_t len, bool front)
6119 ptrdiff_t offset;
6120 Lisp_Object entry, obj;
6122 if (STRINGP (input_obj))
6124 offset = buf - SSDATA (input_obj);
6125 obj = input_obj;
6127 else
6129 offset = 0;
6130 obj = make_unibyte_string (buf, len);
6133 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
6135 if (front)
6136 pset_write_queue (p, Fcons (entry, p->write_queue));
6137 else
6138 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6141 /* Remove the first element in the write_queue of process P, put its
6142 contents in OBJ, BUF and LEN, and return true. If the
6143 write_queue is empty, return false. */
6145 static bool
6146 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6147 const char **buf, ptrdiff_t *len)
6149 Lisp_Object entry, offset_length;
6150 ptrdiff_t offset;
6152 if (NILP (p->write_queue))
6153 return 0;
6155 entry = XCAR (p->write_queue);
6156 pset_write_queue (p, XCDR (p->write_queue));
6158 *obj = XCAR (entry);
6159 offset_length = XCDR (entry);
6161 *len = XINT (XCDR (offset_length));
6162 offset = XINT (XCAR (offset_length));
6163 *buf = SSDATA (*obj) + offset;
6165 return 1;
6168 /* Send some data to process PROC.
6169 BUF is the beginning of the data; LEN is the number of characters.
6170 OBJECT is the Lisp object that the data comes from. If OBJECT is
6171 nil or t, it means that the data comes from C string.
6173 If OBJECT is not nil, the data is encoded by PROC's coding-system
6174 for encoding before it is sent.
6176 This function can evaluate Lisp code and can garbage collect. */
6178 static void
6179 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6180 Lisp_Object object)
6182 struct Lisp_Process *p = XPROCESS (proc);
6183 ssize_t rv;
6184 struct coding_system *coding;
6186 if (NETCONN_P (proc))
6188 wait_while_connecting (proc);
6189 wait_for_tls_negotiation (proc);
6192 if (p->raw_status_new)
6193 update_status (p);
6194 if (! EQ (p->status, Qrun))
6195 error ("Process %s not running", SDATA (p->name));
6196 if (p->outfd < 0)
6197 error ("Output file descriptor of %s is closed", SDATA (p->name));
6199 coding = proc_encode_coding_system[p->outfd];
6200 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6202 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6203 || (BUFFERP (object)
6204 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6205 || EQ (object, Qt))
6207 pset_encode_coding_system
6208 (p, complement_process_encoding_system (p->encode_coding_system));
6209 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6211 /* The coding system for encoding was changed to raw-text
6212 because we sent a unibyte text previously. Now we are
6213 sending a multibyte text, thus we must encode it by the
6214 original coding system specified for the current process.
6216 Another reason we come here is that the coding system
6217 was just complemented and a new one was returned by
6218 complement_process_encoding_system. */
6219 setup_coding_system (p->encode_coding_system, coding);
6220 Vlast_coding_system_used = p->encode_coding_system;
6222 coding->src_multibyte = 1;
6224 else
6226 coding->src_multibyte = 0;
6227 /* For sending a unibyte text, character code conversion should
6228 not take place but EOL conversion should. So, setup raw-text
6229 or one of the subsidiary if we have not yet done it. */
6230 if (CODING_REQUIRE_ENCODING (coding))
6232 if (CODING_REQUIRE_FLUSHING (coding))
6234 /* But, before changing the coding, we must flush out data. */
6235 coding->mode |= CODING_MODE_LAST_BLOCK;
6236 send_process (proc, "", 0, Qt);
6237 coding->mode &= CODING_MODE_LAST_BLOCK;
6239 setup_coding_system (raw_text_coding_system
6240 (Vlast_coding_system_used),
6241 coding);
6242 coding->src_multibyte = 0;
6245 coding->dst_multibyte = 0;
6247 if (CODING_REQUIRE_ENCODING (coding))
6249 coding->dst_object = Qt;
6250 if (BUFFERP (object))
6252 ptrdiff_t from_byte, from, to;
6253 ptrdiff_t save_pt, save_pt_byte;
6254 struct buffer *cur = current_buffer;
6256 set_buffer_internal (XBUFFER (object));
6257 save_pt = PT, save_pt_byte = PT_BYTE;
6259 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6260 from = BYTE_TO_CHAR (from_byte);
6261 to = BYTE_TO_CHAR (from_byte + len);
6262 TEMP_SET_PT_BOTH (from, from_byte);
6263 encode_coding_object (coding, object, from, from_byte,
6264 to, from_byte + len, Qt);
6265 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6266 set_buffer_internal (cur);
6268 else if (STRINGP (object))
6270 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6271 SBYTES (object), Qt);
6273 else
6275 coding->dst_object = make_unibyte_string (buf, len);
6276 coding->produced = len;
6279 len = coding->produced;
6280 object = coding->dst_object;
6281 buf = SSDATA (object);
6284 /* If there is already data in the write_queue, put the new data
6285 in the back of queue. Otherwise, ignore it. */
6286 if (!NILP (p->write_queue))
6287 write_queue_push (p, object, buf, len, 0);
6289 do /* while !NILP (p->write_queue) */
6291 ptrdiff_t cur_len = -1;
6292 const char *cur_buf;
6293 Lisp_Object cur_object;
6295 /* If write_queue is empty, ignore it. */
6296 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6298 cur_len = len;
6299 cur_buf = buf;
6300 cur_object = object;
6303 while (cur_len > 0)
6305 /* Send this batch, using one or more write calls. */
6306 ptrdiff_t written = 0;
6307 int outfd = p->outfd;
6308 #ifdef DATAGRAM_SOCKETS
6309 if (DATAGRAM_CHAN_P (outfd))
6311 rv = sendto (outfd, cur_buf, cur_len,
6312 0, datagram_address[outfd].sa,
6313 datagram_address[outfd].len);
6314 if (rv >= 0)
6315 written = rv;
6316 else if (errno == EMSGSIZE)
6317 report_file_error ("Sending datagram", proc);
6319 else
6320 #endif
6322 #ifdef HAVE_GNUTLS
6323 if (p->gnutls_p && p->gnutls_state)
6324 written = emacs_gnutls_write (p, cur_buf, cur_len);
6325 else
6326 #endif
6327 written = emacs_write_sig (outfd, cur_buf, cur_len);
6328 rv = (written ? 0 : -1);
6329 if (p->read_output_delay > 0
6330 && p->adaptive_read_buffering == 1)
6332 p->read_output_delay = 0;
6333 process_output_delay_count--;
6334 p->read_output_skip = 0;
6338 if (rv < 0)
6340 if (would_block (errno))
6341 /* Buffer is full. Wait, accepting input;
6342 that may allow the program
6343 to finish doing output and read more. */
6345 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6346 /* A gross hack to work around a bug in FreeBSD.
6347 In the following sequence, read(2) returns
6348 bogus data:
6350 write(2) 1022 bytes
6351 write(2) 954 bytes, get EAGAIN
6352 read(2) 1024 bytes in process_read_output
6353 read(2) 11 bytes in process_read_output
6355 That is, read(2) returns more bytes than have
6356 ever been written successfully. The 1033 bytes
6357 read are the 1022 bytes written successfully
6358 after processing (for example with CRs added if
6359 the terminal is set up that way which it is
6360 here). The same bytes will be seen again in a
6361 later read(2), without the CRs. */
6363 if (errno == EAGAIN)
6365 int flags = FWRITE;
6366 ioctl (p->outfd, TIOCFLUSH, &flags);
6368 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6370 /* Put what we should have written in wait_queue. */
6371 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6372 wait_reading_process_output (0, 20 * 1000 * 1000,
6373 0, 0, Qnil, NULL, 0);
6374 /* Reread queue, to see what is left. */
6375 break;
6377 else if (errno == EPIPE)
6379 p->raw_status_new = 0;
6380 pset_status (p, list2 (Qexit, make_number (256)));
6381 p->tick = ++process_tick;
6382 deactivate_process (proc);
6383 error ("process %s no longer connected to pipe; closed it",
6384 SDATA (p->name));
6386 else
6387 /* This is a real error. */
6388 report_file_error ("Writing to process", proc);
6390 cur_buf += written;
6391 cur_len -= written;
6394 while (!NILP (p->write_queue));
6397 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6398 3, 3, 0,
6399 doc: /* Send current contents of region as input to PROCESS.
6400 PROCESS may be a process, a buffer, the name of a process or buffer, or
6401 nil, indicating the current buffer's process.
6402 Called from program, takes three arguments, PROCESS, START and END.
6403 If the region is more than 500 characters long,
6404 it is sent in several bunches. This may happen even for shorter regions.
6405 Output from processes can arrive in between bunches.
6407 If PROCESS is a non-blocking network process that hasn't been fully
6408 set up yet, this function will block until socket setup has completed. */)
6409 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6411 Lisp_Object proc = get_process (process);
6412 ptrdiff_t start_byte, end_byte;
6414 validate_region (&start, &end);
6416 start_byte = CHAR_TO_BYTE (XINT (start));
6417 end_byte = CHAR_TO_BYTE (XINT (end));
6419 if (XINT (start) < GPT && XINT (end) > GPT)
6420 move_gap_both (XINT (start), start_byte);
6422 if (NETCONN_P (proc))
6423 wait_while_connecting (proc);
6425 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6426 end_byte - start_byte, Fcurrent_buffer ());
6428 return Qnil;
6431 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6432 2, 2, 0,
6433 doc: /* Send PROCESS the contents of STRING as input.
6434 PROCESS may be a process, a buffer, the name of a process or buffer, or
6435 nil, indicating the current buffer's process.
6436 If STRING is more than 500 characters long,
6437 it is sent in several bunches. This may happen even for shorter strings.
6438 Output from processes can arrive in between bunches.
6440 If PROCESS is a non-blocking network process that hasn't been fully
6441 set up yet, this function will block until socket setup has completed. */)
6442 (Lisp_Object process, Lisp_Object string)
6444 CHECK_STRING (string);
6445 Lisp_Object proc = get_process (process);
6446 send_process (proc, SSDATA (string),
6447 SBYTES (string), string);
6448 return Qnil;
6451 /* Return the foreground process group for the tty/pty that
6452 the process P uses. */
6453 static pid_t
6454 emacs_get_tty_pgrp (struct Lisp_Process *p)
6456 pid_t gid = -1;
6458 #ifdef TIOCGPGRP
6459 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6461 int fd;
6462 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6463 master side. Try the slave side. */
6464 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6466 if (fd != -1)
6468 ioctl (fd, TIOCGPGRP, &gid);
6469 emacs_close (fd);
6472 #endif /* defined (TIOCGPGRP ) */
6474 return gid;
6477 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6478 Sprocess_running_child_p, 0, 1, 0,
6479 doc: /* Return non-nil if PROCESS has given the terminal to a
6480 child. If the operating system does not make it possible to find out,
6481 return t. If we can find out, return the numeric ID of the foreground
6482 process group. */)
6483 (Lisp_Object process)
6485 /* Initialize in case ioctl doesn't exist or gives an error,
6486 in a way that will cause returning t. */
6487 Lisp_Object proc = get_process (process);
6488 struct Lisp_Process *p = XPROCESS (proc);
6490 if (!EQ (p->type, Qreal))
6491 error ("Process %s is not a subprocess",
6492 SDATA (p->name));
6493 if (p->infd < 0)
6494 error ("Process %s is not active",
6495 SDATA (p->name));
6497 pid_t gid = emacs_get_tty_pgrp (p);
6499 if (gid == p->pid)
6500 return Qnil;
6501 if (gid != -1)
6502 return make_number (gid);
6503 return Qt;
6506 /* Send a signal number SIGNO to PROCESS.
6507 If CURRENT_GROUP is t, that means send to the process group
6508 that currently owns the terminal being used to communicate with PROCESS.
6509 This is used for various commands in shell mode.
6510 If CURRENT_GROUP is lambda, that means send to the process group
6511 that currently owns the terminal, but only if it is NOT the shell itself.
6513 If NOMSG is false, insert signal-announcements into process's buffers
6514 right away.
6516 If we can, we try to signal PROCESS by sending control characters
6517 down the pty. This allows us to signal inferiors who have changed
6518 their uid, for which kill would return an EPERM error. */
6520 static void
6521 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6522 bool nomsg)
6524 Lisp_Object proc;
6525 struct Lisp_Process *p;
6526 pid_t gid;
6527 bool no_pgrp = 0;
6529 proc = get_process (process);
6530 p = XPROCESS (proc);
6532 if (!EQ (p->type, Qreal))
6533 error ("Process %s is not a subprocess",
6534 SDATA (p->name));
6535 if (p->infd < 0)
6536 error ("Process %s is not active",
6537 SDATA (p->name));
6539 if (!p->pty_flag)
6540 current_group = Qnil;
6542 /* If we are using pgrps, get a pgrp number and make it negative. */
6543 if (NILP (current_group))
6544 /* Send the signal to the shell's process group. */
6545 gid = p->pid;
6546 else
6548 #ifdef SIGNALS_VIA_CHARACTERS
6549 /* If possible, send signals to the entire pgrp
6550 by sending an input character to it. */
6552 struct termios t;
6553 cc_t *sig_char = NULL;
6555 tcgetattr (p->infd, &t);
6557 switch (signo)
6559 case SIGINT:
6560 sig_char = &t.c_cc[VINTR];
6561 break;
6563 case SIGQUIT:
6564 sig_char = &t.c_cc[VQUIT];
6565 break;
6567 case SIGTSTP:
6568 #ifdef VSWTCH
6569 sig_char = &t.c_cc[VSWTCH];
6570 #else
6571 sig_char = &t.c_cc[VSUSP];
6572 #endif
6573 break;
6576 if (sig_char && *sig_char != CDISABLE)
6578 send_process (proc, (char *) sig_char, 1, Qnil);
6579 return;
6581 /* If we can't send the signal with a character,
6582 fall through and send it another way. */
6584 /* The code above may fall through if it can't
6585 handle the signal. */
6586 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6588 #ifdef TIOCGPGRP
6589 /* Get the current pgrp using the tty itself, if we have that.
6590 Otherwise, use the pty to get the pgrp.
6591 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6592 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6593 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6594 His patch indicates that if TIOCGPGRP returns an error, then
6595 we should just assume that p->pid is also the process group id. */
6597 gid = emacs_get_tty_pgrp (p);
6599 if (gid == -1)
6600 /* If we can't get the information, assume
6601 the shell owns the tty. */
6602 gid = p->pid;
6604 /* It is not clear whether anything really can set GID to -1.
6605 Perhaps on some system one of those ioctls can or could do so.
6606 Or perhaps this is vestigial. */
6607 if (gid == -1)
6608 no_pgrp = 1;
6609 #else /* ! defined (TIOCGPGRP) */
6610 /* Can't select pgrps on this system, so we know that
6611 the child itself heads the pgrp. */
6612 gid = p->pid;
6613 #endif /* ! defined (TIOCGPGRP) */
6615 /* If current_group is lambda, and the shell owns the terminal,
6616 don't send any signal. */
6617 if (EQ (current_group, Qlambda) && gid == p->pid)
6618 return;
6621 #ifdef SIGCONT
6622 if (signo == SIGCONT)
6624 p->raw_status_new = 0;
6625 pset_status (p, Qrun);
6626 p->tick = ++process_tick;
6627 if (!nomsg)
6629 status_notify (NULL, NULL);
6630 redisplay_preserve_echo_area (13);
6633 #endif
6635 #ifdef TIOCSIGSEND
6636 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6637 We don't know whether the bug is fixed in later HP-UX versions. */
6638 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6639 return;
6640 #endif
6642 /* If we don't have process groups, send the signal to the immediate
6643 subprocess. That isn't really right, but it's better than any
6644 obvious alternative. */
6645 pid_t pid = no_pgrp ? gid : - gid;
6647 /* Do not kill an already-reaped process, as that could kill an
6648 innocent bystander that happens to have the same process ID. */
6649 sigset_t oldset;
6650 block_child_signal (&oldset);
6651 if (p->alive)
6652 kill (pid, signo);
6653 unblock_child_signal (&oldset);
6656 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6657 doc: /* Interrupt process PROCESS.
6658 PROCESS may be a process, a buffer, or the name of a process or buffer.
6659 No arg or nil means current buffer's process.
6660 Second arg CURRENT-GROUP non-nil means send signal to
6661 the current process-group of the process's controlling terminal
6662 rather than to the process's own process group.
6663 If the process is a shell, this means interrupt current subjob
6664 rather than the shell.
6666 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6667 don't send the signal. */)
6668 (Lisp_Object process, Lisp_Object current_group)
6670 process_send_signal (process, SIGINT, current_group, 0);
6671 return process;
6674 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6675 doc: /* Kill process PROCESS. May be process or name of one.
6676 See function `interrupt-process' for more details on usage. */)
6677 (Lisp_Object process, Lisp_Object current_group)
6679 process_send_signal (process, SIGKILL, current_group, 0);
6680 return process;
6683 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6684 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6685 See function `interrupt-process' for more details on usage. */)
6686 (Lisp_Object process, Lisp_Object current_group)
6688 process_send_signal (process, SIGQUIT, current_group, 0);
6689 return process;
6692 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6693 doc: /* Stop process PROCESS. May be process or name of one.
6694 See function `interrupt-process' for more details on usage.
6695 If PROCESS is a network or serial or pipe connection, inhibit handling
6696 of incoming traffic. */)
6697 (Lisp_Object process, Lisp_Object current_group)
6699 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6700 || PIPECONN_P (process)))
6702 struct Lisp_Process *p;
6704 p = XPROCESS (process);
6705 if (NILP (p->command)
6706 && p->infd >= 0)
6707 delete_read_fd (p->infd);
6708 pset_command (p, Qt);
6709 return process;
6711 #ifndef SIGTSTP
6712 error ("No SIGTSTP support");
6713 #else
6714 process_send_signal (process, SIGTSTP, current_group, 0);
6715 #endif
6716 return process;
6719 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6720 doc: /* Continue process PROCESS. May be process or name of one.
6721 See function `interrupt-process' for more details on usage.
6722 If PROCESS is a network or serial process, resume handling of incoming
6723 traffic. */)
6724 (Lisp_Object process, Lisp_Object current_group)
6726 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6727 || PIPECONN_P (process)))
6729 struct Lisp_Process *p;
6731 p = XPROCESS (process);
6732 if (EQ (p->command, Qt)
6733 && p->infd >= 0
6734 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6736 add_process_read_fd (p->infd);
6737 #ifdef WINDOWSNT
6738 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6739 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6740 #else /* not WINDOWSNT */
6741 tcflush (p->infd, TCIFLUSH);
6742 #endif /* not WINDOWSNT */
6744 pset_command (p, Qnil);
6745 return process;
6747 #ifdef SIGCONT
6748 process_send_signal (process, SIGCONT, current_group, 0);
6749 #else
6750 error ("No SIGCONT support");
6751 #endif
6752 return process;
6755 /* Return the integer value of the signal whose abbreviation is ABBR,
6756 or a negative number if there is no such signal. */
6757 static int
6758 abbr_to_signal (char const *name)
6760 int i, signo;
6761 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6763 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6764 name += 3;
6766 for (i = 0; i < sizeof sigbuf; i++)
6768 sigbuf[i] = c_toupper (name[i]);
6769 if (! sigbuf[i])
6770 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6773 return -1;
6776 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6777 2, 2, "sProcess (name or number): \nnSignal code: ",
6778 doc: /* Send PROCESS the signal with code SIGCODE.
6779 PROCESS may also be a number specifying the process id of the
6780 process to signal; in this case, the process need not be a child of
6781 this Emacs.
6782 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6783 (Lisp_Object process, Lisp_Object sigcode)
6785 pid_t pid;
6786 int signo;
6788 if (STRINGP (process))
6790 Lisp_Object tem = Fget_process (process);
6791 if (NILP (tem))
6793 Lisp_Object process_number
6794 = string_to_number (SSDATA (process), 10, 1);
6795 if (NUMBERP (process_number))
6796 tem = process_number;
6798 process = tem;
6800 else if (!NUMBERP (process))
6801 process = get_process (process);
6803 if (NILP (process))
6804 return process;
6806 if (NUMBERP (process))
6807 CONS_TO_INTEGER (process, pid_t, pid);
6808 else
6810 CHECK_PROCESS (process);
6811 pid = XPROCESS (process)->pid;
6812 if (pid <= 0)
6813 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6816 if (INTEGERP (sigcode))
6818 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6819 signo = XINT (sigcode);
6821 else
6823 char *name;
6825 CHECK_SYMBOL (sigcode);
6826 name = SSDATA (SYMBOL_NAME (sigcode));
6828 signo = abbr_to_signal (name);
6829 if (signo < 0)
6830 error ("Undefined signal name %s", name);
6833 return make_number (kill (pid, signo));
6836 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6837 doc: /* Make PROCESS see end-of-file in its input.
6838 EOF comes after any text already sent to it.
6839 PROCESS may be a process, a buffer, the name of a process or buffer, or
6840 nil, indicating the current buffer's process.
6841 If PROCESS is a network connection, or is a process communicating
6842 through a pipe (as opposed to a pty), then you cannot send any more
6843 text to PROCESS after you call this function.
6844 If PROCESS is a serial process, wait until all output written to the
6845 process has been transmitted to the serial port. */)
6846 (Lisp_Object process)
6848 Lisp_Object proc;
6849 struct coding_system *coding = NULL;
6850 int outfd;
6852 proc = get_process (process);
6854 if (NETCONN_P (proc))
6855 wait_while_connecting (proc);
6857 if (DATAGRAM_CONN_P (proc))
6858 return process;
6861 outfd = XPROCESS (proc)->outfd;
6862 if (outfd >= 0)
6863 coding = proc_encode_coding_system[outfd];
6865 /* Make sure the process is really alive. */
6866 if (XPROCESS (proc)->raw_status_new)
6867 update_status (XPROCESS (proc));
6868 if (! EQ (XPROCESS (proc)->status, Qrun))
6869 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6871 if (coding && CODING_REQUIRE_FLUSHING (coding))
6873 coding->mode |= CODING_MODE_LAST_BLOCK;
6874 send_process (proc, "", 0, Qnil);
6877 if (XPROCESS (proc)->pty_flag)
6878 send_process (proc, "\004", 1, Qnil);
6879 else if (EQ (XPROCESS (proc)->type, Qserial))
6881 #ifndef WINDOWSNT
6882 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6883 report_file_error ("Failed tcdrain", Qnil);
6884 #endif /* not WINDOWSNT */
6885 /* Do nothing on Windows because writes are blocking. */
6887 else
6889 struct Lisp_Process *p = XPROCESS (proc);
6890 int old_outfd = p->outfd;
6891 int new_outfd;
6893 #ifdef HAVE_SHUTDOWN
6894 /* If this is a network connection, or socketpair is used
6895 for communication with the subprocess, call shutdown to cause EOF.
6896 (In some old system, shutdown to socketpair doesn't work.
6897 Then we just can't win.) */
6898 if (0 <= old_outfd
6899 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6900 shutdown (old_outfd, 1);
6901 #endif
6902 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6903 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6904 if (new_outfd < 0)
6905 report_file_error ("Opening null device", Qnil);
6906 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6907 p->outfd = new_outfd;
6909 if (!proc_encode_coding_system[new_outfd])
6910 proc_encode_coding_system[new_outfd]
6911 = xmalloc (sizeof (struct coding_system));
6912 if (old_outfd >= 0)
6914 *proc_encode_coding_system[new_outfd]
6915 = *proc_encode_coding_system[old_outfd];
6916 memset (proc_encode_coding_system[old_outfd], 0,
6917 sizeof (struct coding_system));
6919 else
6920 setup_coding_system (p->encode_coding_system,
6921 proc_encode_coding_system[new_outfd]);
6923 return process;
6926 /* The main Emacs thread records child processes in three places:
6928 - Vprocess_alist, for asynchronous subprocesses, which are child
6929 processes visible to Lisp.
6931 - deleted_pid_list, for child processes invisible to Lisp,
6932 typically because of delete-process. These are recorded so that
6933 the processes can be reaped when they exit, so that the operating
6934 system's process table is not cluttered by zombies.
6936 - the local variable PID in Fcall_process, call_process_cleanup and
6937 call_process_kill, for synchronous subprocesses.
6938 record_unwind_protect is used to make sure this process is not
6939 forgotten: if the user interrupts call-process and the child
6940 process refuses to exit immediately even with two C-g's,
6941 call_process_kill adds PID's contents to deleted_pid_list before
6942 returning.
6944 The main Emacs thread invokes waitpid only on child processes that
6945 it creates and that have not been reaped. This avoid races on
6946 platforms such as GTK, where other threads create their own
6947 subprocesses which the main thread should not reap. For example,
6948 if the main thread attempted to reap an already-reaped child, it
6949 might inadvertently reap a GTK-created process that happened to
6950 have the same process ID. */
6952 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6953 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6954 keep track of its own children. GNUstep is similar. */
6956 static void dummy_handler (int sig) {}
6957 static signal_handler_t volatile lib_child_handler;
6959 /* Handle a SIGCHLD signal by looking for known child processes of
6960 Emacs whose status have changed. For each one found, record its
6961 new status.
6963 All we do is change the status; we do not run sentinels or print
6964 notifications. That is saved for the next time keyboard input is
6965 done, in order to avoid timing errors.
6967 ** WARNING: this can be called during garbage collection.
6968 Therefore, it must not be fooled by the presence of mark bits in
6969 Lisp objects.
6971 ** USG WARNING: Although it is not obvious from the documentation
6972 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6973 signal() before executing at least one wait(), otherwise the
6974 handler will be called again, resulting in an infinite loop. The
6975 relevant portion of the documentation reads "SIGCLD signals will be
6976 queued and the signal-catching function will be continually
6977 reentered until the queue is empty". Invoking signal() causes the
6978 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6979 Inc.
6981 ** Malloc WARNING: This should never call malloc either directly or
6982 indirectly; if it does, that is a bug. */
6984 static void
6985 handle_child_signal (int sig)
6987 Lisp_Object tail, proc;
6989 /* Find the process that signaled us, and record its status. */
6991 /* The process can have been deleted by Fdelete_process, or have
6992 been started asynchronously by Fcall_process. */
6993 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6995 bool all_pids_are_fixnums
6996 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6997 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6998 Lisp_Object head = XCAR (tail);
6999 Lisp_Object xpid;
7000 if (! CONSP (head))
7001 continue;
7002 xpid = XCAR (head);
7003 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
7005 pid_t deleted_pid;
7006 if (INTEGERP (xpid))
7007 deleted_pid = XINT (xpid);
7008 else
7009 deleted_pid = XFLOAT_DATA (xpid);
7010 if (child_status_changed (deleted_pid, 0, 0))
7012 if (STRINGP (XCDR (head)))
7013 unlink (SSDATA (XCDR (head)));
7014 XSETCAR (tail, Qnil);
7019 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7020 FOR_EACH_PROCESS (tail, proc)
7022 struct Lisp_Process *p = XPROCESS (proc);
7023 int status;
7025 if (p->alive
7026 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7028 /* Change the status of the process that was found. */
7029 p->tick = ++process_tick;
7030 p->raw_status = status;
7031 p->raw_status_new = 1;
7033 /* If process has terminated, stop waiting for its output. */
7034 if (WIFSIGNALED (status) || WIFEXITED (status))
7036 bool clear_desc_flag = 0;
7037 p->alive = 0;
7038 if (p->infd >= 0)
7039 clear_desc_flag = 1;
7041 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7042 if (clear_desc_flag)
7043 delete_read_fd (p->infd);
7048 lib_child_handler (sig);
7049 #ifdef NS_IMPL_GNUSTEP
7050 /* NSTask in GNUstep sets its child handler each time it is called.
7051 So we must re-set ours. */
7052 catch_child_signal ();
7053 #endif
7056 static void
7057 deliver_child_signal (int sig)
7059 deliver_process_signal (sig, handle_child_signal);
7063 static Lisp_Object
7064 exec_sentinel_error_handler (Lisp_Object error_val)
7066 cmd_error_internal (error_val, "error in process sentinel: ");
7067 Vinhibit_quit = Qt;
7068 update_echo_area ();
7069 Fsleep_for (make_number (2), Qnil);
7070 return Qt;
7073 static void
7074 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7076 Lisp_Object sentinel, odeactivate;
7077 struct Lisp_Process *p = XPROCESS (proc);
7078 ptrdiff_t count = SPECPDL_INDEX ();
7079 bool outer_running_asynch_code = running_asynch_code;
7080 int waiting = waiting_for_user_input_p;
7082 if (inhibit_sentinels)
7083 return;
7085 odeactivate = Vdeactivate_mark;
7086 #if 0
7087 Lisp_Object obuffer, okeymap;
7088 XSETBUFFER (obuffer, current_buffer);
7089 okeymap = BVAR (current_buffer, keymap);
7090 #endif
7092 /* There's no good reason to let sentinels change the current
7093 buffer, and many callers of accept-process-output, sit-for, and
7094 friends don't expect current-buffer to be changed from under them. */
7095 record_unwind_current_buffer ();
7097 sentinel = p->sentinel;
7099 /* Inhibit quit so that random quits don't screw up a running filter. */
7100 specbind (Qinhibit_quit, Qt);
7101 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7103 /* In case we get recursively called,
7104 and we already saved the match data nonrecursively,
7105 save the same match data in safely recursive fashion. */
7106 if (outer_running_asynch_code)
7108 Lisp_Object tem;
7109 tem = Fmatch_data (Qnil, Qnil, Qnil);
7110 restore_search_regs ();
7111 record_unwind_save_match_data ();
7112 Fset_match_data (tem, Qt);
7115 /* For speed, if a search happens within this code,
7116 save the match data in a special nonrecursive fashion. */
7117 running_asynch_code = 1;
7119 internal_condition_case_1 (read_process_output_call,
7120 list3 (sentinel, proc, reason),
7121 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7122 exec_sentinel_error_handler);
7124 /* If we saved the match data nonrecursively, restore it now. */
7125 restore_search_regs ();
7126 running_asynch_code = outer_running_asynch_code;
7128 Vdeactivate_mark = odeactivate;
7130 /* Restore waiting_for_user_input_p as it was
7131 when we were called, in case the filter clobbered it. */
7132 waiting_for_user_input_p = waiting;
7134 #if 0
7135 if (! EQ (Fcurrent_buffer (), obuffer)
7136 || ! EQ (current_buffer->keymap, okeymap))
7137 #endif
7138 /* But do it only if the caller is actually going to read events.
7139 Otherwise there's no need to make him wake up, and it could
7140 cause trouble (for example it would make sit_for return). */
7141 if (waiting_for_user_input_p == -1)
7142 record_asynch_buffer_change ();
7144 unbind_to (count, Qnil);
7147 /* Report all recent events of a change in process status
7148 (either run the sentinel or output a message).
7149 This is usually done while Emacs is waiting for keyboard input
7150 but can be done at other times.
7152 Return positive if any input was received from WAIT_PROC (or from
7153 any process if WAIT_PROC is null), zero if input was attempted but
7154 none received, and negative if we didn't even try. */
7156 static int
7157 status_notify (struct Lisp_Process *deleting_process,
7158 struct Lisp_Process *wait_proc)
7160 Lisp_Object proc;
7161 Lisp_Object tail, msg;
7162 int got_some_output = -1;
7164 tail = Qnil;
7165 msg = Qnil;
7167 /* Set this now, so that if new processes are created by sentinels
7168 that we run, we get called again to handle their status changes. */
7169 update_tick = process_tick;
7171 FOR_EACH_PROCESS (tail, proc)
7173 Lisp_Object symbol;
7174 register struct Lisp_Process *p = XPROCESS (proc);
7176 if (p->tick != p->update_tick)
7178 p->update_tick = p->tick;
7180 /* If process is still active, read any output that remains. */
7181 while (! EQ (p->filter, Qt)
7182 && ! connecting_status (p->status)
7183 && ! EQ (p->status, Qlisten)
7184 /* Network or serial process not stopped: */
7185 && ! EQ (p->command, Qt)
7186 && p->infd >= 0
7187 && p != deleting_process)
7189 int nread = read_process_output (proc, p->infd);
7190 if ((!wait_proc || wait_proc == XPROCESS (proc))
7191 && got_some_output < nread)
7192 got_some_output = nread;
7193 if (nread <= 0)
7194 break;
7197 /* Get the text to use for the message. */
7198 if (p->raw_status_new)
7199 update_status (p);
7200 msg = status_message (p);
7202 /* If process is terminated, deactivate it or delete it. */
7203 symbol = p->status;
7204 if (CONSP (p->status))
7205 symbol = XCAR (p->status);
7207 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7208 || EQ (symbol, Qclosed))
7210 if (delete_exited_processes)
7211 remove_process (proc);
7212 else
7213 deactivate_process (proc);
7216 /* The actions above may have further incremented p->tick.
7217 So set p->update_tick again so that an error in the sentinel will
7218 not cause this code to be run again. */
7219 p->update_tick = p->tick;
7220 /* Now output the message suitably. */
7221 exec_sentinel (proc, msg);
7222 if (BUFFERP (p->buffer))
7223 /* In case it uses %s in mode-line-format. */
7224 bset_update_mode_line (XBUFFER (p->buffer));
7226 } /* end for */
7228 return got_some_output;
7231 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7232 Sinternal_default_process_sentinel, 2, 2, 0,
7233 doc: /* Function used as default sentinel for processes.
7234 This inserts a status message into the process's buffer, if there is one. */)
7235 (Lisp_Object proc, Lisp_Object msg)
7237 Lisp_Object buffer, symbol;
7238 struct Lisp_Process *p;
7239 CHECK_PROCESS (proc);
7240 p = XPROCESS (proc);
7241 buffer = p->buffer;
7242 symbol = p->status;
7243 if (CONSP (symbol))
7244 symbol = XCAR (symbol);
7246 if (!EQ (symbol, Qrun) && !NILP (buffer))
7248 Lisp_Object tem;
7249 struct buffer *old = current_buffer;
7250 ptrdiff_t opoint, opoint_byte;
7251 ptrdiff_t before, before_byte;
7253 /* Avoid error if buffer is deleted
7254 (probably that's why the process is dead, too). */
7255 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7256 return Qnil;
7257 Fset_buffer (buffer);
7259 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7260 msg = (code_convert_string_norecord
7261 (msg, Vlocale_coding_system, 1));
7263 opoint = PT;
7264 opoint_byte = PT_BYTE;
7265 /* Insert new output into buffer
7266 at the current end-of-output marker,
7267 thus preserving logical ordering of input and output. */
7268 if (XMARKER (p->mark)->buffer)
7269 Fgoto_char (p->mark);
7270 else
7271 SET_PT_BOTH (ZV, ZV_BYTE);
7273 before = PT;
7274 before_byte = PT_BYTE;
7276 tem = BVAR (current_buffer, read_only);
7277 bset_read_only (current_buffer, Qnil);
7278 insert_string ("\nProcess ");
7279 { /* FIXME: temporary kludge. */
7280 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7281 insert_string (" ");
7282 Finsert (1, &msg);
7283 bset_read_only (current_buffer, tem);
7284 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7286 if (opoint >= before)
7287 SET_PT_BOTH (opoint + (PT - before),
7288 opoint_byte + (PT_BYTE - before_byte));
7289 else
7290 SET_PT_BOTH (opoint, opoint_byte);
7292 set_buffer_internal (old);
7294 return Qnil;
7298 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7299 Sset_process_coding_system, 1, 3, 0,
7300 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7301 DECODING will be used to decode subprocess output and ENCODING to
7302 encode subprocess input. */)
7303 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7305 CHECK_PROCESS (process);
7307 struct Lisp_Process *p = XPROCESS (process);
7309 Fcheck_coding_system (decoding);
7310 Fcheck_coding_system (encoding);
7311 encoding = coding_inherit_eol_type (encoding, Qnil);
7312 pset_decode_coding_system (p, decoding);
7313 pset_encode_coding_system (p, encoding);
7315 /* If the sockets haven't been set up yet, the final setup part of
7316 this will be called asynchronously. */
7317 if (p->infd < 0 || p->outfd < 0)
7318 return Qnil;
7320 setup_process_coding_systems (process);
7322 return Qnil;
7325 DEFUN ("process-coding-system",
7326 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7327 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7328 (register Lisp_Object process)
7330 CHECK_PROCESS (process);
7331 return Fcons (XPROCESS (process)->decode_coding_system,
7332 XPROCESS (process)->encode_coding_system);
7335 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7336 Sset_process_filter_multibyte, 2, 2, 0,
7337 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7338 If FLAG is non-nil, the filter is given multibyte strings.
7339 If FLAG is nil, the filter is given unibyte strings. In this case,
7340 all character code conversion except for end-of-line conversion is
7341 suppressed. */)
7342 (Lisp_Object process, Lisp_Object flag)
7344 CHECK_PROCESS (process);
7346 struct Lisp_Process *p = XPROCESS (process);
7347 if (NILP (flag))
7348 pset_decode_coding_system
7349 (p, raw_text_coding_system (p->decode_coding_system));
7351 /* If the sockets haven't been set up yet, the final setup part of
7352 this will be called asynchronously. */
7353 if (p->infd < 0 || p->outfd < 0)
7354 return Qnil;
7356 setup_process_coding_systems (process);
7358 return Qnil;
7361 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7362 Sprocess_filter_multibyte_p, 1, 1, 0,
7363 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7364 (Lisp_Object process)
7366 CHECK_PROCESS (process);
7367 struct Lisp_Process *p = XPROCESS (process);
7368 if (p->infd < 0)
7369 return Qnil;
7370 struct coding_system *coding = proc_decode_coding_system[p->infd];
7371 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7377 # ifdef HAVE_GPM
7379 void
7380 add_gpm_wait_descriptor (int desc)
7382 add_keyboard_wait_descriptor (desc);
7385 void
7386 delete_gpm_wait_descriptor (int desc)
7388 delete_keyboard_wait_descriptor (desc);
7391 # endif
7393 # ifdef USABLE_SIGIO
7395 /* Return true if *MASK has a bit set
7396 that corresponds to one of the keyboard input descriptors. */
7398 static bool
7399 keyboard_bit_set (fd_set *mask)
7401 int fd;
7403 for (fd = 0; fd <= max_desc; fd++)
7404 if (FD_ISSET (fd, mask)
7405 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7406 == (FOR_READ | KEYBOARD_FD)))
7407 return 1;
7409 return 0;
7411 # endif
7413 #else /* not subprocesses */
7415 /* Defined in msdos.c. */
7416 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7417 struct timespec *, void *);
7419 /* Implementation of wait_reading_process_output, assuming that there
7420 are no subprocesses. Used only by the MS-DOS build.
7422 Wait for timeout to elapse and/or keyboard input to be available.
7424 TIME_LIMIT is:
7425 timeout in seconds
7426 If negative, gobble data immediately available but don't wait for any.
7428 NSECS is:
7429 an additional duration to wait, measured in nanoseconds
7430 If TIME_LIMIT is zero, then:
7431 If NSECS == 0, there is no limit.
7432 If NSECS > 0, the timeout consists of NSECS only.
7433 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7435 READ_KBD is:
7436 0 to ignore keyboard input, or
7437 1 to return when input is available, or
7438 -1 means caller will actually read the input, so don't throw to
7439 the quit handler.
7441 see full version for other parameters. We know that wait_proc will
7442 always be NULL, since `subprocesses' isn't defined.
7444 DO_DISPLAY means redisplay should be done to show subprocess
7445 output that arrives.
7447 Return -1 signifying we got no output and did not try. */
7450 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7451 bool do_display,
7452 Lisp_Object wait_for_cell,
7453 struct Lisp_Process *wait_proc, int just_wait_proc)
7455 register int nfds;
7456 struct timespec end_time, timeout;
7457 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7459 if (TYPE_MAXIMUM (time_t) < time_limit)
7460 time_limit = TYPE_MAXIMUM (time_t);
7462 if (time_limit < 0 || nsecs < 0)
7463 wait = MINIMUM;
7464 else if (time_limit > 0 || nsecs > 0)
7466 wait = TIMEOUT;
7467 end_time = timespec_add (current_timespec (),
7468 make_timespec (time_limit, nsecs));
7470 else
7471 wait = INFINITY;
7473 /* Turn off periodic alarms (in case they are in use)
7474 and then turn off any other atimers,
7475 because the select emulator uses alarms. */
7476 stop_polling ();
7477 turn_on_atimers (0);
7479 while (1)
7481 bool timeout_reduced_for_timers = false;
7482 fd_set waitchannels;
7483 int xerrno;
7485 /* If calling from keyboard input, do not quit
7486 since we want to return C-g as an input character.
7487 Otherwise, do pending quit if requested. */
7488 if (read_kbd >= 0)
7489 QUIT;
7491 /* Exit now if the cell we're waiting for became non-nil. */
7492 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7493 break;
7495 /* Compute time from now till when time limit is up. */
7496 /* Exit if already run out. */
7497 if (wait == TIMEOUT)
7499 struct timespec now = current_timespec ();
7500 if (timespec_cmp (end_time, now) <= 0)
7501 break;
7502 timeout = timespec_sub (end_time, now);
7504 else
7505 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7507 /* If our caller will not immediately handle keyboard events,
7508 run timer events directly.
7509 (Callers that will immediately read keyboard events
7510 call timer_delay on their own.) */
7511 if (NILP (wait_for_cell))
7513 struct timespec timer_delay;
7517 unsigned old_timers_run = timers_run;
7518 timer_delay = timer_check ();
7519 if (timers_run != old_timers_run && do_display)
7520 /* We must retry, since a timer may have requeued itself
7521 and that could alter the time delay. */
7522 redisplay_preserve_echo_area (14);
7523 else
7524 break;
7526 while (!detect_input_pending ());
7528 /* If there is unread keyboard input, also return. */
7529 if (read_kbd != 0
7530 && requeued_events_pending_p ())
7531 break;
7533 if (timespec_valid_p (timer_delay))
7535 if (timespec_cmp (timer_delay, timeout) < 0)
7537 timeout = timer_delay;
7538 timeout_reduced_for_timers = true;
7543 /* Cause C-g and alarm signals to take immediate action,
7544 and cause input available signals to zero out timeout. */
7545 if (read_kbd < 0)
7546 set_waiting_for_input (&timeout);
7548 /* If a frame has been newly mapped and needs updating,
7549 reprocess its display stuff. */
7550 if (frame_garbaged && do_display)
7552 clear_waiting_for_input ();
7553 redisplay_preserve_echo_area (15);
7554 if (read_kbd < 0)
7555 set_waiting_for_input (&timeout);
7558 /* Wait till there is something to do. */
7559 FD_ZERO (&waitchannels);
7560 if (read_kbd && detect_input_pending ())
7561 nfds = 0;
7562 else
7564 if (read_kbd || !NILP (wait_for_cell))
7565 FD_SET (0, &waitchannels);
7566 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7569 xerrno = errno;
7571 /* Make C-g and alarm signals set flags again. */
7572 clear_waiting_for_input ();
7574 /* If we woke up due to SIGWINCH, actually change size now. */
7575 do_pending_window_change (0);
7577 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7578 /* We waited the full specified time, so return now. */
7579 break;
7581 if (nfds == -1)
7583 /* If the system call was interrupted, then go around the
7584 loop again. */
7585 if (xerrno == EINTR)
7586 FD_ZERO (&waitchannels);
7587 else
7588 report_file_errno ("Failed select", Qnil, xerrno);
7591 /* Check for keyboard input. */
7593 if (read_kbd
7594 && detect_input_pending_run_timers (do_display))
7596 swallow_events (do_display);
7597 if (detect_input_pending_run_timers (do_display))
7598 break;
7601 /* If there is unread keyboard input, also return. */
7602 if (read_kbd
7603 && requeued_events_pending_p ())
7604 break;
7606 /* If wait_for_cell. check for keyboard input
7607 but don't run any timers.
7608 ??? (It seems wrong to me to check for keyboard
7609 input at all when wait_for_cell, but the code
7610 has been this way since July 1994.
7611 Try changing this after version 19.31.) */
7612 if (! NILP (wait_for_cell)
7613 && detect_input_pending ())
7615 swallow_events (do_display);
7616 if (detect_input_pending ())
7617 break;
7620 /* Exit now if the cell we're waiting for became non-nil. */
7621 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7622 break;
7625 start_polling ();
7627 return -1;
7630 #endif /* not subprocesses */
7632 /* The following functions are needed even if async subprocesses are
7633 not supported. Some of them are no-op stubs in that case. */
7635 #ifdef HAVE_TIMERFD
7637 /* Add FD, which is a descriptor returned by timerfd_create,
7638 to the set of non-keyboard input descriptors. */
7640 void
7641 add_timer_wait_descriptor (int fd)
7643 add_read_fd (fd, timerfd_callback, NULL);
7644 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7647 #endif /* HAVE_TIMERFD */
7649 /* If program file NAME starts with /: for quoting a magic
7650 name, remove that, preserving the multibyteness of NAME. */
7652 Lisp_Object
7653 remove_slash_colon (Lisp_Object name)
7655 return
7656 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7657 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7658 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7659 : name);
7662 /* Add DESC to the set of keyboard input descriptors. */
7664 void
7665 add_keyboard_wait_descriptor (int desc)
7667 #ifdef subprocesses /* Actually means "not MSDOS". */
7668 eassert (desc >= 0 && desc < FD_SETSIZE);
7669 fd_callback_info[desc].flags &= ~PROCESS_FD;
7670 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7671 if (desc > max_desc)
7672 max_desc = desc;
7673 #endif
7676 /* From now on, do not expect DESC to give keyboard input. */
7678 void
7679 delete_keyboard_wait_descriptor (int desc)
7681 #ifdef subprocesses
7682 eassert (desc >= 0 && desc < FD_SETSIZE);
7684 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7686 if (desc == max_desc)
7687 recompute_max_desc ();
7688 #endif
7691 /* Setup coding systems of PROCESS. */
7693 void
7694 setup_process_coding_systems (Lisp_Object process)
7696 #ifdef subprocesses
7697 struct Lisp_Process *p = XPROCESS (process);
7698 int inch = p->infd;
7699 int outch = p->outfd;
7700 Lisp_Object coding_system;
7702 if (inch < 0 || outch < 0)
7703 return;
7705 if (!proc_decode_coding_system[inch])
7706 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7707 coding_system = p->decode_coding_system;
7708 if (EQ (p->filter, Qinternal_default_process_filter)
7709 && BUFFERP (p->buffer))
7711 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7712 coding_system = raw_text_coding_system (coding_system);
7714 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7716 if (!proc_encode_coding_system[outch])
7717 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7718 setup_coding_system (p->encode_coding_system,
7719 proc_encode_coding_system[outch]);
7720 #endif
7723 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7724 doc: /* Return the (or a) live process associated with BUFFER.
7725 BUFFER may be a buffer or the name of one.
7726 Return nil if all processes associated with BUFFER have been
7727 deleted or killed. */)
7728 (register Lisp_Object buffer)
7730 #ifdef subprocesses
7731 register Lisp_Object buf, tail, proc;
7733 if (NILP (buffer)) return Qnil;
7734 buf = Fget_buffer (buffer);
7735 if (NILP (buf)) return Qnil;
7737 FOR_EACH_PROCESS (tail, proc)
7738 if (EQ (XPROCESS (proc)->buffer, buf))
7739 return proc;
7740 #endif /* subprocesses */
7741 return Qnil;
7744 DEFUN ("process-inherit-coding-system-flag",
7745 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7746 1, 1, 0,
7747 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7748 If this flag is t, `buffer-file-coding-system' of the buffer
7749 associated with PROCESS will inherit the coding system used to decode
7750 the process output. */)
7751 (register Lisp_Object process)
7753 #ifdef subprocesses
7754 CHECK_PROCESS (process);
7755 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7756 #else
7757 /* Ignore the argument and return the value of
7758 inherit-process-coding-system. */
7759 return inherit_process_coding_system ? Qt : Qnil;
7760 #endif
7763 /* Kill all processes associated with `buffer'.
7764 If `buffer' is nil, kill all processes. */
7766 void
7767 kill_buffer_processes (Lisp_Object buffer)
7769 #ifdef subprocesses
7770 Lisp_Object tail, proc;
7772 FOR_EACH_PROCESS (tail, proc)
7773 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7775 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7776 Fdelete_process (proc);
7777 else if (XPROCESS (proc)->infd >= 0)
7778 process_send_signal (proc, SIGHUP, Qnil, 1);
7780 #else /* subprocesses */
7781 /* Since we have no subprocesses, this does nothing. */
7782 #endif /* subprocesses */
7785 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7786 Swaiting_for_user_input_p, 0, 0, 0,
7787 doc: /* Return non-nil if Emacs is waiting for input from the user.
7788 This is intended for use by asynchronous process output filters and sentinels. */)
7789 (void)
7791 #ifdef subprocesses
7792 return (waiting_for_user_input_p ? Qt : Qnil);
7793 #else
7794 return Qnil;
7795 #endif
7798 /* Stop reading input from keyboard sources. */
7800 void
7801 hold_keyboard_input (void)
7803 kbd_is_on_hold = 1;
7806 /* Resume reading input from keyboard sources. */
7808 void
7809 unhold_keyboard_input (void)
7811 kbd_is_on_hold = 0;
7814 /* Return true if keyboard input is on hold, zero otherwise. */
7816 bool
7817 kbd_on_hold_p (void)
7819 return kbd_is_on_hold;
7823 /* Enumeration of and access to system processes a-la ps(1). */
7825 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7826 0, 0, 0,
7827 doc: /* Return a list of numerical process IDs of all running processes.
7828 If this functionality is unsupported, return nil.
7830 See `process-attributes' for getting attributes of a process given its ID. */)
7831 (void)
7833 return list_system_processes ();
7836 DEFUN ("process-attributes", Fprocess_attributes,
7837 Sprocess_attributes, 1, 1, 0,
7838 doc: /* Return attributes of the process given by its PID, a number.
7840 Value is an alist where each element is a cons cell of the form
7842 (KEY . VALUE)
7844 If this functionality is unsupported, the value is nil.
7846 See `list-system-processes' for getting a list of all process IDs.
7848 The KEYs of the attributes that this function may return are listed
7849 below, together with the type of the associated VALUE (in parentheses).
7850 Not all platforms support all of these attributes; unsupported
7851 attributes will not appear in the returned alist.
7852 Unless explicitly indicated otherwise, numbers can have either
7853 integer or floating point values.
7855 euid -- Effective user User ID of the process (number)
7856 user -- User name corresponding to euid (string)
7857 egid -- Effective user Group ID of the process (number)
7858 group -- Group name corresponding to egid (string)
7859 comm -- Command name (executable name only) (string)
7860 state -- Process state code, such as "S", "R", or "T" (string)
7861 ppid -- Parent process ID (number)
7862 pgrp -- Process group ID (number)
7863 sess -- Session ID, i.e. process ID of session leader (number)
7864 ttname -- Controlling tty name (string)
7865 tpgid -- ID of foreground process group on the process's tty (number)
7866 minflt -- number of minor page faults (number)
7867 majflt -- number of major page faults (number)
7868 cminflt -- cumulative number of minor page faults (number)
7869 cmajflt -- cumulative number of major page faults (number)
7870 utime -- user time used by the process, in (current-time) format,
7871 which is a list of integers (HIGH LOW USEC PSEC)
7872 stime -- system time used by the process (current-time)
7873 time -- sum of utime and stime (current-time)
7874 cutime -- user time used by the process and its children (current-time)
7875 cstime -- system time used by the process and its children (current-time)
7876 ctime -- sum of cutime and cstime (current-time)
7877 pri -- priority of the process (number)
7878 nice -- nice value of the process (number)
7879 thcount -- process thread count (number)
7880 start -- time the process started (current-time)
7881 vsize -- virtual memory size of the process in KB's (number)
7882 rss -- resident set size of the process in KB's (number)
7883 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7884 pcpu -- percents of CPU time used by the process (floating-point number)
7885 pmem -- percents of total physical memory used by process's resident set
7886 (floating-point number)
7887 args -- command line which invoked the process (string). */)
7888 ( Lisp_Object pid)
7890 return system_process_attributes (pid);
7893 #ifdef subprocesses
7894 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7895 Invoke this after init_process_emacs, and after glib and/or GNUstep
7896 futz with the SIGCHLD handler, but before Emacs forks any children.
7897 This function's caller should block SIGCHLD. */
7899 void
7900 catch_child_signal (void)
7902 struct sigaction action, old_action;
7903 sigset_t oldset;
7904 emacs_sigaction_init (&action, deliver_child_signal);
7905 block_child_signal (&oldset);
7906 sigaction (SIGCHLD, &action, &old_action);
7907 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7908 || ! (old_action.sa_flags & SA_SIGINFO));
7910 if (old_action.sa_handler != deliver_child_signal)
7911 lib_child_handler
7912 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7913 ? dummy_handler
7914 : old_action.sa_handler);
7915 unblock_child_signal (&oldset);
7917 #endif /* subprocesses */
7919 /* Limit the number of open files to the value it had at startup. */
7921 void
7922 restore_nofile_limit (void)
7924 #ifdef HAVE_SETRLIMIT
7925 if (FD_SETSIZE < nofile_limit.rlim_cur)
7926 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7927 #endif
7931 /* This is not called "init_process" because that is the name of a
7932 Mach system call, so it would cause problems on Darwin systems. */
7933 void
7934 init_process_emacs (int sockfd)
7936 #ifdef subprocesses
7937 int i;
7939 inhibit_sentinels = 0;
7941 #ifndef CANNOT_DUMP
7942 if (! noninteractive || initialized)
7943 #endif
7945 #if defined HAVE_GLIB && !defined WINDOWSNT
7946 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7947 this should always fail, but is enough to initialize glib's
7948 private SIGCHLD handler, allowing catch_child_signal to copy
7949 it into lib_child_handler. */
7950 g_source_unref (g_child_watch_source_new (getpid ()));
7951 #endif
7952 catch_child_signal ();
7955 #ifdef HAVE_SETRLIMIT
7956 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
7957 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
7958 nofile_limit.rlim_cur = 0;
7959 else if (FD_SETSIZE < nofile_limit.rlim_cur)
7961 struct rlimit rlim = nofile_limit;
7962 rlim.rlim_cur = FD_SETSIZE;
7963 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
7964 nofile_limit.rlim_cur = 0;
7966 #endif
7968 external_sock_fd = sockfd;
7969 max_desc = -1;
7970 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7972 num_pending_connects = 0;
7974 process_output_delay_count = 0;
7975 process_output_skip = 0;
7977 /* Don't do this, it caused infinite select loops. The display
7978 method should call add_keyboard_wait_descriptor on stdin if it
7979 needs that. */
7980 #if 0
7981 FD_SET (0, &input_wait_mask);
7982 #endif
7984 Vprocess_alist = Qnil;
7985 deleted_pid_list = Qnil;
7986 for (i = 0; i < FD_SETSIZE; i++)
7988 chan_process[i] = Qnil;
7989 proc_buffered_char[i] = -1;
7991 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7992 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7993 #ifdef DATAGRAM_SOCKETS
7994 memset (datagram_address, 0, sizeof datagram_address);
7995 #endif
7997 #if defined (DARWIN_OS)
7998 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7999 processes. As such, we only change the default value. */
8000 if (initialized)
8002 char const *release = (STRINGP (Voperating_system_release)
8003 ? SSDATA (Voperating_system_release)
8004 : 0);
8005 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
8006 Vprocess_connection_type = Qnil;
8009 #endif
8010 #endif /* subprocesses */
8011 kbd_is_on_hold = 0;
8014 void
8015 syms_of_process (void)
8017 #ifdef subprocesses
8019 DEFSYM (Qprocessp, "processp");
8020 DEFSYM (Qrun, "run");
8021 DEFSYM (Qstop, "stop");
8022 DEFSYM (Qsignal, "signal");
8024 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8025 here again. */
8027 DEFSYM (Qopen, "open");
8028 DEFSYM (Qclosed, "closed");
8029 DEFSYM (Qconnect, "connect");
8030 DEFSYM (Qfailed, "failed");
8031 DEFSYM (Qlisten, "listen");
8032 DEFSYM (Qlocal, "local");
8033 DEFSYM (Qipv4, "ipv4");
8034 #ifdef AF_INET6
8035 DEFSYM (Qipv6, "ipv6");
8036 #endif
8037 DEFSYM (Qdatagram, "datagram");
8038 DEFSYM (Qseqpacket, "seqpacket");
8040 DEFSYM (QCport, ":port");
8041 DEFSYM (QCspeed, ":speed");
8042 DEFSYM (QCprocess, ":process");
8044 DEFSYM (QCbytesize, ":bytesize");
8045 DEFSYM (QCstopbits, ":stopbits");
8046 DEFSYM (QCparity, ":parity");
8047 DEFSYM (Qodd, "odd");
8048 DEFSYM (Qeven, "even");
8049 DEFSYM (QCflowcontrol, ":flowcontrol");
8050 DEFSYM (Qhw, "hw");
8051 DEFSYM (Qsw, "sw");
8052 DEFSYM (QCsummary, ":summary");
8054 DEFSYM (Qreal, "real");
8055 DEFSYM (Qnetwork, "network");
8056 DEFSYM (Qserial, "serial");
8057 DEFSYM (Qpipe, "pipe");
8058 DEFSYM (QCbuffer, ":buffer");
8059 DEFSYM (QChost, ":host");
8060 DEFSYM (QCservice, ":service");
8061 DEFSYM (QClocal, ":local");
8062 DEFSYM (QCremote, ":remote");
8063 DEFSYM (QCcoding, ":coding");
8064 DEFSYM (QCserver, ":server");
8065 DEFSYM (QCnowait, ":nowait");
8066 DEFSYM (QCsentinel, ":sentinel");
8067 DEFSYM (QCuse_external_socket, ":use-external-socket");
8068 DEFSYM (QCtls_parameters, ":tls-parameters");
8069 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8070 DEFSYM (QClog, ":log");
8071 DEFSYM (QCnoquery, ":noquery");
8072 DEFSYM (QCstop, ":stop");
8073 DEFSYM (QCplist, ":plist");
8074 DEFSYM (QCcommand, ":command");
8075 DEFSYM (QCconnection_type, ":connection-type");
8076 DEFSYM (QCstderr, ":stderr");
8077 DEFSYM (Qpty, "pty");
8078 DEFSYM (Qpipe, "pipe");
8080 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8082 staticpro (&Vprocess_alist);
8083 staticpro (&deleted_pid_list);
8085 #endif /* subprocesses */
8087 DEFSYM (QCname, ":name");
8088 DEFSYM (QCtype, ":type");
8090 DEFSYM (Qeuid, "euid");
8091 DEFSYM (Qegid, "egid");
8092 DEFSYM (Quser, "user");
8093 DEFSYM (Qgroup, "group");
8094 DEFSYM (Qcomm, "comm");
8095 DEFSYM (Qstate, "state");
8096 DEFSYM (Qppid, "ppid");
8097 DEFSYM (Qpgrp, "pgrp");
8098 DEFSYM (Qsess, "sess");
8099 DEFSYM (Qttname, "ttname");
8100 DEFSYM (Qtpgid, "tpgid");
8101 DEFSYM (Qminflt, "minflt");
8102 DEFSYM (Qmajflt, "majflt");
8103 DEFSYM (Qcminflt, "cminflt");
8104 DEFSYM (Qcmajflt, "cmajflt");
8105 DEFSYM (Qutime, "utime");
8106 DEFSYM (Qstime, "stime");
8107 DEFSYM (Qtime, "time");
8108 DEFSYM (Qcutime, "cutime");
8109 DEFSYM (Qcstime, "cstime");
8110 DEFSYM (Qctime, "ctime");
8111 #ifdef subprocesses
8112 DEFSYM (Qinternal_default_process_sentinel,
8113 "internal-default-process-sentinel");
8114 DEFSYM (Qinternal_default_process_filter,
8115 "internal-default-process-filter");
8116 #endif
8117 DEFSYM (Qpri, "pri");
8118 DEFSYM (Qnice, "nice");
8119 DEFSYM (Qthcount, "thcount");
8120 DEFSYM (Qstart, "start");
8121 DEFSYM (Qvsize, "vsize");
8122 DEFSYM (Qrss, "rss");
8123 DEFSYM (Qetime, "etime");
8124 DEFSYM (Qpcpu, "pcpu");
8125 DEFSYM (Qpmem, "pmem");
8126 DEFSYM (Qargs, "args");
8128 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8129 doc: /* Non-nil means delete processes immediately when they exit.
8130 A value of nil means don't delete them until `list-processes' is run. */);
8132 delete_exited_processes = 1;
8134 #ifdef subprocesses
8135 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8136 doc: /* Control type of device used to communicate with subprocesses.
8137 Values are nil to use a pipe, or t or `pty' to use a pty.
8138 The value has no effect if the system has no ptys or if all ptys are busy:
8139 then a pipe is used in any case.
8140 The value takes effect when `start-process' is called. */);
8141 Vprocess_connection_type = Qt;
8143 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8144 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8145 On some systems, when Emacs reads the output from a subprocess, the output data
8146 is read in very small blocks, potentially resulting in very poor performance.
8147 This behavior can be remedied to some extent by setting this variable to a
8148 non-nil value, as it will automatically delay reading from such processes, to
8149 allow them to produce more output before Emacs tries to read it.
8150 If the value is t, the delay is reset after each write to the process; any other
8151 non-nil value means that the delay is not reset on write.
8152 The variable takes effect when `start-process' is called. */);
8153 Vprocess_adaptive_read_buffering = Qt;
8155 defsubr (&Sprocessp);
8156 defsubr (&Sget_process);
8157 defsubr (&Sdelete_process);
8158 defsubr (&Sprocess_status);
8159 defsubr (&Sprocess_exit_status);
8160 defsubr (&Sprocess_id);
8161 defsubr (&Sprocess_name);
8162 defsubr (&Sprocess_tty_name);
8163 defsubr (&Sprocess_command);
8164 defsubr (&Sset_process_buffer);
8165 defsubr (&Sprocess_buffer);
8166 defsubr (&Sprocess_mark);
8167 defsubr (&Sset_process_filter);
8168 defsubr (&Sprocess_filter);
8169 defsubr (&Sset_process_sentinel);
8170 defsubr (&Sprocess_sentinel);
8171 defsubr (&Sset_process_thread);
8172 defsubr (&Sprocess_thread);
8173 defsubr (&Sset_process_window_size);
8174 defsubr (&Sset_process_inherit_coding_system_flag);
8175 defsubr (&Sset_process_query_on_exit_flag);
8176 defsubr (&Sprocess_query_on_exit_flag);
8177 defsubr (&Sprocess_contact);
8178 defsubr (&Sprocess_plist);
8179 defsubr (&Sset_process_plist);
8180 defsubr (&Sprocess_list);
8181 defsubr (&Smake_process);
8182 defsubr (&Smake_pipe_process);
8183 defsubr (&Sserial_process_configure);
8184 defsubr (&Smake_serial_process);
8185 defsubr (&Sset_network_process_option);
8186 defsubr (&Smake_network_process);
8187 defsubr (&Sformat_network_address);
8188 defsubr (&Snetwork_interface_list);
8189 defsubr (&Snetwork_interface_info);
8190 #ifdef DATAGRAM_SOCKETS
8191 defsubr (&Sprocess_datagram_address);
8192 defsubr (&Sset_process_datagram_address);
8193 #endif
8194 defsubr (&Saccept_process_output);
8195 defsubr (&Sprocess_send_region);
8196 defsubr (&Sprocess_send_string);
8197 defsubr (&Sinterrupt_process);
8198 defsubr (&Skill_process);
8199 defsubr (&Squit_process);
8200 defsubr (&Sstop_process);
8201 defsubr (&Scontinue_process);
8202 defsubr (&Sprocess_running_child_p);
8203 defsubr (&Sprocess_send_eof);
8204 defsubr (&Ssignal_process);
8205 defsubr (&Swaiting_for_user_input_p);
8206 defsubr (&Sprocess_type);
8207 defsubr (&Sinternal_default_process_sentinel);
8208 defsubr (&Sinternal_default_process_filter);
8209 defsubr (&Sset_process_coding_system);
8210 defsubr (&Sprocess_coding_system);
8211 defsubr (&Sset_process_filter_multibyte);
8212 defsubr (&Sprocess_filter_multibyte_p);
8215 Lisp_Object subfeatures = Qnil;
8216 const struct socket_options *sopt;
8218 #define ADD_SUBFEATURE(key, val) \
8219 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8221 ADD_SUBFEATURE (QCnowait, Qt);
8222 #ifdef DATAGRAM_SOCKETS
8223 ADD_SUBFEATURE (QCtype, Qdatagram);
8224 #endif
8225 #ifdef HAVE_SEQPACKET
8226 ADD_SUBFEATURE (QCtype, Qseqpacket);
8227 #endif
8228 #ifdef HAVE_LOCAL_SOCKETS
8229 ADD_SUBFEATURE (QCfamily, Qlocal);
8230 #endif
8231 ADD_SUBFEATURE (QCfamily, Qipv4);
8232 #ifdef AF_INET6
8233 ADD_SUBFEATURE (QCfamily, Qipv6);
8234 #endif
8235 #ifdef HAVE_GETSOCKNAME
8236 ADD_SUBFEATURE (QCservice, Qt);
8237 #endif
8238 ADD_SUBFEATURE (QCserver, Qt);
8240 for (sopt = socket_options; sopt->name; sopt++)
8241 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8243 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8246 #endif /* subprocesses */
8248 defsubr (&Sget_buffer_process);
8249 defsubr (&Sprocess_inherit_coding_system_flag);
8250 defsubr (&Slist_system_processes);
8251 defsubr (&Sprocess_attributes);