Avoid leaving garbage on screen when using 'raise' display property
[emacs.git] / src / process.c
blob2f2e5c1b2515a9a631492decdebc033a32a8f532
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2017 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 maybe_quit ();
3436 ret = connect (s, sa, addrlen);
3437 xerrno = errno;
3439 if (ret == 0 || xerrno == EISCONN)
3441 /* The unwind-protect will be discarded afterwards. */
3442 break;
3445 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3446 break;
3448 #ifndef WINDOWSNT
3449 if (xerrno == EINTR)
3451 /* Unlike most other syscalls connect() cannot be called
3452 again. (That would return EALREADY.) The proper way to
3453 wait for completion is pselect(). */
3454 int sc;
3455 socklen_t len;
3456 fd_set fdset;
3457 retry_select:
3458 FD_ZERO (&fdset);
3459 FD_SET (s, &fdset);
3460 maybe_quit ();
3461 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3462 if (sc == -1)
3464 if (errno == EINTR)
3465 goto retry_select;
3466 else
3467 report_file_error ("Failed select", Qnil);
3469 eassert (sc > 0);
3471 len = sizeof xerrno;
3472 eassert (FD_ISSET (s, &fdset));
3473 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3474 report_file_error ("Failed getsockopt", Qnil);
3475 if (xerrno == 0)
3476 break;
3477 if (NILP (addrinfos))
3478 report_file_errno ("Failed connect", Qnil, xerrno);
3480 #endif /* !WINDOWSNT */
3482 /* Discard the unwind protect closing S. */
3483 specpdl_ptr = specpdl + count;
3484 emacs_close (s);
3485 s = -1;
3486 if (0 <= socket_to_use)
3487 break;
3489 #ifdef WINDOWSNT
3490 if (xerrno == EINTR)
3491 goto retry_connect;
3492 #endif
3495 if (s >= 0)
3497 #ifdef DATAGRAM_SOCKETS
3498 if (p->socktype == SOCK_DGRAM)
3500 if (datagram_address[s].sa)
3501 emacs_abort ();
3503 datagram_address[s].sa = xmalloc (addrlen);
3504 datagram_address[s].len = addrlen;
3505 if (p->is_server)
3507 Lisp_Object remote;
3508 memset (datagram_address[s].sa, 0, addrlen);
3509 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3511 int rfamily;
3512 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3513 if (rlen != 0 && rfamily == family
3514 && rlen == addrlen)
3515 conv_lisp_to_sockaddr (rfamily, remote,
3516 datagram_address[s].sa, rlen);
3519 else
3520 memcpy (datagram_address[s].sa, sa, addrlen);
3522 #endif
3524 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3525 conv_sockaddr_to_lisp (sa, addrlen));
3526 #ifdef HAVE_GETSOCKNAME
3527 if (!p->is_server)
3529 struct sockaddr_in sa1;
3530 socklen_t len1 = sizeof (sa1);
3531 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3532 contact = Fplist_put (contact, QClocal,
3533 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3535 #endif
3538 if (s < 0)
3540 /* If non-blocking got this far - and failed - assume non-blocking is
3541 not supported after all. This is probably a wrong assumption, but
3542 the normal blocking calls to open-network-stream handles this error
3543 better. */
3544 if (p->is_non_blocking_client)
3545 return;
3547 report_file_errno ((p->is_server
3548 ? "make server process failed"
3549 : "make client process failed"),
3550 contact, xerrno);
3553 inch = s;
3554 outch = s;
3556 chan_process[inch] = proc;
3558 fcntl (inch, F_SETFL, O_NONBLOCK);
3560 p = XPROCESS (proc);
3561 p->open_fd[SUBPROCESS_STDIN] = inch;
3562 p->infd = inch;
3563 p->outfd = outch;
3565 /* Discard the unwind protect for closing S, if any. */
3566 specpdl_ptr = specpdl + count;
3568 if (p->is_server && p->socktype != SOCK_DGRAM)
3569 pset_status (p, Qlisten);
3571 /* Make the process marker point into the process buffer (if any). */
3572 if (BUFFERP (p->buffer))
3573 set_marker_both (p->mark, p->buffer,
3574 BUF_ZV (XBUFFER (p->buffer)),
3575 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3577 if (p->is_non_blocking_client)
3579 /* We may get here if connect did succeed immediately. However,
3580 in that case, we still need to signal this like a non-blocking
3581 connection. */
3582 if (! (connecting_status (p->status)
3583 && EQ (XCDR (p->status), addrinfos)))
3584 pset_status (p, Fcons (Qconnect, addrinfos));
3585 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3586 add_non_blocking_write_fd (inch);
3588 else
3589 /* A server may have a client filter setting of Qt, but it must
3590 still listen for incoming connects unless it is stopped. */
3591 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3592 || (EQ (p->status, Qlisten) && NILP (p->command)))
3593 add_process_read_fd (inch);
3595 if (inch > max_desc)
3596 max_desc = inch;
3598 /* Set up the masks based on the process filter. */
3599 set_process_filter_masks (p);
3601 setup_process_coding_systems (proc);
3603 #ifdef HAVE_GNUTLS
3604 /* Continue the asynchronous connection. */
3605 if (!NILP (p->gnutls_boot_parameters))
3607 Lisp_Object boot, params = p->gnutls_boot_parameters;
3609 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3610 p->gnutls_boot_parameters = Qnil;
3612 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3613 /* Run sentinels, etc. */
3614 finish_after_tls_connection (proc);
3615 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3617 deactivate_process (proc);
3618 if (NILP (boot))
3619 pset_status (p, list2 (Qfailed,
3620 build_string ("TLS negotiation failed")));
3621 else
3622 pset_status (p, list2 (Qfailed, boot));
3625 #endif
3629 /* Create a network stream/datagram client/server process. Treated
3630 exactly like a normal process when reading and writing. Primary
3631 differences are in status display and process deletion. A network
3632 connection has no PID; you cannot signal it. All you can do is
3633 stop/continue it and deactivate/close it via delete-process. */
3635 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3636 0, MANY, 0,
3637 doc: /* Create and return a network server or client process.
3639 In Emacs, network connections are represented by process objects, so
3640 input and output work as for subprocesses and `delete-process' closes
3641 a network connection. However, a network process has no process id,
3642 it cannot be signaled, and the status codes are different from normal
3643 processes.
3645 Arguments are specified as keyword/argument pairs. The following
3646 arguments are defined:
3648 :name NAME -- NAME is name for process. It is modified if necessary
3649 to make it unique.
3651 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3652 with the process. Process output goes at end of that buffer, unless
3653 you specify an output stream or filter function to handle the output.
3654 BUFFER may be also nil, meaning that this process is not associated
3655 with any buffer.
3657 :host HOST -- HOST is name of the host to connect to, or its IP
3658 address. The symbol `local' specifies the local host. If specified
3659 for a server process, it must be a valid name or address for the local
3660 host, and only clients connecting to that address will be accepted.
3662 :service SERVICE -- SERVICE is name of the service desired, or an
3663 integer specifying a port number to connect to. If SERVICE is t,
3664 a random port number is selected for the server. A port number can
3665 be specified as an integer string, e.g., "80", as well as an integer.
3667 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3668 stream type connection, `datagram' creates a datagram type connection,
3669 `seqpacket' creates a reliable datagram connection.
3671 :family FAMILY -- FAMILY is the address (and protocol) family for the
3672 service specified by HOST and SERVICE. The default (nil) is to use
3673 whatever address family (IPv4 or IPv6) that is defined for the host
3674 and port number specified by HOST and SERVICE. Other address families
3675 supported are:
3676 local -- for a local (i.e. UNIX) address specified by SERVICE.
3677 ipv4 -- use IPv4 address family only.
3678 ipv6 -- use IPv6 address family only.
3680 :local ADDRESS -- ADDRESS is the local address used for the connection.
3681 This parameter is ignored when opening a client process. When specified
3682 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3684 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3685 connection. This parameter is ignored when opening a stream server
3686 process. For a datagram server process, it specifies the initial
3687 setting of the remote datagram address. When specified for a client
3688 process, the FAMILY, HOST, and SERVICE args are ignored.
3690 The format of ADDRESS depends on the address family:
3691 - An IPv4 address is represented as an vector of integers [A B C D P]
3692 corresponding to numeric IP address A.B.C.D and port number P.
3693 - A local address is represented as a string with the address in the
3694 local address space.
3695 - An "unsupported family" address is represented by a cons (F . AV)
3696 where F is the family number and AV is a vector containing the socket
3697 address data with one element per address data byte. Do not rely on
3698 this format in portable code, as it may depend on implementation
3699 defined constants, data sizes, and data structure alignment.
3701 :coding CODING -- If CODING is a symbol, it specifies the coding
3702 system used for both reading and writing for this process. If CODING
3703 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3704 ENCODING is used for writing.
3706 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3707 process, return without waiting for the connection to complete;
3708 instead, the sentinel function will be called with second arg matching
3709 "open" (if successful) or "failed" when the connect completes.
3710 Default is to use a blocking connect (i.e. wait) for stream type
3711 connections.
3713 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3714 running when Emacs is exited.
3716 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3717 In the stopped state, a server process does not accept new
3718 connections, and a client process does not handle incoming traffic.
3719 The stopped state is cleared by `continue-process' and set by
3720 `stop-process'.
3722 :filter FILTER -- Install FILTER as the process filter.
3724 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3725 process filter are multibyte, otherwise they are unibyte.
3726 If this keyword is not specified, the strings are multibyte if
3727 the default value of `enable-multibyte-characters' is non-nil.
3729 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3731 :log LOG -- Install LOG as the server process log function. This
3732 function is called when the server accepts a network connection from a
3733 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3734 is the server process, CLIENT is the new process for the connection,
3735 and MESSAGE is a string.
3737 :plist PLIST -- Install PLIST as the new process's initial plist.
3739 :tls-parameters LIST -- is a list that should be supplied if you're
3740 opening a TLS connection. The first element is the TLS type (either
3741 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3742 be a keyword list accepted by gnutls-boot (as returned by
3743 `gnutls-boot-parameters').
3745 :server QLEN -- if QLEN is non-nil, create a server process for the
3746 specified FAMILY, SERVICE, and connection type (stream or datagram).
3747 If QLEN is an integer, it is used as the max. length of the server's
3748 pending connection queue (also known as the backlog); the default
3749 queue length is 5. Default is to create a client process.
3751 The following network options can be specified for this connection:
3753 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3754 :dontroute BOOL -- Only send to directly connected hosts.
3755 :keepalive BOOL -- Send keep-alive messages on network stream.
3756 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3757 :oobinline BOOL -- Place out-of-band data in receive data stream.
3758 :priority INT -- Set protocol defined priority for sent packets.
3759 :reuseaddr BOOL -- Allow reusing a recently used local address
3760 (this is allowed by default for a server process).
3761 :bindtodevice NAME -- bind to interface NAME. Using this may require
3762 special privileges on some systems.
3763 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3764 been passed to Emacs. If Emacs wasn't
3765 passed a socket, this option is silently
3766 ignored.
3769 Consult the relevant system programmer's manual pages for more
3770 information on using these options.
3773 A server process will listen for and accept connections from clients.
3774 When a client connection is accepted, a new network process is created
3775 for the connection with the following parameters:
3777 - The client's process name is constructed by concatenating the server
3778 process's NAME and a client identification string.
3779 - If the FILTER argument is non-nil, the client process will not get a
3780 separate process buffer; otherwise, the client's process buffer is a newly
3781 created buffer named after the server process's BUFFER name or process
3782 NAME concatenated with the client identification string.
3783 - The connection type and the process filter and sentinel parameters are
3784 inherited from the server process's TYPE, FILTER and SENTINEL.
3785 - The client process's contact info is set according to the client's
3786 addressing information (typically an IP address and a port number).
3787 - The client process's plist is initialized from the server's plist.
3789 Notice that the FILTER and SENTINEL args are never used directly by
3790 the server process. Also, the BUFFER argument is not used directly by
3791 the server process, but via the optional :log function, accepted (and
3792 failed) connections may be logged in the server process's buffer.
3794 The original argument list, modified with the actual connection
3795 information, is available via the `process-contact' function.
3797 usage: (make-network-process &rest ARGS) */)
3798 (ptrdiff_t nargs, Lisp_Object *args)
3800 Lisp_Object proc;
3801 Lisp_Object contact;
3802 struct Lisp_Process *p;
3803 const char *portstring;
3804 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3805 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3806 #ifdef HAVE_LOCAL_SOCKETS
3807 struct sockaddr_un address_un;
3808 #endif
3809 EMACS_INT port = 0;
3810 Lisp_Object tem;
3811 Lisp_Object name, buffer, host, service, address;
3812 Lisp_Object filter, sentinel, use_external_socket_p;
3813 Lisp_Object addrinfos = Qnil;
3814 int socktype;
3815 int family = -1;
3816 enum { any_protocol = 0 };
3817 #ifdef HAVE_GETADDRINFO_A
3818 struct gaicb *dns_request = NULL;
3819 #endif
3820 ptrdiff_t count = SPECPDL_INDEX ();
3822 if (nargs == 0)
3823 return Qnil;
3825 /* Save arguments for process-contact and clone-process. */
3826 contact = Flist (nargs, args);
3828 #ifdef WINDOWSNT
3829 /* Ensure socket support is loaded if available. */
3830 init_winsock (TRUE);
3831 #endif
3833 /* :type TYPE (nil: stream, datagram */
3834 tem = Fplist_get (contact, QCtype);
3835 if (NILP (tem))
3836 socktype = SOCK_STREAM;
3837 #ifdef DATAGRAM_SOCKETS
3838 else if (EQ (tem, Qdatagram))
3839 socktype = SOCK_DGRAM;
3840 #endif
3841 #ifdef HAVE_SEQPACKET
3842 else if (EQ (tem, Qseqpacket))
3843 socktype = SOCK_SEQPACKET;
3844 #endif
3845 else
3846 error ("Unsupported connection type");
3848 name = Fplist_get (contact, QCname);
3849 buffer = Fplist_get (contact, QCbuffer);
3850 filter = Fplist_get (contact, QCfilter);
3851 sentinel = Fplist_get (contact, QCsentinel);
3852 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3854 CHECK_STRING (name);
3856 /* :local ADDRESS or :remote ADDRESS */
3857 tem = Fplist_get (contact, QCserver);
3858 if (NILP (tem))
3859 address = Fplist_get (contact, QCremote);
3860 else
3861 address = Fplist_get (contact, QClocal);
3862 if (!NILP (address))
3864 host = service = Qnil;
3866 if (!get_lisp_to_sockaddr_size (address, &family))
3867 error ("Malformed :address");
3869 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3870 goto open_socket;
3873 /* :family FAMILY -- nil (for Inet), local, or integer. */
3874 tem = Fplist_get (contact, QCfamily);
3875 if (NILP (tem))
3877 #ifdef AF_INET6
3878 family = AF_UNSPEC;
3879 #else
3880 family = AF_INET;
3881 #endif
3883 #ifdef HAVE_LOCAL_SOCKETS
3884 else if (EQ (tem, Qlocal))
3885 family = AF_LOCAL;
3886 #endif
3887 #ifdef AF_INET6
3888 else if (EQ (tem, Qipv6))
3889 family = AF_INET6;
3890 #endif
3891 else if (EQ (tem, Qipv4))
3892 family = AF_INET;
3893 else if (TYPE_RANGED_INTEGERP (int, tem))
3894 family = XINT (tem);
3895 else
3896 error ("Unknown address family");
3898 /* :service SERVICE -- string, integer (port number), or t (random port). */
3899 service = Fplist_get (contact, QCservice);
3901 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3902 host = Fplist_get (contact, QChost);
3903 if (NILP (host))
3905 /* The "connection" function gets it bind info from the address we're
3906 given, so use this dummy address if nothing is specified. */
3907 #ifdef HAVE_LOCAL_SOCKETS
3908 if (family != AF_LOCAL)
3909 #endif
3910 host = build_string ("127.0.0.1");
3912 else
3914 if (EQ (host, Qlocal))
3915 /* Depending on setup, "localhost" may map to different IPv4 and/or
3916 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3917 host = build_string ("127.0.0.1");
3918 CHECK_STRING (host);
3921 #ifdef HAVE_LOCAL_SOCKETS
3922 if (family == AF_LOCAL)
3924 if (!NILP (host))
3926 message (":family local ignores the :host property");
3927 contact = Fplist_put (contact, QChost, Qnil);
3928 host = Qnil;
3930 CHECK_STRING (service);
3931 if (sizeof address_un.sun_path <= SBYTES (service))
3932 error ("Service name too long");
3933 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3934 goto open_socket;
3936 #endif
3938 /* Slow down polling to every ten seconds.
3939 Some kernels have a bug which causes retrying connect to fail
3940 after a connect. Polling can interfere with gethostbyname too. */
3941 #ifdef POLL_FOR_INPUT
3942 if (socktype != SOCK_DGRAM)
3944 record_unwind_protect_void (run_all_atimers);
3945 bind_polling_period (10);
3947 #endif
3949 if (!NILP (host))
3951 /* SERVICE can either be a string or int.
3952 Convert to a C string for later use by getaddrinfo. */
3953 if (EQ (service, Qt))
3955 portstring = "0";
3956 portstringlen = 1;
3958 else if (INTEGERP (service))
3960 portstring = portbuf;
3961 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3963 else
3965 CHECK_STRING (service);
3966 portstring = SSDATA (service);
3967 portstringlen = SBYTES (service);
3971 #ifdef HAVE_GETADDRINFO_A
3972 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3974 ptrdiff_t hostlen = SBYTES (host);
3975 struct req
3977 struct gaicb gaicb;
3978 struct addrinfo hints;
3979 char str[FLEXIBLE_ARRAY_MEMBER];
3980 } *req = xmalloc (FLEXSIZEOF (struct req, str,
3981 hostlen + 1 + portstringlen + 1));
3982 dns_request = &req->gaicb;
3983 dns_request->ar_name = req->str;
3984 dns_request->ar_service = req->str + hostlen + 1;
3985 dns_request->ar_request = &req->hints;
3986 dns_request->ar_result = NULL;
3987 memset (&req->hints, 0, sizeof req->hints);
3988 req->hints.ai_family = family;
3989 req->hints.ai_socktype = socktype;
3990 strcpy (req->str, SSDATA (host));
3991 strcpy (req->str + hostlen + 1, portstring);
3993 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3994 if (ret)
3995 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3997 goto open_socket;
3999 #endif /* HAVE_GETADDRINFO_A */
4001 /* If we have a host, use getaddrinfo to resolve both host and service.
4002 Otherwise, use getservbyname to lookup the service. */
4004 if (!NILP (host))
4006 struct addrinfo *res, *lres;
4007 int ret;
4009 maybe_quit ();
4011 struct addrinfo hints;
4012 memset (&hints, 0, sizeof hints);
4013 hints.ai_family = family;
4014 hints.ai_socktype = socktype;
4016 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4017 if (ret)
4018 #ifdef HAVE_GAI_STRERROR
4020 synchronize_system_messages_locale ();
4021 char const *str = gai_strerror (ret);
4022 if (! NILP (Vlocale_coding_system))
4023 str = SSDATA (code_convert_string_norecord
4024 (build_string (str), Vlocale_coding_system, 0));
4025 error ("%s/%s %s", SSDATA (host), portstring, str);
4027 #else
4028 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4029 #endif
4031 for (lres = res; lres; lres = lres->ai_next)
4032 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4034 addrinfos = Fnreverse (addrinfos);
4036 freeaddrinfo (res);
4038 goto open_socket;
4041 /* No hostname has been specified (e.g., a local server process). */
4043 if (EQ (service, Qt))
4044 port = 0;
4045 else if (INTEGERP (service))
4046 port = XINT (service);
4047 else
4049 CHECK_STRING (service);
4051 port = -1;
4052 if (SBYTES (service) != 0)
4054 /* Allow the service to be a string containing the port number,
4055 because that's allowed if you have getaddrbyname. */
4056 char *service_end;
4057 long int lport = strtol (SSDATA (service), &service_end, 10);
4058 if (service_end == SSDATA (service) + SBYTES (service))
4059 port = lport;
4060 else
4062 struct servent *svc_info
4063 = getservbyname (SSDATA (service),
4064 socktype == SOCK_DGRAM ? "udp" : "tcp");
4065 if (svc_info)
4066 port = ntohs (svc_info->s_port);
4071 if (! (0 <= port && port < 1 << 16))
4073 AUTO_STRING (unknown_service, "Unknown service: %s");
4074 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4077 open_socket:
4079 if (!NILP (buffer))
4080 buffer = Fget_buffer_create (buffer);
4082 /* Unwind bind_polling_period. */
4083 unbind_to (count, Qnil);
4085 proc = make_process (name);
4086 record_unwind_protect (remove_process, proc);
4087 p = XPROCESS (proc);
4088 pset_childp (p, contact);
4089 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4090 pset_type (p, Qnetwork);
4092 pset_buffer (p, buffer);
4093 pset_sentinel (p, sentinel);
4094 pset_filter (p, filter);
4095 pset_log (p, Fplist_get (contact, QClog));
4096 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4097 p->kill_without_query = 1;
4098 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4099 pset_command (p, Qt);
4100 eassert (p->pid == 0);
4101 p->backlog = 5;
4102 eassert (! p->is_non_blocking_client);
4103 eassert (! p->is_server);
4104 p->port = port;
4105 p->socktype = socktype;
4106 #ifdef HAVE_GETADDRINFO_A
4107 eassert (! p->dns_request);
4108 #endif
4109 #ifdef HAVE_GNUTLS
4110 tem = Fplist_get (contact, QCtls_parameters);
4111 CHECK_LIST (tem);
4112 p->gnutls_boot_parameters = tem;
4113 #endif
4115 set_network_socket_coding_system (proc, host, service, name);
4117 /* :server BOOL */
4118 tem = Fplist_get (contact, QCserver);
4119 if (!NILP (tem))
4121 /* Don't support network sockets when non-blocking mode is
4122 not available, since a blocked Emacs is not useful. */
4123 p->is_server = true;
4124 if (TYPE_RANGED_INTEGERP (int, tem))
4125 p->backlog = XINT (tem);
4128 /* :nowait BOOL */
4129 if (!p->is_server && socktype != SOCK_DGRAM
4130 && !NILP (Fplist_get (contact, QCnowait)))
4131 p->is_non_blocking_client = true;
4133 bool postpone_connection = false;
4134 #ifdef HAVE_GETADDRINFO_A
4135 /* With async address resolution, the list of addresses is empty, so
4136 postpone connecting to the server. */
4137 if (!p->is_server && NILP (addrinfos))
4139 p->dns_request = dns_request;
4140 p->status = list1 (Qconnect);
4141 postpone_connection = true;
4143 #endif
4144 if (! postpone_connection)
4145 connect_network_socket (proc, addrinfos, use_external_socket_p);
4147 specpdl_ptr = specpdl + count;
4148 return proc;
4152 #ifdef HAVE_NET_IF_H
4154 #ifdef SIOCGIFCONF
4155 static Lisp_Object
4156 network_interface_list (void)
4158 struct ifconf ifconf;
4159 struct ifreq *ifreq;
4160 void *buf = NULL;
4161 ptrdiff_t buf_size = 512;
4162 int s;
4163 Lisp_Object res;
4164 ptrdiff_t count;
4166 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4167 if (s < 0)
4168 return Qnil;
4169 count = SPECPDL_INDEX ();
4170 record_unwind_protect_int (close_file_unwind, s);
4174 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4175 ifconf.ifc_buf = buf;
4176 ifconf.ifc_len = buf_size;
4177 if (ioctl (s, SIOCGIFCONF, &ifconf))
4179 emacs_close (s);
4180 xfree (buf);
4181 return Qnil;
4184 while (ifconf.ifc_len == buf_size);
4186 res = unbind_to (count, Qnil);
4187 ifreq = ifconf.ifc_req;
4188 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4190 struct ifreq *ifq = ifreq;
4191 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4192 #define SIZEOF_IFREQ(sif) \
4193 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4194 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4196 int len = SIZEOF_IFREQ (ifq);
4197 #else
4198 int len = sizeof (*ifreq);
4199 #endif
4200 char namebuf[sizeof (ifq->ifr_name) + 1];
4201 ifreq = (struct ifreq *) ((char *) ifreq + len);
4203 if (ifq->ifr_addr.sa_family != AF_INET)
4204 continue;
4206 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4207 namebuf[sizeof (ifq->ifr_name)] = 0;
4208 res = Fcons (Fcons (build_string (namebuf),
4209 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4210 sizeof (struct sockaddr))),
4211 res);
4214 xfree (buf);
4215 return res;
4217 #endif /* SIOCGIFCONF */
4219 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4221 struct ifflag_def {
4222 int flag_bit;
4223 const char *flag_sym;
4226 static const struct ifflag_def ifflag_table[] = {
4227 #ifdef IFF_UP
4228 { IFF_UP, "up" },
4229 #endif
4230 #ifdef IFF_BROADCAST
4231 { IFF_BROADCAST, "broadcast" },
4232 #endif
4233 #ifdef IFF_DEBUG
4234 { IFF_DEBUG, "debug" },
4235 #endif
4236 #ifdef IFF_LOOPBACK
4237 { IFF_LOOPBACK, "loopback" },
4238 #endif
4239 #ifdef IFF_POINTOPOINT
4240 { IFF_POINTOPOINT, "pointopoint" },
4241 #endif
4242 #ifdef IFF_RUNNING
4243 { IFF_RUNNING, "running" },
4244 #endif
4245 #ifdef IFF_NOARP
4246 { IFF_NOARP, "noarp" },
4247 #endif
4248 #ifdef IFF_PROMISC
4249 { IFF_PROMISC, "promisc" },
4250 #endif
4251 #ifdef IFF_NOTRAILERS
4252 #ifdef NS_IMPL_COCOA
4253 /* Really means smart, notrailers is obsolete. */
4254 { IFF_NOTRAILERS, "smart" },
4255 #else
4256 { IFF_NOTRAILERS, "notrailers" },
4257 #endif
4258 #endif
4259 #ifdef IFF_ALLMULTI
4260 { IFF_ALLMULTI, "allmulti" },
4261 #endif
4262 #ifdef IFF_MASTER
4263 { IFF_MASTER, "master" },
4264 #endif
4265 #ifdef IFF_SLAVE
4266 { IFF_SLAVE, "slave" },
4267 #endif
4268 #ifdef IFF_MULTICAST
4269 { IFF_MULTICAST, "multicast" },
4270 #endif
4271 #ifdef IFF_PORTSEL
4272 { IFF_PORTSEL, "portsel" },
4273 #endif
4274 #ifdef IFF_AUTOMEDIA
4275 { IFF_AUTOMEDIA, "automedia" },
4276 #endif
4277 #ifdef IFF_DYNAMIC
4278 { IFF_DYNAMIC, "dynamic" },
4279 #endif
4280 #ifdef IFF_OACTIVE
4281 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4282 #endif
4283 #ifdef IFF_SIMPLEX
4284 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4285 #endif
4286 #ifdef IFF_LINK0
4287 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4288 #endif
4289 #ifdef IFF_LINK1
4290 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4291 #endif
4292 #ifdef IFF_LINK2
4293 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4294 #endif
4295 { 0, 0 }
4298 static Lisp_Object
4299 network_interface_info (Lisp_Object ifname)
4301 struct ifreq rq;
4302 Lisp_Object res = Qnil;
4303 Lisp_Object elt;
4304 int s;
4305 bool any = 0;
4306 ptrdiff_t count;
4307 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4308 && defined HAVE_GETIFADDRS && defined LLADDR)
4309 struct ifaddrs *ifap;
4310 #endif
4312 CHECK_STRING (ifname);
4314 if (sizeof rq.ifr_name <= SBYTES (ifname))
4315 error ("interface name too long");
4316 lispstpcpy (rq.ifr_name, ifname);
4318 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4319 if (s < 0)
4320 return Qnil;
4321 count = SPECPDL_INDEX ();
4322 record_unwind_protect_int (close_file_unwind, s);
4324 elt = Qnil;
4325 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4326 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4328 int flags = rq.ifr_flags;
4329 const struct ifflag_def *fp;
4330 int fnum;
4332 /* If flags is smaller than int (i.e. short) it may have the high bit set
4333 due to IFF_MULTICAST. In that case, sign extending it into
4334 an int is wrong. */
4335 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4336 flags = (unsigned short) rq.ifr_flags;
4338 any = 1;
4339 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4341 if (flags & fp->flag_bit)
4343 elt = Fcons (intern (fp->flag_sym), elt);
4344 flags -= fp->flag_bit;
4347 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4349 if (flags & 1)
4351 elt = Fcons (make_number (fnum), elt);
4355 #endif
4356 res = Fcons (elt, res);
4358 elt = Qnil;
4359 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4360 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4362 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4363 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4364 int n;
4366 any = 1;
4367 for (n = 0; n < 6; n++)
4368 p->contents[n] = make_number (((unsigned char *)
4369 &rq.ifr_hwaddr.sa_data[0])
4370 [n]);
4371 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4373 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4374 if (getifaddrs (&ifap) != -1)
4376 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4377 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4378 struct ifaddrs *it;
4380 for (it = ifap; it != NULL; it = it->ifa_next)
4382 struct sockaddr_dl *sdl = (struct sockaddr_dl *) it->ifa_addr;
4383 unsigned char linkaddr[6];
4384 int n;
4386 if (it->ifa_addr->sa_family != AF_LINK
4387 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4388 || sdl->sdl_alen != 6)
4389 continue;
4391 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4392 for (n = 0; n < 6; n++)
4393 p->contents[n] = make_number (linkaddr[n]);
4395 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4396 break;
4399 #ifdef HAVE_FREEIFADDRS
4400 freeifaddrs (ifap);
4401 #endif
4403 #endif /* HAVE_GETIFADDRS && LLADDR */
4405 res = Fcons (elt, res);
4407 elt = Qnil;
4408 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4409 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4411 any = 1;
4412 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4413 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4414 #else
4415 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4416 #endif
4418 #endif
4419 res = Fcons (elt, res);
4421 elt = Qnil;
4422 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4423 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4425 any = 1;
4426 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4428 #endif
4429 res = Fcons (elt, res);
4431 elt = Qnil;
4432 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4433 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4435 any = 1;
4436 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4438 #endif
4439 res = Fcons (elt, res);
4441 return unbind_to (count, any ? res : Qnil);
4443 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4444 #endif /* defined (HAVE_NET_IF_H) */
4446 DEFUN ("network-interface-list", Fnetwork_interface_list,
4447 Snetwork_interface_list, 0, 0, 0,
4448 doc: /* Return an alist of all network interfaces and their network address.
4449 Each element is a cons, the car of which is a string containing the
4450 interface name, and the cdr is the network address in internal
4451 format; see the description of ADDRESS in `make-network-process'.
4453 If the information is not available, return nil. */)
4454 (void)
4456 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4457 return network_interface_list ();
4458 #else
4459 return Qnil;
4460 #endif
4463 DEFUN ("network-interface-info", Fnetwork_interface_info,
4464 Snetwork_interface_info, 1, 1, 0,
4465 doc: /* Return information about network interface named IFNAME.
4466 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4467 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4468 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4469 FLAGS is the current flags of the interface.
4471 Data that is unavailable is returned as nil. */)
4472 (Lisp_Object ifname)
4474 #if ((defined HAVE_NET_IF_H \
4475 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4476 || defined SIOCGIFFLAGS)) \
4477 || defined WINDOWSNT)
4478 return network_interface_info (ifname);
4479 #else
4480 return Qnil;
4481 #endif
4484 /* Turn off input and output for process PROC. */
4486 static void
4487 deactivate_process (Lisp_Object proc)
4489 int inchannel;
4490 struct Lisp_Process *p = XPROCESS (proc);
4491 int i;
4493 #ifdef HAVE_GNUTLS
4494 /* Delete GnuTLS structures in PROC, if any. */
4495 emacs_gnutls_deinit (proc);
4496 #endif /* HAVE_GNUTLS */
4498 if (p->read_output_delay > 0)
4500 if (--process_output_delay_count < 0)
4501 process_output_delay_count = 0;
4502 p->read_output_delay = 0;
4503 p->read_output_skip = 0;
4506 /* Beware SIGCHLD hereabouts. */
4508 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4509 close_process_fd (&p->open_fd[i]);
4511 inchannel = p->infd;
4512 if (inchannel >= 0)
4514 p->infd = -1;
4515 p->outfd = -1;
4516 #ifdef DATAGRAM_SOCKETS
4517 if (DATAGRAM_CHAN_P (inchannel))
4519 xfree (datagram_address[inchannel].sa);
4520 datagram_address[inchannel].sa = 0;
4521 datagram_address[inchannel].len = 0;
4523 #endif
4524 chan_process[inchannel] = Qnil;
4525 delete_read_fd (inchannel);
4526 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4527 delete_write_fd (inchannel);
4528 if (inchannel == max_desc)
4529 recompute_max_desc ();
4534 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4535 0, 4, 0,
4536 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4537 It is given to their filter functions.
4538 Optional argument PROCESS means do not return until output has been
4539 received from PROCESS.
4541 Optional second argument SECONDS and third argument MILLISEC
4542 specify a timeout; return after that much time even if there is
4543 no subprocess output. If SECONDS is a floating point number,
4544 it specifies a fractional number of seconds to wait.
4545 The MILLISEC argument is obsolete and should be avoided.
4547 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4548 from PROCESS only, suspending reading output from other processes.
4549 If JUST-THIS-ONE is an integer, don't run any timers either.
4550 Return non-nil if we received any output from PROCESS (or, if PROCESS
4551 is nil, from any process) before the timeout expired. */)
4552 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4553 Lisp_Object just_this_one)
4555 intmax_t secs;
4556 int nsecs;
4558 if (! NILP (process))
4560 CHECK_PROCESS (process);
4561 struct Lisp_Process *proc = XPROCESS (process);
4563 /* Can't wait for a process that is dedicated to a different
4564 thread. */
4565 if (!EQ (proc->thread, Qnil) && !EQ (proc->thread, Fcurrent_thread ()))
4566 error ("Attempt to accept output from process %s locked to thread %s",
4567 SDATA (proc->name), SDATA (XTHREAD (proc->thread)->name));
4569 else
4570 just_this_one = Qnil;
4572 if (!NILP (millisec))
4573 { /* Obsolete calling convention using integers rather than floats. */
4574 CHECK_NUMBER (millisec);
4575 if (NILP (seconds))
4576 seconds = make_float (XINT (millisec) / 1000.0);
4577 else
4579 CHECK_NUMBER (seconds);
4580 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4584 secs = 0;
4585 nsecs = -1;
4587 if (!NILP (seconds))
4589 if (INTEGERP (seconds))
4591 if (XINT (seconds) > 0)
4593 secs = XINT (seconds);
4594 nsecs = 0;
4597 else if (FLOATP (seconds))
4599 if (XFLOAT_DATA (seconds) > 0)
4601 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4602 secs = min (t.tv_sec, WAIT_READING_MAX);
4603 nsecs = t.tv_nsec;
4606 else
4607 wrong_type_argument (Qnumberp, seconds);
4609 else if (! NILP (process))
4610 nsecs = 0;
4612 return
4613 ((wait_reading_process_output (secs, nsecs, 0, 0,
4614 Qnil,
4615 !NILP (process) ? XPROCESS (process) : NULL,
4616 (NILP (just_this_one) ? 0
4617 : !INTEGERP (just_this_one) ? 1 : -1))
4618 <= 0)
4619 ? Qnil : Qt);
4622 /* Accept a connection for server process SERVER on CHANNEL. */
4624 static EMACS_INT connect_counter = 0;
4626 static void
4627 server_accept_connection (Lisp_Object server, int channel)
4629 Lisp_Object proc, caller, name, buffer;
4630 Lisp_Object contact, host, service;
4631 struct Lisp_Process *ps = XPROCESS (server);
4632 struct Lisp_Process *p;
4633 int s;
4634 union u_sockaddr {
4635 struct sockaddr sa;
4636 struct sockaddr_in in;
4637 #ifdef AF_INET6
4638 struct sockaddr_in6 in6;
4639 #endif
4640 #ifdef HAVE_LOCAL_SOCKETS
4641 struct sockaddr_un un;
4642 #endif
4643 } saddr;
4644 socklen_t len = sizeof saddr;
4645 ptrdiff_t count;
4647 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4649 if (s < 0)
4651 int code = errno;
4652 if (!would_block (code) && !NILP (ps->log))
4653 call3 (ps->log, server, Qnil,
4654 concat3 (build_string ("accept failed with code"),
4655 Fnumber_to_string (make_number (code)),
4656 build_string ("\n")));
4657 return;
4660 count = SPECPDL_INDEX ();
4661 record_unwind_protect_int (close_file_unwind, s);
4663 connect_counter++;
4665 /* Setup a new process to handle the connection. */
4667 /* Generate a unique identification of the caller, and build contact
4668 information for this process. */
4669 host = Qt;
4670 service = Qnil;
4671 switch (saddr.sa.sa_family)
4673 case AF_INET:
4675 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4677 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4678 host = CALLN (Fformat, ipv4_format,
4679 make_number (ip[0]), make_number (ip[1]),
4680 make_number (ip[2]), make_number (ip[3]));
4681 service = make_number (ntohs (saddr.in.sin_port));
4682 AUTO_STRING (caller_format, " <%s:%d>");
4683 caller = CALLN (Fformat, caller_format, host, service);
4685 break;
4687 #ifdef AF_INET6
4688 case AF_INET6:
4690 Lisp_Object args[9];
4691 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4692 int i;
4694 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4695 args[0] = ipv6_format;
4696 for (i = 0; i < 8; i++)
4697 args[i + 1] = make_number (ntohs (ip6[i]));
4698 host = CALLMANY (Fformat, args);
4699 service = make_number (ntohs (saddr.in.sin_port));
4700 AUTO_STRING (caller_format, " <[%s]:%d>");
4701 caller = CALLN (Fformat, caller_format, host, service);
4703 break;
4704 #endif
4706 #ifdef HAVE_LOCAL_SOCKETS
4707 case AF_LOCAL:
4708 #endif
4709 default:
4710 caller = Fnumber_to_string (make_number (connect_counter));
4711 AUTO_STRING (space_less_than, " <");
4712 AUTO_STRING (greater_than, ">");
4713 caller = concat3 (space_less_than, caller, greater_than);
4714 break;
4717 /* Create a new buffer name for this process if it doesn't have a
4718 filter. The new buffer name is based on the buffer name or
4719 process name of the server process concatenated with the caller
4720 identification. */
4722 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4723 || EQ (ps->filter, Qt)))
4724 buffer = Qnil;
4725 else
4727 buffer = ps->buffer;
4728 if (!NILP (buffer))
4729 buffer = Fbuffer_name (buffer);
4730 else
4731 buffer = ps->name;
4732 if (!NILP (buffer))
4734 buffer = concat2 (buffer, caller);
4735 buffer = Fget_buffer_create (buffer);
4739 /* Generate a unique name for the new server process. Combine the
4740 server process name with the caller identification. */
4742 name = concat2 (ps->name, caller);
4743 proc = make_process (name);
4745 chan_process[s] = proc;
4747 fcntl (s, F_SETFL, O_NONBLOCK);
4749 p = XPROCESS (proc);
4751 /* Build new contact information for this setup. */
4752 contact = Fcopy_sequence (ps->childp);
4753 contact = Fplist_put (contact, QCserver, Qnil);
4754 contact = Fplist_put (contact, QChost, host);
4755 if (!NILP (service))
4756 contact = Fplist_put (contact, QCservice, service);
4757 contact = Fplist_put (contact, QCremote,
4758 conv_sockaddr_to_lisp (&saddr.sa, len));
4759 #ifdef HAVE_GETSOCKNAME
4760 len = sizeof saddr;
4761 if (getsockname (s, &saddr.sa, &len) == 0)
4762 contact = Fplist_put (contact, QClocal,
4763 conv_sockaddr_to_lisp (&saddr.sa, len));
4764 #endif
4766 pset_childp (p, contact);
4767 pset_plist (p, Fcopy_sequence (ps->plist));
4768 pset_type (p, Qnetwork);
4770 pset_buffer (p, buffer);
4771 pset_sentinel (p, ps->sentinel);
4772 pset_filter (p, ps->filter);
4773 eassert (NILP (p->command));
4774 eassert (p->pid == 0);
4776 /* Discard the unwind protect for closing S. */
4777 specpdl_ptr = specpdl + count;
4779 p->open_fd[SUBPROCESS_STDIN] = s;
4780 p->infd = s;
4781 p->outfd = s;
4782 pset_status (p, Qrun);
4784 /* Client processes for accepted connections are not stopped initially. */
4785 if (!EQ (p->filter, Qt))
4786 add_process_read_fd (s);
4787 if (s > max_desc)
4788 max_desc = s;
4790 /* Setup coding system for new process based on server process.
4791 This seems to be the proper thing to do, as the coding system
4792 of the new process should reflect the settings at the time the
4793 server socket was opened; not the current settings. */
4795 pset_decode_coding_system (p, ps->decode_coding_system);
4796 pset_encode_coding_system (p, ps->encode_coding_system);
4797 setup_process_coding_systems (proc);
4799 pset_decoding_buf (p, empty_unibyte_string);
4800 eassert (p->decoding_carryover == 0);
4801 pset_encoding_buf (p, empty_unibyte_string);
4803 p->inherit_coding_system_flag
4804 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4806 AUTO_STRING (dash, "-");
4807 AUTO_STRING (nl, "\n");
4808 Lisp_Object host_string = STRINGP (host) ? host : dash;
4810 if (!NILP (ps->log))
4812 AUTO_STRING (accept_from, "accept from ");
4813 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4816 AUTO_STRING (open_from, "open from ");
4817 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4820 #ifdef HAVE_GETADDRINFO_A
4821 static Lisp_Object
4822 check_for_dns (Lisp_Object proc)
4824 struct Lisp_Process *p = XPROCESS (proc);
4825 Lisp_Object addrinfos = Qnil;
4827 /* Sanity check. */
4828 if (! p->dns_request)
4829 return Qnil;
4831 int ret = gai_error (p->dns_request);
4832 if (ret == EAI_INPROGRESS)
4833 return Qt;
4835 /* We got a response. */
4836 if (ret == 0)
4838 struct addrinfo *res;
4840 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4841 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4843 addrinfos = Fnreverse (addrinfos);
4845 /* The DNS lookup failed. */
4846 else if (connecting_status (p->status))
4848 deactivate_process (proc);
4849 pset_status (p, (list2
4850 (Qfailed,
4851 concat3 (build_string ("Name lookup of "),
4852 build_string (p->dns_request->ar_name),
4853 build_string (" failed")))));
4856 free_dns_request (proc);
4858 /* This process should not already be connected (or killed). */
4859 if (! connecting_status (p->status))
4860 return Qnil;
4862 return addrinfos;
4865 #endif /* HAVE_GETADDRINFO_A */
4867 static void
4868 wait_for_socket_fds (Lisp_Object process, char const *name)
4870 while (XPROCESS (process)->infd < 0
4871 && connecting_status (XPROCESS (process)->status))
4873 add_to_log ("Waiting for socket from %s...", build_string (name));
4874 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4878 static void
4879 wait_while_connecting (Lisp_Object process)
4881 while (connecting_status (XPROCESS (process)->status))
4883 add_to_log ("Waiting for connection...");
4884 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4888 static void
4889 wait_for_tls_negotiation (Lisp_Object process)
4891 #ifdef HAVE_GNUTLS
4892 while (XPROCESS (process)->gnutls_p
4893 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4895 add_to_log ("Waiting for TLS...");
4896 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4898 #endif
4901 static void
4902 wait_reading_process_output_unwind (int data)
4904 clear_waiting_thread_info ();
4905 waiting_for_user_input_p = data;
4908 /* This is here so breakpoints can be put on it. */
4909 static void
4910 wait_reading_process_output_1 (void)
4914 /* Read and dispose of subprocess output while waiting for timeout to
4915 elapse and/or keyboard input to be available.
4917 TIME_LIMIT is:
4918 timeout in seconds
4919 If negative, gobble data immediately available but don't wait for any.
4921 NSECS is:
4922 an additional duration to wait, measured in nanoseconds
4923 If TIME_LIMIT is zero, then:
4924 If NSECS == 0, there is no limit.
4925 If NSECS > 0, the timeout consists of NSECS only.
4926 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4928 READ_KBD is:
4929 0 to ignore keyboard input, or
4930 1 to return when input is available, or
4931 -1 meaning caller will actually read the input, so don't throw to
4932 the quit handler
4934 DO_DISPLAY means redisplay should be done to show subprocess
4935 output that arrives.
4937 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4938 (and gobble terminal input into the buffer if any arrives).
4940 If WAIT_PROC is specified, wait until something arrives from that
4941 process.
4943 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4944 (suspending output from other processes). A negative value
4945 means don't run any timers either.
4947 Return positive if we received input from WAIT_PROC (or from any
4948 process if WAIT_PROC is null), zero if we attempted to receive
4949 input but got none, and negative if we didn't even try. */
4952 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4953 bool do_display,
4954 Lisp_Object wait_for_cell,
4955 struct Lisp_Process *wait_proc, int just_wait_proc)
4957 int channel, nfds;
4958 fd_set Available;
4959 fd_set Writeok;
4960 bool check_write;
4961 int check_delay;
4962 bool no_avail;
4963 int xerrno;
4964 Lisp_Object proc;
4965 struct timespec timeout, end_time, timer_delay;
4966 struct timespec got_output_end_time = invalid_timespec ();
4967 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4968 int got_some_output = -1;
4969 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4970 bool retry_for_async;
4971 #endif
4972 ptrdiff_t count = SPECPDL_INDEX ();
4974 /* Close to the current time if known, an invalid timespec otherwise. */
4975 struct timespec now = invalid_timespec ();
4977 eassert (wait_proc == NULL
4978 || EQ (wait_proc->thread, Qnil)
4979 || XTHREAD (wait_proc->thread) == current_thread);
4981 FD_ZERO (&Available);
4982 FD_ZERO (&Writeok);
4984 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4985 && !(CONSP (wait_proc->status)
4986 && EQ (XCAR (wait_proc->status), Qexit)))
4987 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4989 record_unwind_protect_int (wait_reading_process_output_unwind,
4990 waiting_for_user_input_p);
4991 waiting_for_user_input_p = read_kbd;
4993 if (TYPE_MAXIMUM (time_t) < time_limit)
4994 time_limit = TYPE_MAXIMUM (time_t);
4996 if (time_limit < 0 || nsecs < 0)
4997 wait = MINIMUM;
4998 else if (time_limit > 0 || nsecs > 0)
5000 wait = TIMEOUT;
5001 now = current_timespec ();
5002 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5004 else
5005 wait = INFINITY;
5007 while (1)
5009 bool process_skipped = false;
5011 /* If calling from keyboard input, do not quit
5012 since we want to return C-g as an input character.
5013 Otherwise, do pending quit if requested. */
5014 if (read_kbd >= 0)
5015 maybe_quit ();
5016 else if (pending_signals)
5017 process_pending_signals ();
5019 /* Exit now if the cell we're waiting for became non-nil. */
5020 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5021 break;
5023 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5025 Lisp_Object process_list_head, aproc;
5026 struct Lisp_Process *p;
5028 retry_for_async = false;
5029 FOR_EACH_PROCESS(process_list_head, aproc)
5031 p = XPROCESS (aproc);
5033 if (! wait_proc || p == wait_proc)
5035 #ifdef HAVE_GETADDRINFO_A
5036 /* Check for pending DNS requests. */
5037 if (p->dns_request)
5039 Lisp_Object addrinfos = check_for_dns (aproc);
5040 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5041 connect_network_socket (aproc, addrinfos, Qnil);
5042 else
5043 retry_for_async = true;
5045 #endif
5046 #ifdef HAVE_GNUTLS
5047 /* Continue TLS negotiation. */
5048 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5049 && p->is_non_blocking_client)
5051 gnutls_try_handshake (p);
5052 p->gnutls_handshakes_tried++;
5054 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5056 gnutls_verify_boot (aproc, Qnil);
5057 finish_after_tls_connection (aproc);
5059 else
5061 retry_for_async = true;
5062 if (p->gnutls_handshakes_tried
5063 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5065 deactivate_process (aproc);
5066 pset_status (p, list2 (Qfailed,
5067 build_string ("TLS negotiation failed")));
5071 #endif
5075 #endif /* GETADDRINFO_A or GNUTLS */
5077 /* Compute time from now till when time limit is up. */
5078 /* Exit if already run out. */
5079 if (wait == TIMEOUT)
5081 if (!timespec_valid_p (now))
5082 now = current_timespec ();
5083 if (timespec_cmp (end_time, now) <= 0)
5084 break;
5085 timeout = timespec_sub (end_time, now);
5087 else
5088 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5090 /* Normally we run timers here.
5091 But not if wait_for_cell; in those cases,
5092 the wait is supposed to be short,
5093 and those callers cannot handle running arbitrary Lisp code here. */
5094 if (NILP (wait_for_cell)
5095 && just_wait_proc >= 0)
5099 unsigned old_timers_run = timers_run;
5100 struct buffer *old_buffer = current_buffer;
5101 Lisp_Object old_window = selected_window;
5103 timer_delay = timer_check ();
5105 /* If a timer has run, this might have changed buffers
5106 an alike. Make read_key_sequence aware of that. */
5107 if (timers_run != old_timers_run
5108 && (old_buffer != current_buffer
5109 || !EQ (old_window, selected_window))
5110 && waiting_for_user_input_p == -1)
5111 record_asynch_buffer_change ();
5113 if (timers_run != old_timers_run && do_display)
5114 /* We must retry, since a timer may have requeued itself
5115 and that could alter the time_delay. */
5116 redisplay_preserve_echo_area (9);
5117 else
5118 break;
5120 while (!detect_input_pending ());
5122 /* If there is unread keyboard input, also return. */
5123 if (read_kbd != 0
5124 && requeued_events_pending_p ())
5125 break;
5127 /* This is so a breakpoint can be put here. */
5128 if (!timespec_valid_p (timer_delay))
5129 wait_reading_process_output_1 ();
5132 /* Cause C-g and alarm signals to take immediate action,
5133 and cause input available signals to zero out timeout.
5135 It is important that we do this before checking for process
5136 activity. If we get a SIGCHLD after the explicit checks for
5137 process activity, timeout is the only way we will know. */
5138 if (read_kbd < 0)
5139 set_waiting_for_input (&timeout);
5141 /* If status of something has changed, and no input is
5142 available, notify the user of the change right away. After
5143 this explicit check, we'll let the SIGCHLD handler zap
5144 timeout to get our attention. */
5145 if (update_tick != process_tick)
5147 fd_set Atemp;
5148 fd_set Ctemp;
5150 if (kbd_on_hold_p ())
5151 FD_ZERO (&Atemp);
5152 else
5153 compute_input_wait_mask (&Atemp);
5154 compute_write_mask (&Ctemp);
5156 timeout = make_timespec (0, 0);
5157 if ((thread_select (pselect, max_desc + 1,
5158 &Atemp,
5159 (num_pending_connects > 0 ? &Ctemp : NULL),
5160 NULL, &timeout, NULL)
5161 <= 0))
5163 /* It's okay for us to do this and then continue with
5164 the loop, since timeout has already been zeroed out. */
5165 clear_waiting_for_input ();
5166 got_some_output = status_notify (NULL, wait_proc);
5167 if (do_display) redisplay_preserve_echo_area (13);
5171 /* Don't wait for output from a non-running process. Just
5172 read whatever data has already been received. */
5173 if (wait_proc && wait_proc->raw_status_new)
5174 update_status (wait_proc);
5175 if (wait_proc
5176 && ! EQ (wait_proc->status, Qrun)
5177 && ! connecting_status (wait_proc->status))
5179 bool read_some_bytes = false;
5181 clear_waiting_for_input ();
5183 /* If data can be read from the process, do so until exhausted. */
5184 if (wait_proc->infd >= 0)
5186 XSETPROCESS (proc, wait_proc);
5188 while (true)
5190 int nread = read_process_output (proc, wait_proc->infd);
5191 if (nread < 0)
5193 if (errno == EIO || would_block (errno))
5194 break;
5196 else
5198 if (got_some_output < nread)
5199 got_some_output = nread;
5200 if (nread == 0)
5201 break;
5202 read_some_bytes = true;
5207 if (read_some_bytes && do_display)
5208 redisplay_preserve_echo_area (10);
5210 break;
5213 /* Wait till there is something to do. */
5215 if (wait_proc && just_wait_proc)
5217 if (wait_proc->infd < 0) /* Terminated. */
5218 break;
5219 FD_SET (wait_proc->infd, &Available);
5220 check_delay = 0;
5221 check_write = 0;
5223 else if (!NILP (wait_for_cell))
5225 compute_non_process_wait_mask (&Available);
5226 check_delay = 0;
5227 check_write = 0;
5229 else
5231 if (! read_kbd)
5232 compute_non_keyboard_wait_mask (&Available);
5233 else
5234 compute_input_wait_mask (&Available);
5235 compute_write_mask (&Writeok);
5236 check_delay = wait_proc ? 0 : process_output_delay_count;
5237 check_write = true;
5240 /* If frame size has changed or the window is newly mapped,
5241 redisplay now, before we start to wait. There is a race
5242 condition here; if a SIGIO arrives between now and the select
5243 and indicates that a frame is trashed, the select may block
5244 displaying a trashed screen. */
5245 if (frame_garbaged && do_display)
5247 clear_waiting_for_input ();
5248 redisplay_preserve_echo_area (11);
5249 if (read_kbd < 0)
5250 set_waiting_for_input (&timeout);
5253 /* Skip the `select' call if input is available and we're
5254 waiting for keyboard input or a cell change (which can be
5255 triggered by processing X events). In the latter case, set
5256 nfds to 1 to avoid breaking the loop. */
5257 no_avail = 0;
5258 if ((read_kbd || !NILP (wait_for_cell))
5259 && detect_input_pending ())
5261 nfds = read_kbd ? 0 : 1;
5262 no_avail = 1;
5263 FD_ZERO (&Available);
5265 else
5267 /* Set the timeout for adaptive read buffering if any
5268 process has non-zero read_output_skip and non-zero
5269 read_output_delay, and we are not reading output for a
5270 specific process. It is not executed if
5271 Vprocess_adaptive_read_buffering is nil. */
5272 if (process_output_skip && check_delay > 0)
5274 int adaptive_nsecs = timeout.tv_nsec;
5275 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5276 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5277 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5279 proc = chan_process[channel];
5280 if (NILP (proc))
5281 continue;
5282 /* Find minimum non-zero read_output_delay among the
5283 processes with non-zero read_output_skip. */
5284 if (XPROCESS (proc)->read_output_delay > 0)
5286 check_delay--;
5287 if (!XPROCESS (proc)->read_output_skip)
5288 continue;
5289 FD_CLR (channel, &Available);
5290 process_skipped = true;
5291 XPROCESS (proc)->read_output_skip = 0;
5292 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5293 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5296 timeout = make_timespec (0, adaptive_nsecs);
5297 process_output_skip = 0;
5300 /* If we've got some output and haven't limited our timeout
5301 with adaptive read buffering, limit it. */
5302 if (got_some_output > 0 && !process_skipped
5303 && (timeout.tv_sec
5304 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5305 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5308 if (NILP (wait_for_cell) && just_wait_proc >= 0
5309 && timespec_valid_p (timer_delay)
5310 && timespec_cmp (timer_delay, timeout) < 0)
5312 if (!timespec_valid_p (now))
5313 now = current_timespec ();
5314 struct timespec timeout_abs = timespec_add (now, timeout);
5315 if (!timespec_valid_p (got_output_end_time)
5316 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5317 got_output_end_time = timeout_abs;
5318 timeout = timer_delay;
5320 else
5321 got_output_end_time = invalid_timespec ();
5323 /* NOW can become inaccurate if time can pass during pselect. */
5324 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5325 now = invalid_timespec ();
5327 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5328 if (retry_for_async
5329 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5331 timeout.tv_sec = 0;
5332 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5334 #endif
5336 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5337 #if defined HAVE_GLIB && !defined HAVE_NS
5338 nfds = xg_select (max_desc + 1,
5339 &Available, (check_write ? &Writeok : 0),
5340 NULL, &timeout, NULL);
5341 #else /* !HAVE_GLIB */
5342 nfds = thread_select (
5343 # ifdef HAVE_NS
5344 ns_select
5345 # else
5346 pselect
5347 # endif
5348 , max_desc + 1,
5349 &Available,
5350 (check_write ? &Writeok : 0),
5351 NULL, &timeout, NULL);
5352 #endif /* !HAVE_GLIB */
5354 #ifdef HAVE_GNUTLS
5355 /* GnuTLS buffers data internally. In lowat mode it leaves
5356 some data in the TCP buffers so that select works, but
5357 with custom pull/push functions we need to check if some
5358 data is available in the buffers manually. */
5359 if (nfds == 0)
5361 fd_set tls_available;
5362 int set = 0;
5364 FD_ZERO (&tls_available);
5365 if (! wait_proc)
5367 /* We're not waiting on a specific process, so loop
5368 through all the channels and check for data.
5369 This is a workaround needed for some versions of
5370 the gnutls library -- 2.12.14 has been confirmed
5371 to need it. See
5372 http://comments.gmane.org/gmane.emacs.devel/145074 */
5373 for (channel = 0; channel < FD_SETSIZE; ++channel)
5374 if (! NILP (chan_process[channel]))
5376 struct Lisp_Process *p =
5377 XPROCESS (chan_process[channel]);
5378 if (p && p->gnutls_p && p->gnutls_state
5379 && ((emacs_gnutls_record_check_pending
5380 (p->gnutls_state))
5381 > 0))
5383 nfds++;
5384 eassert (p->infd == channel);
5385 FD_SET (p->infd, &tls_available);
5386 set++;
5390 else
5392 /* Check this specific channel. */
5393 if (wait_proc->gnutls_p /* Check for valid process. */
5394 && wait_proc->gnutls_state
5395 /* Do we have pending data? */
5396 && ((emacs_gnutls_record_check_pending
5397 (wait_proc->gnutls_state))
5398 > 0))
5400 nfds = 1;
5401 eassert (0 <= wait_proc->infd);
5402 /* Set to Available. */
5403 FD_SET (wait_proc->infd, &tls_available);
5404 set++;
5407 if (set)
5408 Available = tls_available;
5410 #endif
5413 xerrno = errno;
5415 /* Make C-g and alarm signals set flags again. */
5416 clear_waiting_for_input ();
5418 /* If we woke up due to SIGWINCH, actually change size now. */
5419 do_pending_window_change (0);
5421 if (nfds == 0)
5423 /* Exit the main loop if we've passed the requested timeout,
5424 or aren't skipping processes and got some output and
5425 haven't lowered our timeout due to timers or SIGIO and
5426 have waited a long amount of time due to repeated
5427 timers. */
5428 struct timespec huge_timespec
5429 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5430 struct timespec cmp_time = huge_timespec;
5431 if (wait < TIMEOUT)
5432 break;
5433 if (wait == TIMEOUT)
5434 cmp_time = end_time;
5435 if (!process_skipped && got_some_output > 0
5436 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5438 if (!timespec_valid_p (got_output_end_time))
5439 break;
5440 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5441 cmp_time = got_output_end_time;
5443 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5445 now = current_timespec ();
5446 if (timespec_cmp (cmp_time, now) <= 0)
5447 break;
5451 if (nfds < 0)
5453 if (xerrno == EINTR)
5454 no_avail = 1;
5455 else if (xerrno == EBADF)
5456 emacs_abort ();
5457 else
5458 report_file_errno ("Failed select", Qnil, xerrno);
5461 /* Check for keyboard input. */
5462 /* If there is any, return immediately
5463 to give it higher priority than subprocesses. */
5465 if (read_kbd != 0)
5467 unsigned old_timers_run = timers_run;
5468 struct buffer *old_buffer = current_buffer;
5469 Lisp_Object old_window = selected_window;
5470 bool leave = false;
5472 if (detect_input_pending_run_timers (do_display))
5474 swallow_events (do_display);
5475 if (detect_input_pending_run_timers (do_display))
5476 leave = true;
5479 /* If a timer has run, this might have changed buffers
5480 an alike. Make read_key_sequence aware of that. */
5481 if (timers_run != old_timers_run
5482 && waiting_for_user_input_p == -1
5483 && (old_buffer != current_buffer
5484 || !EQ (old_window, selected_window)))
5485 record_asynch_buffer_change ();
5487 if (leave)
5488 break;
5491 /* If there is unread keyboard input, also return. */
5492 if (read_kbd != 0
5493 && requeued_events_pending_p ())
5494 break;
5496 /* If we are not checking for keyboard input now,
5497 do process events (but don't run any timers).
5498 This is so that X events will be processed.
5499 Otherwise they may have to wait until polling takes place.
5500 That would causes delays in pasting selections, for example.
5502 (We used to do this only if wait_for_cell.) */
5503 if (read_kbd == 0 && detect_input_pending ())
5505 swallow_events (do_display);
5506 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5507 if (detect_input_pending ())
5508 break;
5509 #endif
5512 /* Exit now if the cell we're waiting for became non-nil. */
5513 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5514 break;
5516 #ifdef USABLE_SIGIO
5517 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5518 go read it. This can happen with X on BSD after logging out.
5519 In that case, there really is no input and no SIGIO,
5520 but select says there is input. */
5522 if (read_kbd && interrupt_input
5523 && keyboard_bit_set (&Available) && ! noninteractive)
5524 handle_input_available_signal (SIGIO);
5525 #endif
5527 /* If checking input just got us a size-change event from X,
5528 obey it now if we should. */
5529 if (read_kbd || ! NILP (wait_for_cell))
5530 do_pending_window_change (0);
5532 /* Check for data from a process. */
5533 if (no_avail || nfds == 0)
5534 continue;
5536 for (channel = 0; channel <= max_desc; ++channel)
5538 struct fd_callback_data *d = &fd_callback_info[channel];
5539 if (d->func
5540 && ((d->flags & FOR_READ
5541 && FD_ISSET (channel, &Available))
5542 || ((d->flags & FOR_WRITE)
5543 && FD_ISSET (channel, &Writeok))))
5544 d->func (channel, d->data);
5547 for (channel = 0; channel <= max_desc; channel++)
5549 if (FD_ISSET (channel, &Available)
5550 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5551 == PROCESS_FD))
5553 int nread;
5555 /* If waiting for this channel, arrange to return as
5556 soon as no more input to be processed. No more
5557 waiting. */
5558 proc = chan_process[channel];
5559 if (NILP (proc))
5560 continue;
5562 /* If this is a server stream socket, accept connection. */
5563 if (EQ (XPROCESS (proc)->status, Qlisten))
5565 server_accept_connection (proc, channel);
5566 continue;
5569 /* Read data from the process, starting with our
5570 buffered-ahead character if we have one. */
5572 nread = read_process_output (proc, channel);
5573 if ((!wait_proc || wait_proc == XPROCESS (proc))
5574 && got_some_output < nread)
5575 got_some_output = nread;
5576 if (nread > 0)
5578 /* Vacuum up any leftovers without waiting. */
5579 if (wait_proc == XPROCESS (proc))
5580 wait = MINIMUM;
5581 /* Since read_process_output can run a filter,
5582 which can call accept-process-output,
5583 don't try to read from any other processes
5584 before doing the select again. */
5585 FD_ZERO (&Available);
5587 if (do_display)
5588 redisplay_preserve_echo_area (12);
5590 else if (nread == -1 && would_block (errno))
5592 #ifdef WINDOWSNT
5593 /* FIXME: Is this special case still needed? */
5594 /* Note that we cannot distinguish between no input
5595 available now and a closed pipe.
5596 With luck, a closed pipe will be accompanied by
5597 subprocess termination and SIGCHLD. */
5598 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5599 && !PIPECONN_P (proc))
5601 #endif
5602 #ifdef HAVE_PTYS
5603 /* On some OSs with ptys, when the process on one end of
5604 a pty exits, the other end gets an error reading with
5605 errno = EIO instead of getting an EOF (0 bytes read).
5606 Therefore, if we get an error reading and errno =
5607 EIO, just continue, because the child process has
5608 exited and should clean itself up soon (e.g. when we
5609 get a SIGCHLD). */
5610 else if (nread == -1 && errno == EIO)
5612 struct Lisp_Process *p = XPROCESS (proc);
5614 /* Clear the descriptor now, so we only raise the
5615 signal once. */
5616 delete_read_fd (channel);
5618 if (p->pid == -2)
5620 /* If the EIO occurs on a pty, the SIGCHLD handler's
5621 waitpid call will not find the process object to
5622 delete. Do it here. */
5623 p->tick = ++process_tick;
5624 pset_status (p, Qfailed);
5627 #endif /* HAVE_PTYS */
5628 /* If we can detect process termination, don't consider the
5629 process gone just because its pipe is closed. */
5630 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5631 && !PIPECONN_P (proc))
5633 else if (nread == 0 && PIPECONN_P (proc))
5635 /* Preserve status of processes already terminated. */
5636 XPROCESS (proc)->tick = ++process_tick;
5637 deactivate_process (proc);
5638 if (EQ (XPROCESS (proc)->status, Qrun))
5639 pset_status (XPROCESS (proc),
5640 list2 (Qexit, make_number (0)));
5642 else
5644 /* Preserve status of processes already terminated. */
5645 XPROCESS (proc)->tick = ++process_tick;
5646 deactivate_process (proc);
5647 if (XPROCESS (proc)->raw_status_new)
5648 update_status (XPROCESS (proc));
5649 if (EQ (XPROCESS (proc)->status, Qrun))
5650 pset_status (XPROCESS (proc),
5651 list2 (Qexit, make_number (256)));
5654 if (FD_ISSET (channel, &Writeok)
5655 && (fd_callback_info[channel].flags
5656 & NON_BLOCKING_CONNECT_FD) != 0)
5658 struct Lisp_Process *p;
5660 delete_write_fd (channel);
5662 proc = chan_process[channel];
5663 if (NILP (proc))
5664 continue;
5666 p = XPROCESS (proc);
5668 #ifndef WINDOWSNT
5670 socklen_t xlen = sizeof (xerrno);
5671 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5672 xerrno = errno;
5674 #else
5675 /* On MS-Windows, getsockopt clears the error for the
5676 entire process, which may not be the right thing; see
5677 w32.c. Use getpeername instead. */
5679 struct sockaddr pname;
5680 socklen_t pnamelen = sizeof (pname);
5682 /* If connection failed, getpeername will fail. */
5683 xerrno = 0;
5684 if (getpeername (channel, &pname, &pnamelen) < 0)
5686 /* Obtain connect failure code through error slippage. */
5687 char dummy;
5688 xerrno = errno;
5689 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5690 xerrno = errno;
5693 #endif
5694 if (xerrno)
5696 Lisp_Object addrinfos
5697 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5698 if (!NILP (addrinfos))
5699 XSETCDR (p->status, XCDR (addrinfos));
5700 else
5702 p->tick = ++process_tick;
5703 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5705 deactivate_process (proc);
5706 if (!NILP (addrinfos))
5707 connect_network_socket (proc, addrinfos, Qnil);
5709 else
5711 #ifdef HAVE_GNUTLS
5712 /* If we have an incompletely set up TLS connection,
5713 then defer the sentinel signaling until
5714 later. */
5715 if (NILP (p->gnutls_boot_parameters)
5716 && !p->gnutls_p)
5717 #endif
5719 pset_status (p, Qrun);
5720 /* Execute the sentinel here. If we had relied on
5721 status_notify to do it later, it will read input
5722 from the process before calling the sentinel. */
5723 exec_sentinel (proc, build_string ("open\n"));
5726 if (0 <= p->infd && !EQ (p->filter, Qt)
5727 && !EQ (p->command, Qt))
5728 add_process_read_fd (p->infd);
5731 } /* End for each file descriptor. */
5732 } /* End while exit conditions not met. */
5734 unbind_to (count, Qnil);
5736 /* If calling from keyboard input, do not quit
5737 since we want to return C-g as an input character.
5738 Otherwise, do pending quit if requested. */
5739 if (read_kbd >= 0)
5741 /* Prevent input_pending from remaining set if we quit. */
5742 clear_input_pending ();
5743 maybe_quit ();
5746 return got_some_output;
5749 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5751 static Lisp_Object
5752 read_process_output_call (Lisp_Object fun_and_args)
5754 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5757 static Lisp_Object
5758 read_process_output_error_handler (Lisp_Object error_val)
5760 cmd_error_internal (error_val, "error in process filter: ");
5761 Vinhibit_quit = Qt;
5762 update_echo_area ();
5763 Fsleep_for (make_number (2), Qnil);
5764 return Qt;
5767 static void
5768 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5769 ssize_t nbytes,
5770 struct coding_system *coding);
5772 /* Read pending output from the process channel,
5773 starting with our buffered-ahead character if we have one.
5774 Yield number of decoded characters read.
5776 This function reads at most 4096 characters.
5777 If you want to read all available subprocess output,
5778 you must call it repeatedly until it returns zero.
5780 The characters read are decoded according to PROC's coding-system
5781 for decoding. */
5783 static int
5784 read_process_output (Lisp_Object proc, int channel)
5786 ssize_t nbytes;
5787 struct Lisp_Process *p = XPROCESS (proc);
5788 struct coding_system *coding = proc_decode_coding_system[channel];
5789 int carryover = p->decoding_carryover;
5790 enum { readmax = 4096 };
5791 ptrdiff_t count = SPECPDL_INDEX ();
5792 Lisp_Object odeactivate;
5793 char chars[sizeof coding->carryover + readmax];
5795 if (carryover)
5796 /* See the comment above. */
5797 memcpy (chars, SDATA (p->decoding_buf), carryover);
5799 #ifdef DATAGRAM_SOCKETS
5800 /* We have a working select, so proc_buffered_char is always -1. */
5801 if (DATAGRAM_CHAN_P (channel))
5803 socklen_t len = datagram_address[channel].len;
5804 nbytes = recvfrom (channel, chars + carryover, readmax,
5805 0, datagram_address[channel].sa, &len);
5807 else
5808 #endif
5810 bool buffered = proc_buffered_char[channel] >= 0;
5811 if (buffered)
5813 chars[carryover] = proc_buffered_char[channel];
5814 proc_buffered_char[channel] = -1;
5816 #ifdef HAVE_GNUTLS
5817 if (p->gnutls_p && p->gnutls_state)
5818 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5819 readmax - buffered);
5820 else
5821 #endif
5822 nbytes = emacs_read (channel, chars + carryover + buffered,
5823 readmax - buffered);
5824 if (nbytes > 0 && p->adaptive_read_buffering)
5826 int delay = p->read_output_delay;
5827 if (nbytes < 256)
5829 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5831 if (delay == 0)
5832 process_output_delay_count++;
5833 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5836 else if (delay > 0 && nbytes == readmax - buffered)
5838 delay -= READ_OUTPUT_DELAY_INCREMENT;
5839 if (delay == 0)
5840 process_output_delay_count--;
5842 p->read_output_delay = delay;
5843 if (delay)
5845 p->read_output_skip = 1;
5846 process_output_skip = 1;
5849 nbytes += buffered;
5850 nbytes += buffered && nbytes <= 0;
5853 p->decoding_carryover = 0;
5855 /* At this point, NBYTES holds number of bytes just received
5856 (including the one in proc_buffered_char[channel]). */
5857 if (nbytes <= 0)
5859 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5860 return nbytes;
5861 coding->mode |= CODING_MODE_LAST_BLOCK;
5864 /* Now set NBYTES how many bytes we must decode. */
5865 nbytes += carryover;
5867 odeactivate = Vdeactivate_mark;
5868 /* There's no good reason to let process filters change the current
5869 buffer, and many callers of accept-process-output, sit-for, and
5870 friends don't expect current-buffer to be changed from under them. */
5871 record_unwind_current_buffer ();
5873 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5875 /* Handling the process output should not deactivate the mark. */
5876 Vdeactivate_mark = odeactivate;
5878 unbind_to (count, Qnil);
5879 return nbytes;
5882 static void
5883 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5884 ssize_t nbytes,
5885 struct coding_system *coding)
5887 Lisp_Object outstream = p->filter;
5888 Lisp_Object text;
5889 bool outer_running_asynch_code = running_asynch_code;
5890 int waiting = waiting_for_user_input_p;
5892 #if 0
5893 Lisp_Object obuffer, okeymap;
5894 XSETBUFFER (obuffer, current_buffer);
5895 okeymap = BVAR (current_buffer, keymap);
5896 #endif
5898 /* We inhibit quit here instead of just catching it so that
5899 hitting ^G when a filter happens to be running won't screw
5900 it up. */
5901 specbind (Qinhibit_quit, Qt);
5902 specbind (Qlast_nonmenu_event, Qt);
5904 /* In case we get recursively called,
5905 and we already saved the match data nonrecursively,
5906 save the same match data in safely recursive fashion. */
5907 if (outer_running_asynch_code)
5909 Lisp_Object tem;
5910 /* Don't clobber the CURRENT match data, either! */
5911 tem = Fmatch_data (Qnil, Qnil, Qnil);
5912 restore_search_regs ();
5913 record_unwind_save_match_data ();
5914 Fset_match_data (tem, Qt);
5917 /* For speed, if a search happens within this code,
5918 save the match data in a special nonrecursive fashion. */
5919 running_asynch_code = 1;
5921 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5922 text = coding->dst_object;
5923 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5924 /* A new coding system might be found. */
5925 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5927 pset_decode_coding_system (p, Vlast_coding_system_used);
5929 /* Don't call setup_coding_system for
5930 proc_decode_coding_system[channel] here. It is done in
5931 detect_coding called via decode_coding above. */
5933 /* If a coding system for encoding is not yet decided, we set
5934 it as the same as coding-system for decoding.
5936 But, before doing that we must check if
5937 proc_encode_coding_system[p->outfd] surely points to a
5938 valid memory because p->outfd will be changed once EOF is
5939 sent to the process. */
5940 if (NILP (p->encode_coding_system) && p->outfd >= 0
5941 && proc_encode_coding_system[p->outfd])
5943 pset_encode_coding_system
5944 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5945 setup_coding_system (p->encode_coding_system,
5946 proc_encode_coding_system[p->outfd]);
5950 if (coding->carryover_bytes > 0)
5952 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5953 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5954 memcpy (SDATA (p->decoding_buf), coding->carryover,
5955 coding->carryover_bytes);
5956 p->decoding_carryover = coding->carryover_bytes;
5958 if (SBYTES (text) > 0)
5959 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5960 sometimes it's simply wrong to wrap (e.g. when called from
5961 accept-process-output). */
5962 internal_condition_case_1 (read_process_output_call,
5963 list3 (outstream, make_lisp_proc (p), text),
5964 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5965 read_process_output_error_handler);
5967 /* If we saved the match data nonrecursively, restore it now. */
5968 restore_search_regs ();
5969 running_asynch_code = outer_running_asynch_code;
5971 /* Restore waiting_for_user_input_p as it was
5972 when we were called, in case the filter clobbered it. */
5973 waiting_for_user_input_p = waiting;
5975 #if 0 /* Call record_asynch_buffer_change unconditionally,
5976 because we might have changed minor modes or other things
5977 that affect key bindings. */
5978 if (! EQ (Fcurrent_buffer (), obuffer)
5979 || ! EQ (current_buffer->keymap, okeymap))
5980 #endif
5981 /* But do it only if the caller is actually going to read events.
5982 Otherwise there's no need to make him wake up, and it could
5983 cause trouble (for example it would make sit_for return). */
5984 if (waiting_for_user_input_p == -1)
5985 record_asynch_buffer_change ();
5988 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5989 Sinternal_default_process_filter, 2, 2, 0,
5990 doc: /* Function used as default process filter.
5991 This inserts the process's output into its buffer, if there is one.
5992 Otherwise it discards the output. */)
5993 (Lisp_Object proc, Lisp_Object text)
5995 struct Lisp_Process *p;
5996 ptrdiff_t opoint;
5998 CHECK_PROCESS (proc);
5999 p = XPROCESS (proc);
6000 CHECK_STRING (text);
6002 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6004 Lisp_Object old_read_only;
6005 ptrdiff_t old_begv, old_zv;
6006 ptrdiff_t old_begv_byte, old_zv_byte;
6007 ptrdiff_t before, before_byte;
6008 ptrdiff_t opoint_byte;
6009 struct buffer *b;
6011 Fset_buffer (p->buffer);
6012 opoint = PT;
6013 opoint_byte = PT_BYTE;
6014 old_read_only = BVAR (current_buffer, read_only);
6015 old_begv = BEGV;
6016 old_zv = ZV;
6017 old_begv_byte = BEGV_BYTE;
6018 old_zv_byte = ZV_BYTE;
6020 bset_read_only (current_buffer, Qnil);
6022 /* Insert new output into buffer at the current end-of-output
6023 marker, thus preserving logical ordering of input and output. */
6024 if (XMARKER (p->mark)->buffer)
6025 set_point_from_marker (p->mark);
6026 else
6027 SET_PT_BOTH (ZV, ZV_BYTE);
6028 before = PT;
6029 before_byte = PT_BYTE;
6031 /* If the output marker is outside of the visible region, save
6032 the restriction and widen. */
6033 if (! (BEGV <= PT && PT <= ZV))
6034 Fwiden ();
6036 /* Adjust the multibyteness of TEXT to that of the buffer. */
6037 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6038 != ! STRING_MULTIBYTE (text))
6039 text = (STRING_MULTIBYTE (text)
6040 ? Fstring_as_unibyte (text)
6041 : Fstring_to_multibyte (text));
6042 /* Insert before markers in case we are inserting where
6043 the buffer's mark is, and the user's next command is Meta-y. */
6044 insert_from_string_before_markers (text, 0, 0,
6045 SCHARS (text), SBYTES (text), 0);
6047 /* Make sure the process marker's position is valid when the
6048 process buffer is changed in the signal_after_change above.
6049 W3 is known to do that. */
6050 if (BUFFERP (p->buffer)
6051 && (b = XBUFFER (p->buffer), b != current_buffer))
6052 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6053 else
6054 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6056 update_mode_lines = 23;
6058 /* Make sure opoint and the old restrictions
6059 float ahead of any new text just as point would. */
6060 if (opoint >= before)
6062 opoint += PT - before;
6063 opoint_byte += PT_BYTE - before_byte;
6065 if (old_begv > before)
6067 old_begv += PT - before;
6068 old_begv_byte += PT_BYTE - before_byte;
6070 if (old_zv >= before)
6072 old_zv += PT - before;
6073 old_zv_byte += PT_BYTE - before_byte;
6076 /* If the restriction isn't what it should be, set it. */
6077 if (old_begv != BEGV || old_zv != ZV)
6078 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
6080 bset_read_only (current_buffer, old_read_only);
6081 SET_PT_BOTH (opoint, opoint_byte);
6083 return Qnil;
6086 /* Sending data to subprocess. */
6088 /* In send_process, when a write fails temporarily,
6089 wait_reading_process_output is called. It may execute user code,
6090 e.g. timers, that attempts to write new data to the same process.
6091 We must ensure that data is sent in the right order, and not
6092 interspersed half-completed with other writes (Bug#10815). This is
6093 handled by the write_queue element of struct process. It is a list
6094 with each entry having the form
6096 (string . (offset . length))
6098 where STRING is a lisp string, OFFSET is the offset into the
6099 string's byte sequence from which we should begin to send, and
6100 LENGTH is the number of bytes left to send. */
6102 /* Create a new entry in write_queue.
6103 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6104 BUF is a pointer to the string sequence of the input_obj or a C
6105 string in case of Qt or Qnil. */
6107 static void
6108 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6109 const char *buf, ptrdiff_t len, bool front)
6111 ptrdiff_t offset;
6112 Lisp_Object entry, obj;
6114 if (STRINGP (input_obj))
6116 offset = buf - SSDATA (input_obj);
6117 obj = input_obj;
6119 else
6121 offset = 0;
6122 obj = make_unibyte_string (buf, len);
6125 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
6127 if (front)
6128 pset_write_queue (p, Fcons (entry, p->write_queue));
6129 else
6130 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6133 /* Remove the first element in the write_queue of process P, put its
6134 contents in OBJ, BUF and LEN, and return true. If the
6135 write_queue is empty, return false. */
6137 static bool
6138 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6139 const char **buf, ptrdiff_t *len)
6141 Lisp_Object entry, offset_length;
6142 ptrdiff_t offset;
6144 if (NILP (p->write_queue))
6145 return 0;
6147 entry = XCAR (p->write_queue);
6148 pset_write_queue (p, XCDR (p->write_queue));
6150 *obj = XCAR (entry);
6151 offset_length = XCDR (entry);
6153 *len = XINT (XCDR (offset_length));
6154 offset = XINT (XCAR (offset_length));
6155 *buf = SSDATA (*obj) + offset;
6157 return 1;
6160 /* Send some data to process PROC.
6161 BUF is the beginning of the data; LEN is the number of characters.
6162 OBJECT is the Lisp object that the data comes from. If OBJECT is
6163 nil or t, it means that the data comes from C string.
6165 If OBJECT is not nil, the data is encoded by PROC's coding-system
6166 for encoding before it is sent.
6168 This function can evaluate Lisp code and can garbage collect. */
6170 static void
6171 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6172 Lisp_Object object)
6174 struct Lisp_Process *p = XPROCESS (proc);
6175 ssize_t rv;
6176 struct coding_system *coding;
6178 if (NETCONN_P (proc))
6180 wait_while_connecting (proc);
6181 wait_for_tls_negotiation (proc);
6184 if (p->raw_status_new)
6185 update_status (p);
6186 if (! EQ (p->status, Qrun))
6187 error ("Process %s not running", SDATA (p->name));
6188 if (p->outfd < 0)
6189 error ("Output file descriptor of %s is closed", SDATA (p->name));
6191 coding = proc_encode_coding_system[p->outfd];
6192 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6194 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6195 || (BUFFERP (object)
6196 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6197 || EQ (object, Qt))
6199 pset_encode_coding_system
6200 (p, complement_process_encoding_system (p->encode_coding_system));
6201 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6203 /* The coding system for encoding was changed to raw-text
6204 because we sent a unibyte text previously. Now we are
6205 sending a multibyte text, thus we must encode it by the
6206 original coding system specified for the current process.
6208 Another reason we come here is that the coding system
6209 was just complemented and a new one was returned by
6210 complement_process_encoding_system. */
6211 setup_coding_system (p->encode_coding_system, coding);
6212 Vlast_coding_system_used = p->encode_coding_system;
6214 coding->src_multibyte = 1;
6216 else
6218 coding->src_multibyte = 0;
6219 /* For sending a unibyte text, character code conversion should
6220 not take place but EOL conversion should. So, setup raw-text
6221 or one of the subsidiary if we have not yet done it. */
6222 if (CODING_REQUIRE_ENCODING (coding))
6224 if (CODING_REQUIRE_FLUSHING (coding))
6226 /* But, before changing the coding, we must flush out data. */
6227 coding->mode |= CODING_MODE_LAST_BLOCK;
6228 send_process (proc, "", 0, Qt);
6229 coding->mode &= CODING_MODE_LAST_BLOCK;
6231 setup_coding_system (raw_text_coding_system
6232 (Vlast_coding_system_used),
6233 coding);
6234 coding->src_multibyte = 0;
6237 coding->dst_multibyte = 0;
6239 if (CODING_REQUIRE_ENCODING (coding))
6241 coding->dst_object = Qt;
6242 if (BUFFERP (object))
6244 ptrdiff_t from_byte, from, to;
6245 ptrdiff_t save_pt, save_pt_byte;
6246 struct buffer *cur = current_buffer;
6248 set_buffer_internal (XBUFFER (object));
6249 save_pt = PT, save_pt_byte = PT_BYTE;
6251 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6252 from = BYTE_TO_CHAR (from_byte);
6253 to = BYTE_TO_CHAR (from_byte + len);
6254 TEMP_SET_PT_BOTH (from, from_byte);
6255 encode_coding_object (coding, object, from, from_byte,
6256 to, from_byte + len, Qt);
6257 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6258 set_buffer_internal (cur);
6260 else if (STRINGP (object))
6262 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6263 SBYTES (object), Qt);
6265 else
6267 coding->dst_object = make_unibyte_string (buf, len);
6268 coding->produced = len;
6271 len = coding->produced;
6272 object = coding->dst_object;
6273 buf = SSDATA (object);
6276 /* If there is already data in the write_queue, put the new data
6277 in the back of queue. Otherwise, ignore it. */
6278 if (!NILP (p->write_queue))
6279 write_queue_push (p, object, buf, len, 0);
6281 do /* while !NILP (p->write_queue) */
6283 ptrdiff_t cur_len = -1;
6284 const char *cur_buf;
6285 Lisp_Object cur_object;
6287 /* If write_queue is empty, ignore it. */
6288 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6290 cur_len = len;
6291 cur_buf = buf;
6292 cur_object = object;
6295 while (cur_len > 0)
6297 /* Send this batch, using one or more write calls. */
6298 ptrdiff_t written = 0;
6299 int outfd = p->outfd;
6300 #ifdef DATAGRAM_SOCKETS
6301 if (DATAGRAM_CHAN_P (outfd))
6303 rv = sendto (outfd, cur_buf, cur_len,
6304 0, datagram_address[outfd].sa,
6305 datagram_address[outfd].len);
6306 if (rv >= 0)
6307 written = rv;
6308 else if (errno == EMSGSIZE)
6309 report_file_error ("Sending datagram", proc);
6311 else
6312 #endif
6314 #ifdef HAVE_GNUTLS
6315 if (p->gnutls_p && p->gnutls_state)
6316 written = emacs_gnutls_write (p, cur_buf, cur_len);
6317 else
6318 #endif
6319 written = emacs_write_sig (outfd, cur_buf, cur_len);
6320 rv = (written ? 0 : -1);
6321 if (p->read_output_delay > 0
6322 && p->adaptive_read_buffering == 1)
6324 p->read_output_delay = 0;
6325 process_output_delay_count--;
6326 p->read_output_skip = 0;
6330 if (rv < 0)
6332 if (would_block (errno))
6333 /* Buffer is full. Wait, accepting input;
6334 that may allow the program
6335 to finish doing output and read more. */
6337 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6338 /* A gross hack to work around a bug in FreeBSD.
6339 In the following sequence, read(2) returns
6340 bogus data:
6342 write(2) 1022 bytes
6343 write(2) 954 bytes, get EAGAIN
6344 read(2) 1024 bytes in process_read_output
6345 read(2) 11 bytes in process_read_output
6347 That is, read(2) returns more bytes than have
6348 ever been written successfully. The 1033 bytes
6349 read are the 1022 bytes written successfully
6350 after processing (for example with CRs added if
6351 the terminal is set up that way which it is
6352 here). The same bytes will be seen again in a
6353 later read(2), without the CRs. */
6355 if (errno == EAGAIN)
6357 int flags = FWRITE;
6358 ioctl (p->outfd, TIOCFLUSH, &flags);
6360 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6362 /* Put what we should have written in wait_queue. */
6363 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6364 wait_reading_process_output (0, 20 * 1000 * 1000,
6365 0, 0, Qnil, NULL, 0);
6366 /* Reread queue, to see what is left. */
6367 break;
6369 else if (errno == EPIPE)
6371 p->raw_status_new = 0;
6372 pset_status (p, list2 (Qexit, make_number (256)));
6373 p->tick = ++process_tick;
6374 deactivate_process (proc);
6375 error ("process %s no longer connected to pipe; closed it",
6376 SDATA (p->name));
6378 else
6379 /* This is a real error. */
6380 report_file_error ("Writing to process", proc);
6382 cur_buf += written;
6383 cur_len -= written;
6386 while (!NILP (p->write_queue));
6389 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6390 3, 3, 0,
6391 doc: /* Send current contents of region as input to PROCESS.
6392 PROCESS may be a process, a buffer, the name of a process or buffer, or
6393 nil, indicating the current buffer's process.
6394 Called from program, takes three arguments, PROCESS, START and END.
6395 If the region is more than 500 characters long,
6396 it is sent in several bunches. This may happen even for shorter regions.
6397 Output from processes can arrive in between bunches.
6399 If PROCESS is a non-blocking network process that hasn't been fully
6400 set up yet, this function will block until socket setup has completed. */)
6401 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6403 Lisp_Object proc = get_process (process);
6404 ptrdiff_t start_byte, end_byte;
6406 validate_region (&start, &end);
6408 start_byte = CHAR_TO_BYTE (XINT (start));
6409 end_byte = CHAR_TO_BYTE (XINT (end));
6411 if (XINT (start) < GPT && XINT (end) > GPT)
6412 move_gap_both (XINT (start), start_byte);
6414 if (NETCONN_P (proc))
6415 wait_while_connecting (proc);
6417 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6418 end_byte - start_byte, Fcurrent_buffer ());
6420 return Qnil;
6423 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6424 2, 2, 0,
6425 doc: /* Send PROCESS the contents of STRING as input.
6426 PROCESS may be a process, a buffer, the name of a process or buffer, or
6427 nil, indicating the current buffer's process.
6428 If STRING is more than 500 characters long,
6429 it is sent in several bunches. This may happen even for shorter strings.
6430 Output from processes can arrive in between bunches.
6432 If PROCESS is a non-blocking network process that hasn't been fully
6433 set up yet, this function will block until socket setup has completed. */)
6434 (Lisp_Object process, Lisp_Object string)
6436 CHECK_STRING (string);
6437 Lisp_Object proc = get_process (process);
6438 send_process (proc, SSDATA (string),
6439 SBYTES (string), string);
6440 return Qnil;
6443 /* Return the foreground process group for the tty/pty that
6444 the process P uses. */
6445 static pid_t
6446 emacs_get_tty_pgrp (struct Lisp_Process *p)
6448 pid_t gid = -1;
6450 #ifdef TIOCGPGRP
6451 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6453 int fd;
6454 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6455 master side. Try the slave side. */
6456 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6458 if (fd != -1)
6460 ioctl (fd, TIOCGPGRP, &gid);
6461 emacs_close (fd);
6464 #endif /* defined (TIOCGPGRP ) */
6466 return gid;
6469 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6470 Sprocess_running_child_p, 0, 1, 0,
6471 doc: /* Return non-nil if PROCESS has given the terminal to a
6472 child. If the operating system does not make it possible to find out,
6473 return t. If we can find out, return the numeric ID of the foreground
6474 process group. */)
6475 (Lisp_Object process)
6477 /* Initialize in case ioctl doesn't exist or gives an error,
6478 in a way that will cause returning t. */
6479 Lisp_Object proc = get_process (process);
6480 struct Lisp_Process *p = XPROCESS (proc);
6482 if (!EQ (p->type, Qreal))
6483 error ("Process %s is not a subprocess",
6484 SDATA (p->name));
6485 if (p->infd < 0)
6486 error ("Process %s is not active",
6487 SDATA (p->name));
6489 pid_t gid = emacs_get_tty_pgrp (p);
6491 if (gid == p->pid)
6492 return Qnil;
6493 if (gid != -1)
6494 return make_number (gid);
6495 return Qt;
6498 /* Send a signal number SIGNO to PROCESS.
6499 If CURRENT_GROUP is t, that means send to the process group
6500 that currently owns the terminal being used to communicate with PROCESS.
6501 This is used for various commands in shell mode.
6502 If CURRENT_GROUP is lambda, that means send to the process group
6503 that currently owns the terminal, but only if it is NOT the shell itself.
6505 If NOMSG is false, insert signal-announcements into process's buffers
6506 right away.
6508 If we can, we try to signal PROCESS by sending control characters
6509 down the pty. This allows us to signal inferiors who have changed
6510 their uid, for which kill would return an EPERM error. */
6512 static void
6513 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6514 bool nomsg)
6516 Lisp_Object proc;
6517 struct Lisp_Process *p;
6518 pid_t gid;
6519 bool no_pgrp = 0;
6521 proc = get_process (process);
6522 p = XPROCESS (proc);
6524 if (!EQ (p->type, Qreal))
6525 error ("Process %s is not a subprocess",
6526 SDATA (p->name));
6527 if (p->infd < 0)
6528 error ("Process %s is not active",
6529 SDATA (p->name));
6531 if (!p->pty_flag)
6532 current_group = Qnil;
6534 /* If we are using pgrps, get a pgrp number and make it negative. */
6535 if (NILP (current_group))
6536 /* Send the signal to the shell's process group. */
6537 gid = p->pid;
6538 else
6540 #ifdef SIGNALS_VIA_CHARACTERS
6541 /* If possible, send signals to the entire pgrp
6542 by sending an input character to it. */
6544 struct termios t;
6545 cc_t *sig_char = NULL;
6547 tcgetattr (p->infd, &t);
6549 switch (signo)
6551 case SIGINT:
6552 sig_char = &t.c_cc[VINTR];
6553 break;
6555 case SIGQUIT:
6556 sig_char = &t.c_cc[VQUIT];
6557 break;
6559 case SIGTSTP:
6560 #ifdef VSWTCH
6561 sig_char = &t.c_cc[VSWTCH];
6562 #else
6563 sig_char = &t.c_cc[VSUSP];
6564 #endif
6565 break;
6568 if (sig_char && *sig_char != CDISABLE)
6570 send_process (proc, (char *) sig_char, 1, Qnil);
6571 return;
6573 /* If we can't send the signal with a character,
6574 fall through and send it another way. */
6576 /* The code above may fall through if it can't
6577 handle the signal. */
6578 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6580 #ifdef TIOCGPGRP
6581 /* Get the current pgrp using the tty itself, if we have that.
6582 Otherwise, use the pty to get the pgrp.
6583 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6584 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6585 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6586 His patch indicates that if TIOCGPGRP returns an error, then
6587 we should just assume that p->pid is also the process group id. */
6589 gid = emacs_get_tty_pgrp (p);
6591 if (gid == -1)
6592 /* If we can't get the information, assume
6593 the shell owns the tty. */
6594 gid = p->pid;
6596 /* It is not clear whether anything really can set GID to -1.
6597 Perhaps on some system one of those ioctls can or could do so.
6598 Or perhaps this is vestigial. */
6599 if (gid == -1)
6600 no_pgrp = 1;
6601 #else /* ! defined (TIOCGPGRP) */
6602 /* Can't select pgrps on this system, so we know that
6603 the child itself heads the pgrp. */
6604 gid = p->pid;
6605 #endif /* ! defined (TIOCGPGRP) */
6607 /* If current_group is lambda, and the shell owns the terminal,
6608 don't send any signal. */
6609 if (EQ (current_group, Qlambda) && gid == p->pid)
6610 return;
6613 #ifdef SIGCONT
6614 if (signo == SIGCONT)
6616 p->raw_status_new = 0;
6617 pset_status (p, Qrun);
6618 p->tick = ++process_tick;
6619 if (!nomsg)
6621 status_notify (NULL, NULL);
6622 redisplay_preserve_echo_area (13);
6625 #endif
6627 #ifdef TIOCSIGSEND
6628 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6629 We don't know whether the bug is fixed in later HP-UX versions. */
6630 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6631 return;
6632 #endif
6634 /* If we don't have process groups, send the signal to the immediate
6635 subprocess. That isn't really right, but it's better than any
6636 obvious alternative. */
6637 pid_t pid = no_pgrp ? gid : - gid;
6639 /* Do not kill an already-reaped process, as that could kill an
6640 innocent bystander that happens to have the same process ID. */
6641 sigset_t oldset;
6642 block_child_signal (&oldset);
6643 if (p->alive)
6644 kill (pid, signo);
6645 unblock_child_signal (&oldset);
6648 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6649 doc: /* Interrupt process PROCESS.
6650 PROCESS may be a process, a buffer, or the name of a process or buffer.
6651 No arg or nil means current buffer's process.
6652 Second arg CURRENT-GROUP non-nil means send signal to
6653 the current process-group of the process's controlling terminal
6654 rather than to the process's own process group.
6655 If the process is a shell, this means interrupt current subjob
6656 rather than the shell.
6658 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6659 don't send the signal. */)
6660 (Lisp_Object process, Lisp_Object current_group)
6662 process_send_signal (process, SIGINT, current_group, 0);
6663 return process;
6666 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6667 doc: /* Kill process PROCESS. May be process or name of one.
6668 See function `interrupt-process' for more details on usage. */)
6669 (Lisp_Object process, Lisp_Object current_group)
6671 process_send_signal (process, SIGKILL, current_group, 0);
6672 return process;
6675 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6676 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6677 See function `interrupt-process' for more details on usage. */)
6678 (Lisp_Object process, Lisp_Object current_group)
6680 process_send_signal (process, SIGQUIT, current_group, 0);
6681 return process;
6684 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6685 doc: /* Stop process PROCESS. May be process or name of one.
6686 See function `interrupt-process' for more details on usage.
6687 If PROCESS is a network or serial or pipe connection, inhibit handling
6688 of incoming traffic. */)
6689 (Lisp_Object process, Lisp_Object current_group)
6691 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6692 || PIPECONN_P (process)))
6694 struct Lisp_Process *p;
6696 p = XPROCESS (process);
6697 if (NILP (p->command)
6698 && p->infd >= 0)
6699 delete_read_fd (p->infd);
6700 pset_command (p, Qt);
6701 return process;
6703 #ifndef SIGTSTP
6704 error ("No SIGTSTP support");
6705 #else
6706 process_send_signal (process, SIGTSTP, current_group, 0);
6707 #endif
6708 return process;
6711 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6712 doc: /* Continue process PROCESS. May be process or name of one.
6713 See function `interrupt-process' for more details on usage.
6714 If PROCESS is a network or serial process, resume handling of incoming
6715 traffic. */)
6716 (Lisp_Object process, Lisp_Object current_group)
6718 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6719 || PIPECONN_P (process)))
6721 struct Lisp_Process *p;
6723 p = XPROCESS (process);
6724 if (EQ (p->command, Qt)
6725 && p->infd >= 0
6726 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6728 add_process_read_fd (p->infd);
6729 #ifdef WINDOWSNT
6730 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6731 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6732 #else /* not WINDOWSNT */
6733 tcflush (p->infd, TCIFLUSH);
6734 #endif /* not WINDOWSNT */
6736 pset_command (p, Qnil);
6737 return process;
6739 #ifdef SIGCONT
6740 process_send_signal (process, SIGCONT, current_group, 0);
6741 #else
6742 error ("No SIGCONT support");
6743 #endif
6744 return process;
6747 /* Return the integer value of the signal whose abbreviation is ABBR,
6748 or a negative number if there is no such signal. */
6749 static int
6750 abbr_to_signal (char const *name)
6752 int i, signo;
6753 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6755 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6756 name += 3;
6758 for (i = 0; i < sizeof sigbuf; i++)
6760 sigbuf[i] = c_toupper (name[i]);
6761 if (! sigbuf[i])
6762 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6765 return -1;
6768 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6769 2, 2, "sProcess (name or number): \nnSignal code: ",
6770 doc: /* Send PROCESS the signal with code SIGCODE.
6771 PROCESS may also be a number specifying the process id of the
6772 process to signal; in this case, the process need not be a child of
6773 this Emacs.
6774 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6775 (Lisp_Object process, Lisp_Object sigcode)
6777 pid_t pid;
6778 int signo;
6780 if (STRINGP (process))
6782 Lisp_Object tem = Fget_process (process);
6783 if (NILP (tem))
6785 Lisp_Object process_number
6786 = string_to_number (SSDATA (process), 10, 1);
6787 if (NUMBERP (process_number))
6788 tem = process_number;
6790 process = tem;
6792 else if (!NUMBERP (process))
6793 process = get_process (process);
6795 if (NILP (process))
6796 return process;
6798 if (NUMBERP (process))
6799 CONS_TO_INTEGER (process, pid_t, pid);
6800 else
6802 CHECK_PROCESS (process);
6803 pid = XPROCESS (process)->pid;
6804 if (pid <= 0)
6805 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6808 if (INTEGERP (sigcode))
6810 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6811 signo = XINT (sigcode);
6813 else
6815 char *name;
6817 CHECK_SYMBOL (sigcode);
6818 name = SSDATA (SYMBOL_NAME (sigcode));
6820 signo = abbr_to_signal (name);
6821 if (signo < 0)
6822 error ("Undefined signal name %s", name);
6825 return make_number (kill (pid, signo));
6828 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6829 doc: /* Make PROCESS see end-of-file in its input.
6830 EOF comes after any text already sent to it.
6831 PROCESS may be a process, a buffer, the name of a process or buffer, or
6832 nil, indicating the current buffer's process.
6833 If PROCESS is a network connection, or is a process communicating
6834 through a pipe (as opposed to a pty), then you cannot send any more
6835 text to PROCESS after you call this function.
6836 If PROCESS is a serial process, wait until all output written to the
6837 process has been transmitted to the serial port. */)
6838 (Lisp_Object process)
6840 Lisp_Object proc;
6841 struct coding_system *coding = NULL;
6842 int outfd;
6844 proc = get_process (process);
6846 if (NETCONN_P (proc))
6847 wait_while_connecting (proc);
6849 if (DATAGRAM_CONN_P (proc))
6850 return process;
6853 outfd = XPROCESS (proc)->outfd;
6854 if (outfd >= 0)
6855 coding = proc_encode_coding_system[outfd];
6857 /* Make sure the process is really alive. */
6858 if (XPROCESS (proc)->raw_status_new)
6859 update_status (XPROCESS (proc));
6860 if (! EQ (XPROCESS (proc)->status, Qrun))
6861 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6863 if (coding && CODING_REQUIRE_FLUSHING (coding))
6865 coding->mode |= CODING_MODE_LAST_BLOCK;
6866 send_process (proc, "", 0, Qnil);
6869 if (XPROCESS (proc)->pty_flag)
6870 send_process (proc, "\004", 1, Qnil);
6871 else if (EQ (XPROCESS (proc)->type, Qserial))
6873 #ifndef WINDOWSNT
6874 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6875 report_file_error ("Failed tcdrain", Qnil);
6876 #endif /* not WINDOWSNT */
6877 /* Do nothing on Windows because writes are blocking. */
6879 else
6881 struct Lisp_Process *p = XPROCESS (proc);
6882 int old_outfd = p->outfd;
6883 int new_outfd;
6885 #ifdef HAVE_SHUTDOWN
6886 /* If this is a network connection, or socketpair is used
6887 for communication with the subprocess, call shutdown to cause EOF.
6888 (In some old system, shutdown to socketpair doesn't work.
6889 Then we just can't win.) */
6890 if (0 <= old_outfd
6891 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6892 shutdown (old_outfd, 1);
6893 #endif
6894 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6895 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6896 if (new_outfd < 0)
6897 report_file_error ("Opening null device", Qnil);
6898 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6899 p->outfd = new_outfd;
6901 if (!proc_encode_coding_system[new_outfd])
6902 proc_encode_coding_system[new_outfd]
6903 = xmalloc (sizeof (struct coding_system));
6904 if (old_outfd >= 0)
6906 *proc_encode_coding_system[new_outfd]
6907 = *proc_encode_coding_system[old_outfd];
6908 memset (proc_encode_coding_system[old_outfd], 0,
6909 sizeof (struct coding_system));
6911 else
6912 setup_coding_system (p->encode_coding_system,
6913 proc_encode_coding_system[new_outfd]);
6915 return process;
6918 /* The main Emacs thread records child processes in three places:
6920 - Vprocess_alist, for asynchronous subprocesses, which are child
6921 processes visible to Lisp.
6923 - deleted_pid_list, for child processes invisible to Lisp,
6924 typically because of delete-process. These are recorded so that
6925 the processes can be reaped when they exit, so that the operating
6926 system's process table is not cluttered by zombies.
6928 - the local variable PID in Fcall_process, call_process_cleanup and
6929 call_process_kill, for synchronous subprocesses.
6930 record_unwind_protect is used to make sure this process is not
6931 forgotten: if the user interrupts call-process and the child
6932 process refuses to exit immediately even with two C-g's,
6933 call_process_kill adds PID's contents to deleted_pid_list before
6934 returning.
6936 The main Emacs thread invokes waitpid only on child processes that
6937 it creates and that have not been reaped. This avoid races on
6938 platforms such as GTK, where other threads create their own
6939 subprocesses which the main thread should not reap. For example,
6940 if the main thread attempted to reap an already-reaped child, it
6941 might inadvertently reap a GTK-created process that happened to
6942 have the same process ID. */
6944 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6945 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6946 keep track of its own children. GNUstep is similar. */
6948 static void dummy_handler (int sig) {}
6949 static signal_handler_t volatile lib_child_handler;
6951 /* Handle a SIGCHLD signal by looking for known child processes of
6952 Emacs whose status have changed. For each one found, record its
6953 new status.
6955 All we do is change the status; we do not run sentinels or print
6956 notifications. That is saved for the next time keyboard input is
6957 done, in order to avoid timing errors.
6959 ** WARNING: this can be called during garbage collection.
6960 Therefore, it must not be fooled by the presence of mark bits in
6961 Lisp objects.
6963 ** USG WARNING: Although it is not obvious from the documentation
6964 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6965 signal() before executing at least one wait(), otherwise the
6966 handler will be called again, resulting in an infinite loop. The
6967 relevant portion of the documentation reads "SIGCLD signals will be
6968 queued and the signal-catching function will be continually
6969 reentered until the queue is empty". Invoking signal() causes the
6970 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6971 Inc.
6973 ** Malloc WARNING: This should never call malloc either directly or
6974 indirectly; if it does, that is a bug. */
6976 static void
6977 handle_child_signal (int sig)
6979 Lisp_Object tail, proc;
6981 /* Find the process that signaled us, and record its status. */
6983 /* The process can have been deleted by Fdelete_process, or have
6984 been started asynchronously by Fcall_process. */
6985 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6987 bool all_pids_are_fixnums
6988 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6989 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6990 Lisp_Object head = XCAR (tail);
6991 Lisp_Object xpid;
6992 if (! CONSP (head))
6993 continue;
6994 xpid = XCAR (head);
6995 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6997 pid_t deleted_pid;
6998 if (INTEGERP (xpid))
6999 deleted_pid = XINT (xpid);
7000 else
7001 deleted_pid = XFLOAT_DATA (xpid);
7002 if (child_status_changed (deleted_pid, 0, 0))
7004 if (STRINGP (XCDR (head)))
7005 unlink (SSDATA (XCDR (head)));
7006 XSETCAR (tail, Qnil);
7011 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7012 FOR_EACH_PROCESS (tail, proc)
7014 struct Lisp_Process *p = XPROCESS (proc);
7015 int status;
7017 if (p->alive
7018 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7020 /* Change the status of the process that was found. */
7021 p->tick = ++process_tick;
7022 p->raw_status = status;
7023 p->raw_status_new = 1;
7025 /* If process has terminated, stop waiting for its output. */
7026 if (WIFSIGNALED (status) || WIFEXITED (status))
7028 bool clear_desc_flag = 0;
7029 p->alive = 0;
7030 if (p->infd >= 0)
7031 clear_desc_flag = 1;
7033 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7034 if (clear_desc_flag)
7035 delete_read_fd (p->infd);
7040 lib_child_handler (sig);
7041 #ifdef NS_IMPL_GNUSTEP
7042 /* NSTask in GNUstep sets its child handler each time it is called.
7043 So we must re-set ours. */
7044 catch_child_signal ();
7045 #endif
7048 static void
7049 deliver_child_signal (int sig)
7051 deliver_process_signal (sig, handle_child_signal);
7055 static Lisp_Object
7056 exec_sentinel_error_handler (Lisp_Object error_val)
7058 cmd_error_internal (error_val, "error in process sentinel: ");
7059 Vinhibit_quit = Qt;
7060 update_echo_area ();
7061 Fsleep_for (make_number (2), Qnil);
7062 return Qt;
7065 static void
7066 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7068 Lisp_Object sentinel, odeactivate;
7069 struct Lisp_Process *p = XPROCESS (proc);
7070 ptrdiff_t count = SPECPDL_INDEX ();
7071 bool outer_running_asynch_code = running_asynch_code;
7072 int waiting = waiting_for_user_input_p;
7074 if (inhibit_sentinels)
7075 return;
7077 odeactivate = Vdeactivate_mark;
7078 #if 0
7079 Lisp_Object obuffer, okeymap;
7080 XSETBUFFER (obuffer, current_buffer);
7081 okeymap = BVAR (current_buffer, keymap);
7082 #endif
7084 /* There's no good reason to let sentinels change the current
7085 buffer, and many callers of accept-process-output, sit-for, and
7086 friends don't expect current-buffer to be changed from under them. */
7087 record_unwind_current_buffer ();
7089 sentinel = p->sentinel;
7091 /* Inhibit quit so that random quits don't screw up a running filter. */
7092 specbind (Qinhibit_quit, Qt);
7093 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7095 /* In case we get recursively called,
7096 and we already saved the match data nonrecursively,
7097 save the same match data in safely recursive fashion. */
7098 if (outer_running_asynch_code)
7100 Lisp_Object tem;
7101 tem = Fmatch_data (Qnil, Qnil, Qnil);
7102 restore_search_regs ();
7103 record_unwind_save_match_data ();
7104 Fset_match_data (tem, Qt);
7107 /* For speed, if a search happens within this code,
7108 save the match data in a special nonrecursive fashion. */
7109 running_asynch_code = 1;
7111 internal_condition_case_1 (read_process_output_call,
7112 list3 (sentinel, proc, reason),
7113 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7114 exec_sentinel_error_handler);
7116 /* If we saved the match data nonrecursively, restore it now. */
7117 restore_search_regs ();
7118 running_asynch_code = outer_running_asynch_code;
7120 Vdeactivate_mark = odeactivate;
7122 /* Restore waiting_for_user_input_p as it was
7123 when we were called, in case the filter clobbered it. */
7124 waiting_for_user_input_p = waiting;
7126 #if 0
7127 if (! EQ (Fcurrent_buffer (), obuffer)
7128 || ! EQ (current_buffer->keymap, okeymap))
7129 #endif
7130 /* But do it only if the caller is actually going to read events.
7131 Otherwise there's no need to make him wake up, and it could
7132 cause trouble (for example it would make sit_for return). */
7133 if (waiting_for_user_input_p == -1)
7134 record_asynch_buffer_change ();
7136 unbind_to (count, Qnil);
7139 /* Report all recent events of a change in process status
7140 (either run the sentinel or output a message).
7141 This is usually done while Emacs is waiting for keyboard input
7142 but can be done at other times.
7144 Return positive if any input was received from WAIT_PROC (or from
7145 any process if WAIT_PROC is null), zero if input was attempted but
7146 none received, and negative if we didn't even try. */
7148 static int
7149 status_notify (struct Lisp_Process *deleting_process,
7150 struct Lisp_Process *wait_proc)
7152 Lisp_Object proc;
7153 Lisp_Object tail, msg;
7154 int got_some_output = -1;
7156 tail = Qnil;
7157 msg = Qnil;
7159 /* Set this now, so that if new processes are created by sentinels
7160 that we run, we get called again to handle their status changes. */
7161 update_tick = process_tick;
7163 FOR_EACH_PROCESS (tail, proc)
7165 Lisp_Object symbol;
7166 register struct Lisp_Process *p = XPROCESS (proc);
7168 if (p->tick != p->update_tick)
7170 p->update_tick = p->tick;
7172 /* If process is still active, read any output that remains. */
7173 while (! EQ (p->filter, Qt)
7174 && ! connecting_status (p->status)
7175 && ! EQ (p->status, Qlisten)
7176 /* Network or serial process not stopped: */
7177 && ! EQ (p->command, Qt)
7178 && p->infd >= 0
7179 && p != deleting_process)
7181 int nread = read_process_output (proc, p->infd);
7182 if ((!wait_proc || wait_proc == XPROCESS (proc))
7183 && got_some_output < nread)
7184 got_some_output = nread;
7185 if (nread <= 0)
7186 break;
7189 /* Get the text to use for the message. */
7190 if (p->raw_status_new)
7191 update_status (p);
7192 msg = status_message (p);
7194 /* If process is terminated, deactivate it or delete it. */
7195 symbol = p->status;
7196 if (CONSP (p->status))
7197 symbol = XCAR (p->status);
7199 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7200 || EQ (symbol, Qclosed))
7202 if (delete_exited_processes)
7203 remove_process (proc);
7204 else
7205 deactivate_process (proc);
7208 /* The actions above may have further incremented p->tick.
7209 So set p->update_tick again so that an error in the sentinel will
7210 not cause this code to be run again. */
7211 p->update_tick = p->tick;
7212 /* Now output the message suitably. */
7213 exec_sentinel (proc, msg);
7214 if (BUFFERP (p->buffer))
7215 /* In case it uses %s in mode-line-format. */
7216 bset_update_mode_line (XBUFFER (p->buffer));
7218 } /* end for */
7220 return got_some_output;
7223 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7224 Sinternal_default_process_sentinel, 2, 2, 0,
7225 doc: /* Function used as default sentinel for processes.
7226 This inserts a status message into the process's buffer, if there is one. */)
7227 (Lisp_Object proc, Lisp_Object msg)
7229 Lisp_Object buffer, symbol;
7230 struct Lisp_Process *p;
7231 CHECK_PROCESS (proc);
7232 p = XPROCESS (proc);
7233 buffer = p->buffer;
7234 symbol = p->status;
7235 if (CONSP (symbol))
7236 symbol = XCAR (symbol);
7238 if (!EQ (symbol, Qrun) && !NILP (buffer))
7240 Lisp_Object tem;
7241 struct buffer *old = current_buffer;
7242 ptrdiff_t opoint, opoint_byte;
7243 ptrdiff_t before, before_byte;
7245 /* Avoid error if buffer is deleted
7246 (probably that's why the process is dead, too). */
7247 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7248 return Qnil;
7249 Fset_buffer (buffer);
7251 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7252 msg = (code_convert_string_norecord
7253 (msg, Vlocale_coding_system, 1));
7255 opoint = PT;
7256 opoint_byte = PT_BYTE;
7257 /* Insert new output into buffer
7258 at the current end-of-output marker,
7259 thus preserving logical ordering of input and output. */
7260 if (XMARKER (p->mark)->buffer)
7261 Fgoto_char (p->mark);
7262 else
7263 SET_PT_BOTH (ZV, ZV_BYTE);
7265 before = PT;
7266 before_byte = PT_BYTE;
7268 tem = BVAR (current_buffer, read_only);
7269 bset_read_only (current_buffer, Qnil);
7270 insert_string ("\nProcess ");
7271 { /* FIXME: temporary kludge. */
7272 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7273 insert_string (" ");
7274 Finsert (1, &msg);
7275 bset_read_only (current_buffer, tem);
7276 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7278 if (opoint >= before)
7279 SET_PT_BOTH (opoint + (PT - before),
7280 opoint_byte + (PT_BYTE - before_byte));
7281 else
7282 SET_PT_BOTH (opoint, opoint_byte);
7284 set_buffer_internal (old);
7286 return Qnil;
7290 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7291 Sset_process_coding_system, 1, 3, 0,
7292 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7293 DECODING will be used to decode subprocess output and ENCODING to
7294 encode subprocess input. */)
7295 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7297 CHECK_PROCESS (process);
7299 struct Lisp_Process *p = XPROCESS (process);
7301 Fcheck_coding_system (decoding);
7302 Fcheck_coding_system (encoding);
7303 encoding = coding_inherit_eol_type (encoding, Qnil);
7304 pset_decode_coding_system (p, decoding);
7305 pset_encode_coding_system (p, encoding);
7307 /* If the sockets haven't been set up yet, the final setup part of
7308 this will be called asynchronously. */
7309 if (p->infd < 0 || p->outfd < 0)
7310 return Qnil;
7312 setup_process_coding_systems (process);
7314 return Qnil;
7317 DEFUN ("process-coding-system",
7318 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7319 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7320 (register Lisp_Object process)
7322 CHECK_PROCESS (process);
7323 return Fcons (XPROCESS (process)->decode_coding_system,
7324 XPROCESS (process)->encode_coding_system);
7327 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7328 Sset_process_filter_multibyte, 2, 2, 0,
7329 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7330 If FLAG is non-nil, the filter is given multibyte strings.
7331 If FLAG is nil, the filter is given unibyte strings. In this case,
7332 all character code conversion except for end-of-line conversion is
7333 suppressed. */)
7334 (Lisp_Object process, Lisp_Object flag)
7336 CHECK_PROCESS (process);
7338 struct Lisp_Process *p = XPROCESS (process);
7339 if (NILP (flag))
7340 pset_decode_coding_system
7341 (p, raw_text_coding_system (p->decode_coding_system));
7343 /* If the sockets haven't been set up yet, the final setup part of
7344 this will be called asynchronously. */
7345 if (p->infd < 0 || p->outfd < 0)
7346 return Qnil;
7348 setup_process_coding_systems (process);
7350 return Qnil;
7353 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7354 Sprocess_filter_multibyte_p, 1, 1, 0,
7355 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7356 (Lisp_Object process)
7358 CHECK_PROCESS (process);
7359 struct Lisp_Process *p = XPROCESS (process);
7360 if (p->infd < 0)
7361 return Qnil;
7362 struct coding_system *coding = proc_decode_coding_system[p->infd];
7363 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7369 # ifdef HAVE_GPM
7371 void
7372 add_gpm_wait_descriptor (int desc)
7374 add_keyboard_wait_descriptor (desc);
7377 void
7378 delete_gpm_wait_descriptor (int desc)
7380 delete_keyboard_wait_descriptor (desc);
7383 # endif
7385 # ifdef USABLE_SIGIO
7387 /* Return true if *MASK has a bit set
7388 that corresponds to one of the keyboard input descriptors. */
7390 static bool
7391 keyboard_bit_set (fd_set *mask)
7393 int fd;
7395 for (fd = 0; fd <= max_desc; fd++)
7396 if (FD_ISSET (fd, mask)
7397 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7398 == (FOR_READ | KEYBOARD_FD)))
7399 return 1;
7401 return 0;
7403 # endif
7405 #else /* not subprocesses */
7407 /* Defined in msdos.c. */
7408 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7409 struct timespec *, void *);
7411 /* Implementation of wait_reading_process_output, assuming that there
7412 are no subprocesses. Used only by the MS-DOS build.
7414 Wait for timeout to elapse and/or keyboard input to be available.
7416 TIME_LIMIT is:
7417 timeout in seconds
7418 If negative, gobble data immediately available but don't wait for any.
7420 NSECS is:
7421 an additional duration to wait, measured in nanoseconds
7422 If TIME_LIMIT is zero, then:
7423 If NSECS == 0, there is no limit.
7424 If NSECS > 0, the timeout consists of NSECS only.
7425 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7427 READ_KBD is:
7428 0 to ignore keyboard input, or
7429 1 to return when input is available, or
7430 -1 means caller will actually read the input, so don't throw to
7431 the quit handler.
7433 see full version for other parameters. We know that wait_proc will
7434 always be NULL, since `subprocesses' isn't defined.
7436 DO_DISPLAY means redisplay should be done to show subprocess
7437 output that arrives.
7439 Return -1 signifying we got no output and did not try. */
7442 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7443 bool do_display,
7444 Lisp_Object wait_for_cell,
7445 struct Lisp_Process *wait_proc, int just_wait_proc)
7447 register int nfds;
7448 struct timespec end_time, timeout;
7449 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7451 if (TYPE_MAXIMUM (time_t) < time_limit)
7452 time_limit = TYPE_MAXIMUM (time_t);
7454 if (time_limit < 0 || nsecs < 0)
7455 wait = MINIMUM;
7456 else if (time_limit > 0 || nsecs > 0)
7458 wait = TIMEOUT;
7459 end_time = timespec_add (current_timespec (),
7460 make_timespec (time_limit, nsecs));
7462 else
7463 wait = INFINITY;
7465 /* Turn off periodic alarms (in case they are in use)
7466 and then turn off any other atimers,
7467 because the select emulator uses alarms. */
7468 stop_polling ();
7469 turn_on_atimers (0);
7471 while (1)
7473 bool timeout_reduced_for_timers = false;
7474 fd_set waitchannels;
7475 int xerrno;
7477 /* If calling from keyboard input, do not quit
7478 since we want to return C-g as an input character.
7479 Otherwise, do pending quit if requested. */
7480 if (read_kbd >= 0)
7481 maybe_quit ();
7483 /* Exit now if the cell we're waiting for became non-nil. */
7484 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7485 break;
7487 /* Compute time from now till when time limit is up. */
7488 /* Exit if already run out. */
7489 if (wait == TIMEOUT)
7491 struct timespec now = current_timespec ();
7492 if (timespec_cmp (end_time, now) <= 0)
7493 break;
7494 timeout = timespec_sub (end_time, now);
7496 else
7497 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7499 /* If our caller will not immediately handle keyboard events,
7500 run timer events directly.
7501 (Callers that will immediately read keyboard events
7502 call timer_delay on their own.) */
7503 if (NILP (wait_for_cell))
7505 struct timespec timer_delay;
7509 unsigned old_timers_run = timers_run;
7510 timer_delay = timer_check ();
7511 if (timers_run != old_timers_run && do_display)
7512 /* We must retry, since a timer may have requeued itself
7513 and that could alter the time delay. */
7514 redisplay_preserve_echo_area (14);
7515 else
7516 break;
7518 while (!detect_input_pending ());
7520 /* If there is unread keyboard input, also return. */
7521 if (read_kbd != 0
7522 && requeued_events_pending_p ())
7523 break;
7525 if (timespec_valid_p (timer_delay))
7527 if (timespec_cmp (timer_delay, timeout) < 0)
7529 timeout = timer_delay;
7530 timeout_reduced_for_timers = true;
7535 /* Cause C-g and alarm signals to take immediate action,
7536 and cause input available signals to zero out timeout. */
7537 if (read_kbd < 0)
7538 set_waiting_for_input (&timeout);
7540 /* If a frame has been newly mapped and needs updating,
7541 reprocess its display stuff. */
7542 if (frame_garbaged && do_display)
7544 clear_waiting_for_input ();
7545 redisplay_preserve_echo_area (15);
7546 if (read_kbd < 0)
7547 set_waiting_for_input (&timeout);
7550 /* Wait till there is something to do. */
7551 FD_ZERO (&waitchannels);
7552 if (read_kbd && detect_input_pending ())
7553 nfds = 0;
7554 else
7556 if (read_kbd || !NILP (wait_for_cell))
7557 FD_SET (0, &waitchannels);
7558 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7561 xerrno = errno;
7563 /* Make C-g and alarm signals set flags again. */
7564 clear_waiting_for_input ();
7566 /* If we woke up due to SIGWINCH, actually change size now. */
7567 do_pending_window_change (0);
7569 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7570 /* We waited the full specified time, so return now. */
7571 break;
7573 if (nfds == -1)
7575 /* If the system call was interrupted, then go around the
7576 loop again. */
7577 if (xerrno == EINTR)
7578 FD_ZERO (&waitchannels);
7579 else
7580 report_file_errno ("Failed select", Qnil, xerrno);
7583 /* Check for keyboard input. */
7585 if (read_kbd
7586 && detect_input_pending_run_timers (do_display))
7588 swallow_events (do_display);
7589 if (detect_input_pending_run_timers (do_display))
7590 break;
7593 /* If there is unread keyboard input, also return. */
7594 if (read_kbd
7595 && requeued_events_pending_p ())
7596 break;
7598 /* If wait_for_cell. check for keyboard input
7599 but don't run any timers.
7600 ??? (It seems wrong to me to check for keyboard
7601 input at all when wait_for_cell, but the code
7602 has been this way since July 1994.
7603 Try changing this after version 19.31.) */
7604 if (! NILP (wait_for_cell)
7605 && detect_input_pending ())
7607 swallow_events (do_display);
7608 if (detect_input_pending ())
7609 break;
7612 /* Exit now if the cell we're waiting for became non-nil. */
7613 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7614 break;
7617 start_polling ();
7619 return -1;
7622 #endif /* not subprocesses */
7624 /* The following functions are needed even if async subprocesses are
7625 not supported. Some of them are no-op stubs in that case. */
7627 #ifdef HAVE_TIMERFD
7629 /* Add FD, which is a descriptor returned by timerfd_create,
7630 to the set of non-keyboard input descriptors. */
7632 void
7633 add_timer_wait_descriptor (int fd)
7635 add_read_fd (fd, timerfd_callback, NULL);
7636 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7639 #endif /* HAVE_TIMERFD */
7641 /* If program file NAME starts with /: for quoting a magic
7642 name, remove that, preserving the multibyteness of NAME. */
7644 Lisp_Object
7645 remove_slash_colon (Lisp_Object name)
7647 return
7648 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7649 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7650 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7651 : name);
7654 /* Add DESC to the set of keyboard input descriptors. */
7656 void
7657 add_keyboard_wait_descriptor (int desc)
7659 #ifdef subprocesses /* Actually means "not MSDOS". */
7660 eassert (desc >= 0 && desc < FD_SETSIZE);
7661 fd_callback_info[desc].flags &= ~PROCESS_FD;
7662 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7663 if (desc > max_desc)
7664 max_desc = desc;
7665 #endif
7668 /* From now on, do not expect DESC to give keyboard input. */
7670 void
7671 delete_keyboard_wait_descriptor (int desc)
7673 #ifdef subprocesses
7674 eassert (desc >= 0 && desc < FD_SETSIZE);
7676 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7678 if (desc == max_desc)
7679 recompute_max_desc ();
7680 #endif
7683 /* Setup coding systems of PROCESS. */
7685 void
7686 setup_process_coding_systems (Lisp_Object process)
7688 #ifdef subprocesses
7689 struct Lisp_Process *p = XPROCESS (process);
7690 int inch = p->infd;
7691 int outch = p->outfd;
7692 Lisp_Object coding_system;
7694 if (inch < 0 || outch < 0)
7695 return;
7697 if (!proc_decode_coding_system[inch])
7698 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7699 coding_system = p->decode_coding_system;
7700 if (EQ (p->filter, Qinternal_default_process_filter)
7701 && BUFFERP (p->buffer))
7703 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7704 coding_system = raw_text_coding_system (coding_system);
7706 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7708 if (!proc_encode_coding_system[outch])
7709 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7710 setup_coding_system (p->encode_coding_system,
7711 proc_encode_coding_system[outch]);
7712 #endif
7715 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7716 doc: /* Return the (or a) live process associated with BUFFER.
7717 BUFFER may be a buffer or the name of one.
7718 Return nil if all processes associated with BUFFER have been
7719 deleted or killed. */)
7720 (register Lisp_Object buffer)
7722 #ifdef subprocesses
7723 register Lisp_Object buf, tail, proc;
7725 if (NILP (buffer)) return Qnil;
7726 buf = Fget_buffer (buffer);
7727 if (NILP (buf)) return Qnil;
7729 FOR_EACH_PROCESS (tail, proc)
7730 if (EQ (XPROCESS (proc)->buffer, buf))
7731 return proc;
7732 #endif /* subprocesses */
7733 return Qnil;
7736 DEFUN ("process-inherit-coding-system-flag",
7737 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7738 1, 1, 0,
7739 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7740 If this flag is t, `buffer-file-coding-system' of the buffer
7741 associated with PROCESS will inherit the coding system used to decode
7742 the process output. */)
7743 (register Lisp_Object process)
7745 #ifdef subprocesses
7746 CHECK_PROCESS (process);
7747 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7748 #else
7749 /* Ignore the argument and return the value of
7750 inherit-process-coding-system. */
7751 return inherit_process_coding_system ? Qt : Qnil;
7752 #endif
7755 /* Kill all processes associated with `buffer'.
7756 If `buffer' is nil, kill all processes. */
7758 void
7759 kill_buffer_processes (Lisp_Object buffer)
7761 #ifdef subprocesses
7762 Lisp_Object tail, proc;
7764 FOR_EACH_PROCESS (tail, proc)
7765 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7767 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7768 Fdelete_process (proc);
7769 else if (XPROCESS (proc)->infd >= 0)
7770 process_send_signal (proc, SIGHUP, Qnil, 1);
7772 #else /* subprocesses */
7773 /* Since we have no subprocesses, this does nothing. */
7774 #endif /* subprocesses */
7777 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7778 Swaiting_for_user_input_p, 0, 0, 0,
7779 doc: /* Return non-nil if Emacs is waiting for input from the user.
7780 This is intended for use by asynchronous process output filters and sentinels. */)
7781 (void)
7783 #ifdef subprocesses
7784 return (waiting_for_user_input_p ? Qt : Qnil);
7785 #else
7786 return Qnil;
7787 #endif
7790 /* Stop reading input from keyboard sources. */
7792 void
7793 hold_keyboard_input (void)
7795 kbd_is_on_hold = 1;
7798 /* Resume reading input from keyboard sources. */
7800 void
7801 unhold_keyboard_input (void)
7803 kbd_is_on_hold = 0;
7806 /* Return true if keyboard input is on hold, zero otherwise. */
7808 bool
7809 kbd_on_hold_p (void)
7811 return kbd_is_on_hold;
7815 /* Enumeration of and access to system processes a-la ps(1). */
7817 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7818 0, 0, 0,
7819 doc: /* Return a list of numerical process IDs of all running processes.
7820 If this functionality is unsupported, return nil.
7822 See `process-attributes' for getting attributes of a process given its ID. */)
7823 (void)
7825 return list_system_processes ();
7828 DEFUN ("process-attributes", Fprocess_attributes,
7829 Sprocess_attributes, 1, 1, 0,
7830 doc: /* Return attributes of the process given by its PID, a number.
7832 Value is an alist where each element is a cons cell of the form
7834 (KEY . VALUE)
7836 If this functionality is unsupported, the value is nil.
7838 See `list-system-processes' for getting a list of all process IDs.
7840 The KEYs of the attributes that this function may return are listed
7841 below, together with the type of the associated VALUE (in parentheses).
7842 Not all platforms support all of these attributes; unsupported
7843 attributes will not appear in the returned alist.
7844 Unless explicitly indicated otherwise, numbers can have either
7845 integer or floating point values.
7847 euid -- Effective user User ID of the process (number)
7848 user -- User name corresponding to euid (string)
7849 egid -- Effective user Group ID of the process (number)
7850 group -- Group name corresponding to egid (string)
7851 comm -- Command name (executable name only) (string)
7852 state -- Process state code, such as "S", "R", or "T" (string)
7853 ppid -- Parent process ID (number)
7854 pgrp -- Process group ID (number)
7855 sess -- Session ID, i.e. process ID of session leader (number)
7856 ttname -- Controlling tty name (string)
7857 tpgid -- ID of foreground process group on the process's tty (number)
7858 minflt -- number of minor page faults (number)
7859 majflt -- number of major page faults (number)
7860 cminflt -- cumulative number of minor page faults (number)
7861 cmajflt -- cumulative number of major page faults (number)
7862 utime -- user time used by the process, in (current-time) format,
7863 which is a list of integers (HIGH LOW USEC PSEC)
7864 stime -- system time used by the process (current-time)
7865 time -- sum of utime and stime (current-time)
7866 cutime -- user time used by the process and its children (current-time)
7867 cstime -- system time used by the process and its children (current-time)
7868 ctime -- sum of cutime and cstime (current-time)
7869 pri -- priority of the process (number)
7870 nice -- nice value of the process (number)
7871 thcount -- process thread count (number)
7872 start -- time the process started (current-time)
7873 vsize -- virtual memory size of the process in KB's (number)
7874 rss -- resident set size of the process in KB's (number)
7875 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7876 pcpu -- percents of CPU time used by the process (floating-point number)
7877 pmem -- percents of total physical memory used by process's resident set
7878 (floating-point number)
7879 args -- command line which invoked the process (string). */)
7880 ( Lisp_Object pid)
7882 return system_process_attributes (pid);
7885 #ifdef subprocesses
7886 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7887 Invoke this after init_process_emacs, and after glib and/or GNUstep
7888 futz with the SIGCHLD handler, but before Emacs forks any children.
7889 This function's caller should block SIGCHLD. */
7891 void
7892 catch_child_signal (void)
7894 struct sigaction action, old_action;
7895 sigset_t oldset;
7896 emacs_sigaction_init (&action, deliver_child_signal);
7897 block_child_signal (&oldset);
7898 sigaction (SIGCHLD, &action, &old_action);
7899 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7900 || ! (old_action.sa_flags & SA_SIGINFO));
7902 if (old_action.sa_handler != deliver_child_signal)
7903 lib_child_handler
7904 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7905 ? dummy_handler
7906 : old_action.sa_handler);
7907 unblock_child_signal (&oldset);
7909 #endif /* subprocesses */
7911 /* Limit the number of open files to the value it had at startup. */
7913 void
7914 restore_nofile_limit (void)
7916 #ifdef HAVE_SETRLIMIT
7917 if (FD_SETSIZE < nofile_limit.rlim_cur)
7918 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7919 #endif
7923 /* This is not called "init_process" because that is the name of a
7924 Mach system call, so it would cause problems on Darwin systems. */
7925 void
7926 init_process_emacs (int sockfd)
7928 #ifdef subprocesses
7929 int i;
7931 inhibit_sentinels = 0;
7933 #ifndef CANNOT_DUMP
7934 if (! noninteractive || initialized)
7935 #endif
7937 #if defined HAVE_GLIB && !defined WINDOWSNT
7938 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7939 this should always fail, but is enough to initialize glib's
7940 private SIGCHLD handler, allowing catch_child_signal to copy
7941 it into lib_child_handler. */
7942 g_source_unref (g_child_watch_source_new (getpid ()));
7943 #endif
7944 catch_child_signal ();
7947 #ifdef HAVE_SETRLIMIT
7948 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
7949 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
7950 nofile_limit.rlim_cur = 0;
7951 else if (FD_SETSIZE < nofile_limit.rlim_cur)
7953 struct rlimit rlim = nofile_limit;
7954 rlim.rlim_cur = FD_SETSIZE;
7955 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
7956 nofile_limit.rlim_cur = 0;
7958 #endif
7960 external_sock_fd = sockfd;
7961 max_desc = -1;
7962 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7964 num_pending_connects = 0;
7966 process_output_delay_count = 0;
7967 process_output_skip = 0;
7969 /* Don't do this, it caused infinite select loops. The display
7970 method should call add_keyboard_wait_descriptor on stdin if it
7971 needs that. */
7972 #if 0
7973 FD_SET (0, &input_wait_mask);
7974 #endif
7976 Vprocess_alist = Qnil;
7977 deleted_pid_list = Qnil;
7978 for (i = 0; i < FD_SETSIZE; i++)
7980 chan_process[i] = Qnil;
7981 proc_buffered_char[i] = -1;
7983 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7984 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7985 #ifdef DATAGRAM_SOCKETS
7986 memset (datagram_address, 0, sizeof datagram_address);
7987 #endif
7989 #if defined (DARWIN_OS)
7990 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7991 processes. As such, we only change the default value. */
7992 if (initialized)
7994 char const *release = (STRINGP (Voperating_system_release)
7995 ? SSDATA (Voperating_system_release)
7996 : 0);
7997 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7998 Vprocess_connection_type = Qnil;
8001 #endif
8002 #endif /* subprocesses */
8003 kbd_is_on_hold = 0;
8006 void
8007 syms_of_process (void)
8009 #ifdef subprocesses
8011 DEFSYM (Qprocessp, "processp");
8012 DEFSYM (Qrun, "run");
8013 DEFSYM (Qstop, "stop");
8014 DEFSYM (Qsignal, "signal");
8016 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8017 here again. */
8019 DEFSYM (Qopen, "open");
8020 DEFSYM (Qclosed, "closed");
8021 DEFSYM (Qconnect, "connect");
8022 DEFSYM (Qfailed, "failed");
8023 DEFSYM (Qlisten, "listen");
8024 DEFSYM (Qlocal, "local");
8025 DEFSYM (Qipv4, "ipv4");
8026 #ifdef AF_INET6
8027 DEFSYM (Qipv6, "ipv6");
8028 #endif
8029 DEFSYM (Qdatagram, "datagram");
8030 DEFSYM (Qseqpacket, "seqpacket");
8032 DEFSYM (QCport, ":port");
8033 DEFSYM (QCspeed, ":speed");
8034 DEFSYM (QCprocess, ":process");
8036 DEFSYM (QCbytesize, ":bytesize");
8037 DEFSYM (QCstopbits, ":stopbits");
8038 DEFSYM (QCparity, ":parity");
8039 DEFSYM (Qodd, "odd");
8040 DEFSYM (Qeven, "even");
8041 DEFSYM (QCflowcontrol, ":flowcontrol");
8042 DEFSYM (Qhw, "hw");
8043 DEFSYM (Qsw, "sw");
8044 DEFSYM (QCsummary, ":summary");
8046 DEFSYM (Qreal, "real");
8047 DEFSYM (Qnetwork, "network");
8048 DEFSYM (Qserial, "serial");
8049 DEFSYM (Qpipe, "pipe");
8050 DEFSYM (QCbuffer, ":buffer");
8051 DEFSYM (QChost, ":host");
8052 DEFSYM (QCservice, ":service");
8053 DEFSYM (QClocal, ":local");
8054 DEFSYM (QCremote, ":remote");
8055 DEFSYM (QCcoding, ":coding");
8056 DEFSYM (QCserver, ":server");
8057 DEFSYM (QCnowait, ":nowait");
8058 DEFSYM (QCsentinel, ":sentinel");
8059 DEFSYM (QCuse_external_socket, ":use-external-socket");
8060 DEFSYM (QCtls_parameters, ":tls-parameters");
8061 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8062 DEFSYM (QClog, ":log");
8063 DEFSYM (QCnoquery, ":noquery");
8064 DEFSYM (QCstop, ":stop");
8065 DEFSYM (QCplist, ":plist");
8066 DEFSYM (QCcommand, ":command");
8067 DEFSYM (QCconnection_type, ":connection-type");
8068 DEFSYM (QCstderr, ":stderr");
8069 DEFSYM (Qpty, "pty");
8070 DEFSYM (Qpipe, "pipe");
8072 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8074 staticpro (&Vprocess_alist);
8075 staticpro (&deleted_pid_list);
8077 #endif /* subprocesses */
8079 DEFSYM (QCname, ":name");
8080 DEFSYM (QCtype, ":type");
8082 DEFSYM (Qeuid, "euid");
8083 DEFSYM (Qegid, "egid");
8084 DEFSYM (Quser, "user");
8085 DEFSYM (Qgroup, "group");
8086 DEFSYM (Qcomm, "comm");
8087 DEFSYM (Qstate, "state");
8088 DEFSYM (Qppid, "ppid");
8089 DEFSYM (Qpgrp, "pgrp");
8090 DEFSYM (Qsess, "sess");
8091 DEFSYM (Qttname, "ttname");
8092 DEFSYM (Qtpgid, "tpgid");
8093 DEFSYM (Qminflt, "minflt");
8094 DEFSYM (Qmajflt, "majflt");
8095 DEFSYM (Qcminflt, "cminflt");
8096 DEFSYM (Qcmajflt, "cmajflt");
8097 DEFSYM (Qutime, "utime");
8098 DEFSYM (Qstime, "stime");
8099 DEFSYM (Qtime, "time");
8100 DEFSYM (Qcutime, "cutime");
8101 DEFSYM (Qcstime, "cstime");
8102 DEFSYM (Qctime, "ctime");
8103 #ifdef subprocesses
8104 DEFSYM (Qinternal_default_process_sentinel,
8105 "internal-default-process-sentinel");
8106 DEFSYM (Qinternal_default_process_filter,
8107 "internal-default-process-filter");
8108 #endif
8109 DEFSYM (Qpri, "pri");
8110 DEFSYM (Qnice, "nice");
8111 DEFSYM (Qthcount, "thcount");
8112 DEFSYM (Qstart, "start");
8113 DEFSYM (Qvsize, "vsize");
8114 DEFSYM (Qrss, "rss");
8115 DEFSYM (Qetime, "etime");
8116 DEFSYM (Qpcpu, "pcpu");
8117 DEFSYM (Qpmem, "pmem");
8118 DEFSYM (Qargs, "args");
8120 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8121 doc: /* Non-nil means delete processes immediately when they exit.
8122 A value of nil means don't delete them until `list-processes' is run. */);
8124 delete_exited_processes = 1;
8126 #ifdef subprocesses
8127 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8128 doc: /* Control type of device used to communicate with subprocesses.
8129 Values are nil to use a pipe, or t or `pty' to use a pty.
8130 The value has no effect if the system has no ptys or if all ptys are busy:
8131 then a pipe is used in any case.
8132 The value takes effect when `start-process' is called. */);
8133 Vprocess_connection_type = Qt;
8135 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8136 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8137 On some systems, when Emacs reads the output from a subprocess, the output data
8138 is read in very small blocks, potentially resulting in very poor performance.
8139 This behavior can be remedied to some extent by setting this variable to a
8140 non-nil value, as it will automatically delay reading from such processes, to
8141 allow them to produce more output before Emacs tries to read it.
8142 If the value is t, the delay is reset after each write to the process; any other
8143 non-nil value means that the delay is not reset on write.
8144 The variable takes effect when `start-process' is called. */);
8145 Vprocess_adaptive_read_buffering = Qt;
8147 defsubr (&Sprocessp);
8148 defsubr (&Sget_process);
8149 defsubr (&Sdelete_process);
8150 defsubr (&Sprocess_status);
8151 defsubr (&Sprocess_exit_status);
8152 defsubr (&Sprocess_id);
8153 defsubr (&Sprocess_name);
8154 defsubr (&Sprocess_tty_name);
8155 defsubr (&Sprocess_command);
8156 defsubr (&Sset_process_buffer);
8157 defsubr (&Sprocess_buffer);
8158 defsubr (&Sprocess_mark);
8159 defsubr (&Sset_process_filter);
8160 defsubr (&Sprocess_filter);
8161 defsubr (&Sset_process_sentinel);
8162 defsubr (&Sprocess_sentinel);
8163 defsubr (&Sset_process_thread);
8164 defsubr (&Sprocess_thread);
8165 defsubr (&Sset_process_window_size);
8166 defsubr (&Sset_process_inherit_coding_system_flag);
8167 defsubr (&Sset_process_query_on_exit_flag);
8168 defsubr (&Sprocess_query_on_exit_flag);
8169 defsubr (&Sprocess_contact);
8170 defsubr (&Sprocess_plist);
8171 defsubr (&Sset_process_plist);
8172 defsubr (&Sprocess_list);
8173 defsubr (&Smake_process);
8174 defsubr (&Smake_pipe_process);
8175 defsubr (&Sserial_process_configure);
8176 defsubr (&Smake_serial_process);
8177 defsubr (&Sset_network_process_option);
8178 defsubr (&Smake_network_process);
8179 defsubr (&Sformat_network_address);
8180 defsubr (&Snetwork_interface_list);
8181 defsubr (&Snetwork_interface_info);
8182 #ifdef DATAGRAM_SOCKETS
8183 defsubr (&Sprocess_datagram_address);
8184 defsubr (&Sset_process_datagram_address);
8185 #endif
8186 defsubr (&Saccept_process_output);
8187 defsubr (&Sprocess_send_region);
8188 defsubr (&Sprocess_send_string);
8189 defsubr (&Sinterrupt_process);
8190 defsubr (&Skill_process);
8191 defsubr (&Squit_process);
8192 defsubr (&Sstop_process);
8193 defsubr (&Scontinue_process);
8194 defsubr (&Sprocess_running_child_p);
8195 defsubr (&Sprocess_send_eof);
8196 defsubr (&Ssignal_process);
8197 defsubr (&Swaiting_for_user_input_p);
8198 defsubr (&Sprocess_type);
8199 defsubr (&Sinternal_default_process_sentinel);
8200 defsubr (&Sinternal_default_process_filter);
8201 defsubr (&Sset_process_coding_system);
8202 defsubr (&Sprocess_coding_system);
8203 defsubr (&Sset_process_filter_multibyte);
8204 defsubr (&Sprocess_filter_multibyte_p);
8207 Lisp_Object subfeatures = Qnil;
8208 const struct socket_options *sopt;
8210 #define ADD_SUBFEATURE(key, val) \
8211 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8213 ADD_SUBFEATURE (QCnowait, Qt);
8214 #ifdef DATAGRAM_SOCKETS
8215 ADD_SUBFEATURE (QCtype, Qdatagram);
8216 #endif
8217 #ifdef HAVE_SEQPACKET
8218 ADD_SUBFEATURE (QCtype, Qseqpacket);
8219 #endif
8220 #ifdef HAVE_LOCAL_SOCKETS
8221 ADD_SUBFEATURE (QCfamily, Qlocal);
8222 #endif
8223 ADD_SUBFEATURE (QCfamily, Qipv4);
8224 #ifdef AF_INET6
8225 ADD_SUBFEATURE (QCfamily, Qipv6);
8226 #endif
8227 #ifdef HAVE_GETSOCKNAME
8228 ADD_SUBFEATURE (QCservice, Qt);
8229 #endif
8230 ADD_SUBFEATURE (QCserver, Qt);
8232 for (sopt = socket_options; sopt->name; sopt++)
8233 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8235 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8238 #endif /* subprocesses */
8240 defsubr (&Sget_buffer_process);
8241 defsubr (&Sprocess_inherit_coding_system_flag);
8242 defsubr (&Slist_system_processes);
8243 defsubr (&Sprocess_attributes);