Rename comment-depth (etc.) to literal-cache (etc.). Enable it by default
[emacs.git] / src / process.c
blob56f036cd7d20390522cd7c0702aec9cc31e3e193
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at 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 <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_UTIL_H
79 #include <util.h>
80 #endif
82 #ifdef HAVE_PTY_H
83 #include <pty.h>
84 #endif
86 #include <c-ctype.h>
87 #include <sig2str.h>
88 #include <verify.h>
90 #endif /* subprocesses */
92 #include "systime.h"
93 #include "systty.h"
95 #include "window.h"
96 #include "character.h"
97 #include "buffer.h"
98 #include "coding.h"
99 #include "process.h"
100 #include "frame.h"
101 #include "termopts.h"
102 #include "keyboard.h"
103 #include "blockinput.h"
104 #include "atimer.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
107 #include "syswait.h"
108 #ifdef HAVE_GNUTLS
109 #include "gnutls.h"
110 #endif
112 #ifdef HAVE_WINDOW_SYSTEM
113 #include TERM_HEADER
114 #endif /* HAVE_WINDOW_SYSTEM */
116 #ifdef HAVE_GLIB
117 #include "xgselect.h"
118 #ifndef WINDOWSNT
119 #include <glib.h>
120 #endif
121 #endif
123 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
124 /* This is 0.1s in nanoseconds. */
125 #define ASYNC_RETRY_NSEC 100000000
126 #endif
128 #ifdef WINDOWSNT
129 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
130 struct timespec *, void *);
131 #endif
133 /* Work around GCC 4.7.0 bug with strict overflow checking; see
134 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
135 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
136 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
137 # pragma GCC diagnostic ignored "-Wstrict-overflow"
138 #endif
140 /* True if keyboard input is on hold, zero otherwise. */
142 static bool kbd_is_on_hold;
144 /* Nonzero means don't run process sentinels. This is used
145 when exiting. */
146 bool inhibit_sentinels;
148 #ifdef subprocesses
150 #ifndef SOCK_CLOEXEC
151 # define SOCK_CLOEXEC 0
152 #endif
154 #ifndef HAVE_ACCEPT4
156 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
158 static int
159 close_on_exec (int fd)
161 if (0 <= fd)
162 fcntl (fd, F_SETFD, FD_CLOEXEC);
163 return fd;
166 # undef accept4
167 # define accept4(sockfd, addr, addrlen, flags) \
168 process_accept4 (sockfd, addr, addrlen, flags)
169 static int
170 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
172 return close_on_exec (accept (sockfd, addr, addrlen));
175 static int
176 process_socket (int domain, int type, int protocol)
178 return close_on_exec (socket (domain, type, protocol));
180 # undef socket
181 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
182 #endif
184 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
185 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
186 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
187 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
189 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
191 /* Number of events of change of status of a process. */
192 static EMACS_INT process_tick;
193 /* Number of events for which the user or sentinel has been notified. */
194 static EMACS_INT update_tick;
196 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
197 The code can be simplified by assuming NON_BLOCKING_CONNECT once
198 Emacs starts assuming POSIX 1003.1-2001 or later. */
200 #if (defined HAVE_SELECT \
201 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
202 && (defined EWOULDBLOCK || defined EINPROGRESS))
203 # define NON_BLOCKING_CONNECT
204 #endif
206 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
207 this system. We need to read full packets, so we need a
208 "non-destructive" select. So we require either native select,
209 or emulation of select using FIONREAD. */
211 #ifndef BROKEN_DATAGRAM_SOCKETS
212 # if defined HAVE_SELECT || defined USABLE_FIONREAD
213 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
214 # define DATAGRAM_SOCKETS
215 # endif
216 # endif
217 #endif
219 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
220 # define HAVE_SEQPACKET
221 #endif
223 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
224 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
225 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
227 /* Number of processes which have a non-zero read_output_delay,
228 and therefore might be delayed for adaptive read buffering. */
230 static int process_output_delay_count;
232 /* True if any process has non-nil read_output_skip. */
234 static bool process_output_skip;
236 static void create_process (Lisp_Object, char **, Lisp_Object);
237 #ifdef USABLE_SIGIO
238 static bool keyboard_bit_set (fd_set *);
239 #endif
240 static void deactivate_process (Lisp_Object);
241 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
242 static int read_process_output (Lisp_Object, int);
243 static void handle_child_signal (int);
244 static void create_pty (Lisp_Object);
246 static Lisp_Object get_process (register Lisp_Object name);
247 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
249 /* Mask of bits indicating the descriptors that we wait for input on. */
251 static fd_set input_wait_mask;
253 /* Mask that excludes keyboard input descriptor(s). */
255 static fd_set non_keyboard_wait_mask;
257 /* Mask that excludes process input descriptor(s). */
259 static fd_set non_process_wait_mask;
261 /* Mask for selecting for write. */
263 static fd_set write_mask;
265 #ifdef NON_BLOCKING_CONNECT
266 /* Mask of bits indicating the descriptors that we wait for connect to
267 complete on. Once they complete, they are removed from this mask
268 and added to the input_wait_mask and non_keyboard_wait_mask. */
270 static fd_set connect_wait_mask;
272 /* Number of bits set in connect_wait_mask. */
273 static int num_pending_connects;
274 #endif /* NON_BLOCKING_CONNECT */
276 /* The largest descriptor currently in use for a process object; -1 if none. */
277 static int max_process_desc;
279 /* The largest descriptor currently in use for input; -1 if none. */
280 static int max_input_desc;
282 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
283 static Lisp_Object chan_process[FD_SETSIZE];
284 static void wait_for_socket_fds (Lisp_Object, char const *);
286 /* Alist of elements (NAME . PROCESS). */
287 static Lisp_Object Vprocess_alist;
289 /* Buffered-ahead input char from process, indexed by channel.
290 -1 means empty (no char is buffered).
291 Used on sys V where the only way to tell if there is any
292 output from the process is to read at least one char.
293 Always -1 on systems that support FIONREAD. */
295 static int proc_buffered_char[FD_SETSIZE];
297 /* Table of `struct coding-system' for each process. */
298 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
299 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
301 #ifdef DATAGRAM_SOCKETS
302 /* Table of `partner address' for datagram sockets. */
303 static struct sockaddr_and_len {
304 struct sockaddr *sa;
305 ptrdiff_t len;
306 } datagram_address[FD_SETSIZE];
307 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
308 #define DATAGRAM_CONN_P(proc) \
309 (PROCESSP (proc) && \
310 XPROCESS (proc)->infd >= 0 && \
311 datagram_address[XPROCESS (proc)->infd].sa != 0)
312 #else
313 #define DATAGRAM_CHAN_P(chan) (0)
314 #define DATAGRAM_CONN_P(proc) (0)
315 #endif
317 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
318 a `for' loop which iterates over processes from Vprocess_alist. */
320 #define FOR_EACH_PROCESS(list_var, proc_var) \
321 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
323 /* These setters are used only in this file, so they can be private. */
324 static void
325 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
327 p->buffer = val;
329 static void
330 pset_command (struct Lisp_Process *p, Lisp_Object val)
332 p->command = val;
334 static void
335 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
337 p->decode_coding_system = val;
339 static void
340 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
342 p->decoding_buf = val;
344 static void
345 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
347 p->encode_coding_system = val;
349 static void
350 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
352 p->encoding_buf = val;
354 static void
355 pset_filter (struct Lisp_Process *p, Lisp_Object val)
357 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
359 static void
360 pset_log (struct Lisp_Process *p, Lisp_Object val)
362 p->log = val;
364 static void
365 pset_mark (struct Lisp_Process *p, Lisp_Object val)
367 p->mark = val;
369 static void
370 pset_name (struct Lisp_Process *p, Lisp_Object val)
372 p->name = val;
374 static void
375 pset_plist (struct Lisp_Process *p, Lisp_Object val)
377 p->plist = val;
379 static void
380 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
382 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
384 static void
385 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
387 p->tty_name = val;
389 static void
390 pset_type (struct Lisp_Process *p, Lisp_Object val)
392 p->type = val;
394 static void
395 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
397 p->write_queue = val;
399 static void
400 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
402 p->stderrproc = val;
406 static Lisp_Object
407 make_lisp_proc (struct Lisp_Process *p)
409 return make_lisp_ptr (p, Lisp_Vectorlike);
412 static struct fd_callback_data
414 fd_callback func;
415 void *data;
416 #define FOR_READ 1
417 #define FOR_WRITE 2
418 int condition; /* Mask of the defines above. */
419 } fd_callback_info[FD_SETSIZE];
422 /* Add a file descriptor FD to be monitored for when read is possible.
423 When read is possible, call FUNC with argument DATA. */
425 void
426 add_read_fd (int fd, fd_callback func, void *data)
428 add_keyboard_wait_descriptor (fd);
430 fd_callback_info[fd].func = func;
431 fd_callback_info[fd].data = data;
432 fd_callback_info[fd].condition |= FOR_READ;
435 /* Stop monitoring file descriptor FD for when read is possible. */
437 void
438 delete_read_fd (int fd)
440 delete_keyboard_wait_descriptor (fd);
442 fd_callback_info[fd].condition &= ~FOR_READ;
443 if (fd_callback_info[fd].condition == 0)
445 fd_callback_info[fd].func = 0;
446 fd_callback_info[fd].data = 0;
450 /* Add a file descriptor FD to be monitored for when write is possible.
451 When write is possible, call FUNC with argument DATA. */
453 void
454 add_write_fd (int fd, fd_callback func, void *data)
456 FD_SET (fd, &write_mask);
457 if (fd > max_input_desc)
458 max_input_desc = fd;
460 fd_callback_info[fd].func = func;
461 fd_callback_info[fd].data = data;
462 fd_callback_info[fd].condition |= FOR_WRITE;
465 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
467 static void
468 delete_input_desc (int fd)
470 if (fd == max_input_desc)
473 fd--;
474 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
475 || FD_ISSET (fd, &write_mask)));
477 max_input_desc = fd;
481 /* Stop monitoring file descriptor FD for when write is possible. */
483 void
484 delete_write_fd (int fd)
486 FD_CLR (fd, &write_mask);
487 fd_callback_info[fd].condition &= ~FOR_WRITE;
488 if (fd_callback_info[fd].condition == 0)
490 fd_callback_info[fd].func = 0;
491 fd_callback_info[fd].data = 0;
492 delete_input_desc (fd);
497 /* Compute the Lisp form of the process status, p->status, from
498 the numeric status that was returned by `wait'. */
500 static Lisp_Object status_convert (int);
502 static void
503 update_status (struct Lisp_Process *p)
505 eassert (p->raw_status_new);
506 pset_status (p, status_convert (p->raw_status));
507 p->raw_status_new = 0;
510 /* Convert a process status word in Unix format to
511 the list that we use internally. */
513 static Lisp_Object
514 status_convert (int w)
516 if (WIFSTOPPED (w))
517 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
518 else if (WIFEXITED (w))
519 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
520 WCOREDUMP (w) ? Qt : Qnil));
521 else if (WIFSIGNALED (w))
522 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
523 WCOREDUMP (w) ? Qt : Qnil));
524 else
525 return Qrun;
528 /* Given a status-list, extract the three pieces of information
529 and store them individually through the three pointers. */
531 static void
532 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
534 Lisp_Object tem;
536 if (SYMBOLP (l))
538 *symbol = l;
539 *code = 0;
540 *coredump = 0;
542 else
544 *symbol = XCAR (l);
545 tem = XCDR (l);
546 *code = XFASTINT (XCAR (tem));
547 tem = XCDR (tem);
548 *coredump = !NILP (tem);
552 /* Return a string describing a process status list. */
554 static Lisp_Object
555 status_message (struct Lisp_Process *p)
557 Lisp_Object status = p->status;
558 Lisp_Object symbol;
559 int code;
560 bool coredump;
561 Lisp_Object string;
563 decode_status (status, &symbol, &code, &coredump);
565 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
567 char const *signame;
568 synchronize_system_messages_locale ();
569 signame = strsignal (code);
570 if (signame == 0)
571 string = build_string ("unknown");
572 else
574 int c1, c2;
576 string = build_unibyte_string (signame);
577 if (! NILP (Vlocale_coding_system))
578 string = (code_convert_string_norecord
579 (string, Vlocale_coding_system, 0));
580 c1 = STRING_CHAR (SDATA (string));
581 c2 = downcase (c1);
582 if (c1 != c2)
583 Faset (string, make_number (0), make_number (c2));
585 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
586 return concat2 (string, suffix);
588 else if (EQ (symbol, Qexit))
590 if (NETCONN1_P (p))
591 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
592 if (code == 0)
593 return build_string ("finished\n");
594 AUTO_STRING (prefix, "exited abnormally with code ");
595 string = Fnumber_to_string (make_number (code));
596 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
597 return concat3 (prefix, string, suffix);
599 else if (EQ (symbol, Qfailed))
601 AUTO_STRING (prefix, "failed with code ");
602 string = Fnumber_to_string (make_number (code));
603 AUTO_STRING (suffix, "\n");
604 return concat3 (prefix, string, suffix);
606 else
607 return Fcopy_sequence (Fsymbol_name (symbol));
610 enum { PTY_NAME_SIZE = 24 };
612 /* Open an available pty, returning a file descriptor.
613 Store into PTY_NAME the file name of the terminal corresponding to the pty.
614 Return -1 on failure. */
616 static int
617 allocate_pty (char pty_name[PTY_NAME_SIZE])
619 #ifdef HAVE_PTYS
620 int fd;
622 #ifdef PTY_ITERATION
623 PTY_ITERATION
624 #else
625 register int c, i;
626 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
627 for (i = 0; i < 16; i++)
628 #endif
630 #ifdef PTY_NAME_SPRINTF
631 PTY_NAME_SPRINTF
632 #else
633 sprintf (pty_name, "/dev/pty%c%x", c, i);
634 #endif /* no PTY_NAME_SPRINTF */
636 #ifdef PTY_OPEN
637 PTY_OPEN;
638 #else /* no PTY_OPEN */
639 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
640 #endif /* no PTY_OPEN */
642 if (fd >= 0)
644 #ifdef PTY_TTY_NAME_SPRINTF
645 PTY_TTY_NAME_SPRINTF
646 #else
647 sprintf (pty_name, "/dev/tty%c%x", c, i);
648 #endif /* no PTY_TTY_NAME_SPRINTF */
650 /* Set FD's close-on-exec flag. This is needed even if
651 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
652 doesn't require support for that combination.
653 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
654 doesn't work if the close-on-exec flag is set (Bug#20555).
655 Multithreaded platforms where posix_openpt ignores
656 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
657 have a race condition between the PTY_OPEN and here. */
658 fcntl (fd, F_SETFD, FD_CLOEXEC);
660 /* Check to make certain that both sides are available.
661 This avoids a nasty yet stupid bug in rlogins. */
662 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
664 emacs_close (fd);
665 # ifndef __sgi
666 continue;
667 # else
668 return -1;
669 # endif /* __sgi */
671 setup_pty (fd);
672 return fd;
675 #endif /* HAVE_PTYS */
676 return -1;
679 /* Allocate basically initialized process. */
681 static struct Lisp_Process *
682 allocate_process (void)
684 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
687 static Lisp_Object
688 make_process (Lisp_Object name)
690 register Lisp_Object val, tem, name1;
691 register struct Lisp_Process *p;
692 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
693 printmax_t i;
695 p = allocate_process ();
696 /* Initialize Lisp data. Note that allocate_process initializes all
697 Lisp data to nil, so do it only for slots which should not be nil. */
698 pset_status (p, Qrun);
699 pset_mark (p, Fmake_marker ());
701 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
702 non-Lisp data, so do it only for slots which should not be zero. */
703 p->infd = -1;
704 p->outfd = -1;
705 for (i = 0; i < PROCESS_OPEN_FDS; i++)
706 p->open_fd[i] = -1;
708 #ifdef HAVE_GNUTLS
709 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
710 p->gnutls_boot_parameters = Qnil;
711 #endif
713 /* If name is already in use, modify it until it is unused. */
715 name1 = name;
716 for (i = 1; ; i++)
718 tem = Fget_process (name1);
719 if (NILP (tem)) break;
720 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
722 name = name1;
723 pset_name (p, name);
724 pset_sentinel (p, Qinternal_default_process_sentinel);
725 pset_filter (p, Qinternal_default_process_filter);
726 XSETPROCESS (val, p);
727 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
728 return val;
731 static void
732 remove_process (register Lisp_Object proc)
734 register Lisp_Object pair;
736 pair = Frassq (proc, Vprocess_alist);
737 Vprocess_alist = Fdelq (pair, Vprocess_alist);
739 deactivate_process (proc);
742 #ifdef HAVE_GETADDRINFO_A
743 static void
744 free_dns_request (Lisp_Object proc)
746 struct Lisp_Process *p = XPROCESS (proc);
748 if (p->dns_request->ar_result)
749 freeaddrinfo (p->dns_request->ar_result);
750 xfree (p->dns_request);
751 p->dns_request = NULL;
753 #endif
756 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
757 doc: /* Return t if OBJECT is a process. */)
758 (Lisp_Object object)
760 return PROCESSP (object) ? Qt : Qnil;
763 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
764 doc: /* Return the process named NAME, or nil if there is none. */)
765 (register Lisp_Object name)
767 if (PROCESSP (name))
768 return name;
769 CHECK_STRING (name);
770 return Fcdr (Fassoc (name, Vprocess_alist));
773 /* This is how commands for the user decode process arguments. It
774 accepts a process, a process name, a buffer, a buffer name, or nil.
775 Buffers denote the first process in the buffer, and nil denotes the
776 current buffer. */
778 static Lisp_Object
779 get_process (register Lisp_Object name)
781 register Lisp_Object proc, obj;
782 if (STRINGP (name))
784 obj = Fget_process (name);
785 if (NILP (obj))
786 obj = Fget_buffer (name);
787 if (NILP (obj))
788 error ("Process %s does not exist", SDATA (name));
790 else if (NILP (name))
791 obj = Fcurrent_buffer ();
792 else
793 obj = name;
795 /* Now obj should be either a buffer object or a process object. */
796 if (BUFFERP (obj))
798 if (NILP (BVAR (XBUFFER (obj), name)))
799 error ("Attempt to get process for a dead buffer");
800 proc = Fget_buffer_process (obj);
801 if (NILP (proc))
802 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
804 else
806 CHECK_PROCESS (obj);
807 proc = obj;
809 return proc;
813 /* Fdelete_process promises to immediately forget about the process, but in
814 reality, Emacs needs to remember those processes until they have been
815 treated by the SIGCHLD handler and waitpid has been invoked on them;
816 otherwise they might fill up the kernel's process table.
818 Some processes created by call-process are also put onto this list.
820 Members of this list are (process-ID . filename) pairs. The
821 process-ID is a number; the filename, if a string, is a file that
822 needs to be removed after the process exits. */
823 static Lisp_Object deleted_pid_list;
825 void
826 record_deleted_pid (pid_t pid, Lisp_Object filename)
828 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
829 /* GC treated elements set to nil. */
830 Fdelq (Qnil, deleted_pid_list));
834 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
835 doc: /* Delete PROCESS: kill it and forget about it immediately.
836 PROCESS may be a process, a buffer, the name of a process or buffer, or
837 nil, indicating the current buffer's process. */)
838 (register Lisp_Object process)
840 register struct Lisp_Process *p;
842 process = get_process (process);
843 p = XPROCESS (process);
845 #ifdef HAVE_GETADDRINFO_A
846 if (p->dns_request)
848 /* Cancel the request. Unless shutting down, wait until
849 completion. Free the request if completely canceled. */
851 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
852 if (!canceled && !inhibit_sentinels)
854 struct gaicb const *req = p->dns_request;
855 while (gai_suspend (&req, 1, NULL) != 0)
856 continue;
857 canceled = true;
859 if (canceled)
860 free_dns_request (process);
862 #endif
864 p->raw_status_new = 0;
865 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
867 pset_status (p, list2 (Qexit, make_number (0)));
868 p->tick = ++process_tick;
869 status_notify (p, NULL);
870 redisplay_preserve_echo_area (13);
872 else
874 if (p->alive)
875 record_kill_process (p, Qnil);
877 if (p->infd >= 0)
879 /* Update P's status, since record_kill_process will make the
880 SIGCHLD handler update deleted_pid_list, not *P. */
881 Lisp_Object symbol;
882 if (p->raw_status_new)
883 update_status (p);
884 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
885 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
886 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
888 p->tick = ++process_tick;
889 status_notify (p, NULL);
890 redisplay_preserve_echo_area (13);
893 remove_process (process);
894 return Qnil;
897 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
898 doc: /* Return the status of PROCESS.
899 The returned value is one of the following symbols:
900 run -- for a process that is running.
901 stop -- for a process stopped but continuable.
902 exit -- for a process that has exited.
903 signal -- for a process that has got a fatal signal.
904 open -- for a network stream connection that is open.
905 listen -- for a network stream server that is listening.
906 closed -- for a network stream connection that is closed.
907 connect -- when waiting for a non-blocking connection to complete.
908 failed -- when a non-blocking connection has failed.
909 nil -- if arg is a process name and no such process exists.
910 PROCESS may be a process, a buffer, the name of a process, or
911 nil, indicating the current buffer's process. */)
912 (register Lisp_Object process)
914 register struct Lisp_Process *p;
915 register Lisp_Object status;
917 if (STRINGP (process))
918 process = Fget_process (process);
919 else
920 process = get_process (process);
922 if (NILP (process))
923 return process;
925 p = XPROCESS (process);
926 if (p->raw_status_new)
927 update_status (p);
928 status = p->status;
929 if (CONSP (status))
930 status = XCAR (status);
931 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
933 if (EQ (status, Qexit))
934 status = Qclosed;
935 else if (EQ (p->command, Qt))
936 status = Qstop;
937 else if (EQ (status, Qrun))
938 status = Qopen;
940 return status;
943 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
944 1, 1, 0,
945 doc: /* Return the exit status of PROCESS or the signal number that killed it.
946 If PROCESS has not yet exited or died, return 0. */)
947 (register Lisp_Object process)
949 CHECK_PROCESS (process);
950 if (XPROCESS (process)->raw_status_new)
951 update_status (XPROCESS (process));
952 if (CONSP (XPROCESS (process)->status))
953 return XCAR (XCDR (XPROCESS (process)->status));
954 return make_number (0);
957 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
958 doc: /* Return the process id of PROCESS.
959 This is the pid of the external process which PROCESS uses or talks to.
960 For a network connection, this value is nil. */)
961 (register Lisp_Object process)
963 pid_t pid;
965 CHECK_PROCESS (process);
966 pid = XPROCESS (process)->pid;
967 return (pid ? make_fixnum_or_float (pid) : Qnil);
970 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
971 doc: /* Return the name of PROCESS, as a string.
972 This is the name of the program invoked in PROCESS,
973 possibly modified to make it unique among process names. */)
974 (register Lisp_Object process)
976 CHECK_PROCESS (process);
977 return XPROCESS (process)->name;
980 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
981 doc: /* Return the command that was executed to start PROCESS.
982 This is a list of strings, the first string being the program executed
983 and the rest of the strings being the arguments given to it.
984 For a network or serial process, this is nil (process is running) or t
985 (process is stopped). */)
986 (register Lisp_Object process)
988 CHECK_PROCESS (process);
989 return XPROCESS (process)->command;
992 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
993 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
994 This is the terminal that the process itself reads and writes on,
995 not the name of the pty that Emacs uses to talk with that terminal. */)
996 (register Lisp_Object process)
998 CHECK_PROCESS (process);
999 return XPROCESS (process)->tty_name;
1002 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1003 2, 2, 0,
1004 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1005 Return BUFFER. */)
1006 (register Lisp_Object process, Lisp_Object buffer)
1008 struct Lisp_Process *p;
1010 CHECK_PROCESS (process);
1011 if (!NILP (buffer))
1012 CHECK_BUFFER (buffer);
1013 p = XPROCESS (process);
1014 pset_buffer (p, buffer);
1015 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1016 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1017 setup_process_coding_systems (process);
1018 return buffer;
1021 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1022 1, 1, 0,
1023 doc: /* Return the buffer PROCESS is associated with.
1024 The default process filter inserts output from PROCESS into this buffer. */)
1025 (register Lisp_Object process)
1027 CHECK_PROCESS (process);
1028 return XPROCESS (process)->buffer;
1031 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1032 1, 1, 0,
1033 doc: /* Return the marker for the end of the last output from PROCESS. */)
1034 (register Lisp_Object process)
1036 CHECK_PROCESS (process);
1037 return XPROCESS (process)->mark;
1040 static void
1041 set_process_filter_masks (struct Lisp_Process *p)
1043 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1045 FD_CLR (p->infd, &input_wait_mask);
1046 FD_CLR (p->infd, &non_keyboard_wait_mask);
1048 else if (EQ (p->filter, Qt)
1049 /* Network or serial process not stopped: */
1050 && !EQ (p->command, Qt))
1052 FD_SET (p->infd, &input_wait_mask);
1053 FD_SET (p->infd, &non_keyboard_wait_mask);
1057 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1058 2, 2, 0,
1059 doc: /* Give PROCESS the filter function FILTER; nil means default.
1060 A value of t means stop accepting output from the process.
1062 When a process has a non-default filter, its buffer is not used for output.
1063 Instead, each time it does output, the entire string of output is
1064 passed to the filter.
1066 The filter gets two arguments: the process and the string of output.
1067 The string argument is normally a multibyte string, except:
1068 - if the process's input coding system is no-conversion or raw-text,
1069 it is a unibyte string (the non-converted input), or else
1070 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1071 string (the result of converting the decoded input multibyte
1072 string to unibyte with `string-make-unibyte'). */)
1073 (Lisp_Object process, Lisp_Object filter)
1075 CHECK_PROCESS (process);
1076 struct Lisp_Process *p = XPROCESS (process);
1078 /* Don't signal an error if the process's input file descriptor
1079 is closed. This could make debugging Lisp more difficult,
1080 for example when doing something like
1082 (setq process (start-process ...))
1083 (debug)
1084 (set-process-filter process ...) */
1086 if (NILP (filter))
1087 filter = Qinternal_default_process_filter;
1089 pset_filter (p, filter);
1091 if (p->infd >= 0)
1092 set_process_filter_masks (p);
1094 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1095 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1096 setup_process_coding_systems (process);
1097 return filter;
1100 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1101 1, 1, 0,
1102 doc: /* Return the filter function of PROCESS.
1103 See `set-process-filter' for more info on filter functions. */)
1104 (register Lisp_Object process)
1106 CHECK_PROCESS (process);
1107 return XPROCESS (process)->filter;
1110 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1111 2, 2, 0,
1112 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1113 The sentinel is called as a function when the process changes state.
1114 It gets two arguments: the process, and a string describing the change. */)
1115 (register Lisp_Object process, Lisp_Object sentinel)
1117 struct Lisp_Process *p;
1119 CHECK_PROCESS (process);
1120 p = XPROCESS (process);
1122 if (NILP (sentinel))
1123 sentinel = Qinternal_default_process_sentinel;
1125 pset_sentinel (p, sentinel);
1126 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1127 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1128 return sentinel;
1131 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1132 1, 1, 0,
1133 doc: /* Return the sentinel of PROCESS.
1134 See `set-process-sentinel' for more info on sentinels. */)
1135 (register Lisp_Object process)
1137 CHECK_PROCESS (process);
1138 return XPROCESS (process)->sentinel;
1141 DEFUN ("set-process-window-size", Fset_process_window_size,
1142 Sset_process_window_size, 3, 3, 0,
1143 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1144 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1146 CHECK_PROCESS (process);
1148 /* All known platforms store window sizes as 'unsigned short'. */
1149 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1150 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1152 if (NETCONN_P (process)
1153 || XPROCESS (process)->infd < 0
1154 || (set_window_size (XPROCESS (process)->infd,
1155 XINT (height), XINT (width))
1156 < 0))
1157 return Qnil;
1158 else
1159 return Qt;
1162 DEFUN ("set-process-inherit-coding-system-flag",
1163 Fset_process_inherit_coding_system_flag,
1164 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1165 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1166 If the second argument FLAG is non-nil, then the variable
1167 `buffer-file-coding-system' of the buffer associated with PROCESS
1168 will be bound to the value of the coding system used to decode
1169 the process output.
1171 This is useful when the coding system specified for the process buffer
1172 leaves either the character code conversion or the end-of-line conversion
1173 unspecified, or if the coding system used to decode the process output
1174 is more appropriate for saving the process buffer.
1176 Binding the variable `inherit-process-coding-system' to non-nil before
1177 starting the process is an alternative way of setting the inherit flag
1178 for the process which will run.
1180 This function returns FLAG. */)
1181 (register Lisp_Object process, Lisp_Object flag)
1183 CHECK_PROCESS (process);
1184 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1185 return flag;
1188 DEFUN ("set-process-query-on-exit-flag",
1189 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1190 2, 2, 0,
1191 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1192 If the second argument FLAG is non-nil, Emacs will query the user before
1193 exiting or killing a buffer if PROCESS is running. This function
1194 returns FLAG. */)
1195 (register Lisp_Object process, Lisp_Object flag)
1197 CHECK_PROCESS (process);
1198 XPROCESS (process)->kill_without_query = NILP (flag);
1199 return flag;
1202 DEFUN ("process-query-on-exit-flag",
1203 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1204 1, 1, 0,
1205 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1206 (register Lisp_Object process)
1208 CHECK_PROCESS (process);
1209 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1212 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1213 1, 2, 0,
1214 doc: /* Return the contact info of PROCESS; t for a real child.
1215 For a network or serial connection, the value depends on the optional
1216 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1217 SERVICE) for a network connection or (PORT SPEED) for a serial
1218 connection. If KEY is t, the complete contact information for the
1219 connection is returned, else the specific value for the keyword KEY is
1220 returned. See `make-network-process' or `make-serial-process' for a
1221 list of keywords.
1222 If PROCESS is a non-blocking network process that hasn't been fully
1223 set up yet, this function will block until socket setup has completed. */)
1224 (Lisp_Object process, Lisp_Object key)
1226 Lisp_Object contact;
1228 CHECK_PROCESS (process);
1229 contact = XPROCESS (process)->childp;
1231 #ifdef DATAGRAM_SOCKETS
1233 if (NETCONN_P (process))
1234 wait_for_socket_fds (process, "process-contact");
1236 if (DATAGRAM_CONN_P (process)
1237 && (EQ (key, Qt) || EQ (key, QCremote)))
1238 contact = Fplist_put (contact, QCremote,
1239 Fprocess_datagram_address (process));
1240 #endif
1242 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1243 || EQ (key, Qt))
1244 return contact;
1245 if (NILP (key) && NETCONN_P (process))
1246 return list2 (Fplist_get (contact, QChost),
1247 Fplist_get (contact, QCservice));
1248 if (NILP (key) && SERIALCONN_P (process))
1249 return list2 (Fplist_get (contact, QCport),
1250 Fplist_get (contact, QCspeed));
1251 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1252 if the pipe process is useful for purposes other than receiving
1253 stderr. */
1254 if (NILP (key) && PIPECONN_P (process))
1255 return Qt;
1256 return Fplist_get (contact, key);
1259 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1260 1, 1, 0,
1261 doc: /* Return the plist of PROCESS. */)
1262 (register Lisp_Object process)
1264 CHECK_PROCESS (process);
1265 return XPROCESS (process)->plist;
1268 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1269 2, 2, 0,
1270 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1271 (Lisp_Object process, Lisp_Object plist)
1273 CHECK_PROCESS (process);
1274 CHECK_LIST (plist);
1276 pset_plist (XPROCESS (process), plist);
1277 return plist;
1280 #if 0 /* Turned off because we don't currently record this info
1281 in the process. Perhaps add it. */
1282 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1283 doc: /* Return the connection type of PROCESS.
1284 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1285 a socket connection. */)
1286 (Lisp_Object process)
1288 return XPROCESS (process)->type;
1290 #endif
1292 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1293 doc: /* Return the connection type of PROCESS.
1294 The value is either the symbol `real', `network', or `serial'.
1295 PROCESS may be a process, a buffer, the name of a process or buffer, or
1296 nil, indicating the current buffer's process. */)
1297 (Lisp_Object process)
1299 Lisp_Object proc;
1300 proc = get_process (process);
1301 return XPROCESS (proc)->type;
1304 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1305 1, 2, 0,
1306 doc: /* Convert network ADDRESS from internal format to a string.
1307 A 4 or 5 element vector represents an IPv4 address (with port number).
1308 An 8 or 9 element vector represents an IPv6 address (with port number).
1309 If optional second argument OMIT-PORT is non-nil, don't include a port
1310 number in the string, even when present in ADDRESS.
1311 Return nil if format of ADDRESS is invalid. */)
1312 (Lisp_Object address, Lisp_Object omit_port)
1314 if (NILP (address))
1315 return Qnil;
1317 if (STRINGP (address)) /* AF_LOCAL */
1318 return address;
1320 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1322 register struct Lisp_Vector *p = XVECTOR (address);
1323 ptrdiff_t size = p->header.size;
1324 Lisp_Object args[10];
1325 int nargs, i;
1326 char const *format;
1328 if (size == 4 || (size == 5 && !NILP (omit_port)))
1330 format = "%d.%d.%d.%d";
1331 nargs = 4;
1333 else if (size == 5)
1335 format = "%d.%d.%d.%d:%d";
1336 nargs = 5;
1338 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1340 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1341 nargs = 8;
1343 else if (size == 9)
1345 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1346 nargs = 9;
1348 else
1349 return Qnil;
1351 AUTO_STRING (format_obj, format);
1352 args[0] = format_obj;
1354 for (i = 0; i < nargs; i++)
1356 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1357 return Qnil;
1359 if (nargs <= 5 /* IPv4 */
1360 && i < 4 /* host, not port */
1361 && XINT (p->contents[i]) > 255)
1362 return Qnil;
1364 args[i + 1] = p->contents[i];
1367 return Fformat (nargs + 1, args);
1370 if (CONSP (address))
1372 AUTO_STRING (format, "<Family %d>");
1373 return CALLN (Fformat, format, Fcar (address));
1376 return Qnil;
1379 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1380 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1381 (void)
1383 return Fmapcar (Qcdr, Vprocess_alist);
1386 /* Starting asynchronous inferior processes. */
1388 static void start_process_unwind (Lisp_Object proc);
1390 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1391 doc: /* Start a program in a subprocess. Return the process object for it.
1393 This is similar to `start-process', but arguments are specified as
1394 keyword/argument pairs. The following arguments are defined:
1396 :name NAME -- NAME is name for process. It is modified if necessary
1397 to make it unique.
1399 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1400 with the process. Process output goes at end of that buffer, unless
1401 you specify an output stream or filter function to handle the output.
1402 BUFFER may be also nil, meaning that this process is not associated
1403 with any buffer.
1405 :command COMMAND -- COMMAND is a list starting with the program file
1406 name, followed by strings to give to the program as arguments.
1408 :coding CODING -- If CODING is a symbol, it specifies the coding
1409 system used for both reading and writing for this process. If CODING
1410 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1411 ENCODING is used for writing.
1413 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1414 the process is running. If BOOL is not given, query before exiting.
1416 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1417 In the stopped state, a process does not accept incoming data, but you
1418 can send outgoing data. The stopped state is cleared by
1419 `continue-process' and set by `stop-process'.
1421 :connection-type TYPE -- TYPE is control type of device used to
1422 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1423 to use a pty, or nil to use the default specified through
1424 `process-connection-type'.
1426 :filter FILTER -- Install FILTER as the process filter.
1428 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1430 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1431 to the standard error of subprocess. Specifying this implies
1432 `:connection-type' is set to `pipe'.
1434 usage: (make-process &rest ARGS) */)
1435 (ptrdiff_t nargs, Lisp_Object *args)
1437 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1438 Lisp_Object xstderr, stderrproc;
1439 ptrdiff_t count = SPECPDL_INDEX ();
1440 USE_SAFE_ALLOCA;
1442 if (nargs == 0)
1443 return Qnil;
1445 /* Save arguments for process-contact and clone-process. */
1446 contact = Flist (nargs, args);
1448 buffer = Fplist_get (contact, QCbuffer);
1449 if (!NILP (buffer))
1450 buffer = Fget_buffer_create (buffer);
1452 /* Make sure that the child will be able to chdir to the current
1453 buffer's current directory, or its unhandled equivalent. We
1454 can't just have the child check for an error when it does the
1455 chdir, since it's in a vfork. */
1456 current_dir = encode_current_directory ();
1458 name = Fplist_get (contact, QCname);
1459 CHECK_STRING (name);
1461 command = Fplist_get (contact, QCcommand);
1462 if (CONSP (command))
1463 program = XCAR (command);
1464 else
1465 program = Qnil;
1467 if (!NILP (program))
1468 CHECK_STRING (program);
1470 stderrproc = Qnil;
1471 xstderr = Fplist_get (contact, QCstderr);
1472 if (PROCESSP (xstderr))
1474 if (!PIPECONN_P (xstderr))
1475 error ("Process is not a pipe process");
1476 stderrproc = xstderr;
1478 else if (!NILP (xstderr))
1480 CHECK_STRING (program);
1481 stderrproc = CALLN (Fmake_pipe_process,
1482 QCname,
1483 concat2 (name, build_string (" stderr")),
1484 QCbuffer,
1485 Fget_buffer_create (xstderr));
1488 proc = make_process (name);
1489 /* If an error occurs and we can't start the process, we want to
1490 remove it from the process list. This means that each error
1491 check in create_process doesn't need to call remove_process
1492 itself; it's all taken care of here. */
1493 record_unwind_protect (start_process_unwind, proc);
1495 pset_childp (XPROCESS (proc), Qt);
1496 pset_plist (XPROCESS (proc), Qnil);
1497 pset_type (XPROCESS (proc), Qreal);
1498 pset_buffer (XPROCESS (proc), buffer);
1499 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1500 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1501 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1503 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1504 XPROCESS (proc)->kill_without_query = 1;
1505 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1506 pset_command (XPROCESS (proc), Qt);
1508 tem = Fplist_get (contact, QCconnection_type);
1509 if (EQ (tem, Qpty))
1510 XPROCESS (proc)->pty_flag = true;
1511 else if (EQ (tem, Qpipe))
1512 XPROCESS (proc)->pty_flag = false;
1513 else if (NILP (tem))
1514 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1515 else
1516 report_file_error ("Unknown connection type", tem);
1518 if (!NILP (stderrproc))
1520 pset_stderrproc (XPROCESS (proc), stderrproc);
1522 XPROCESS (proc)->pty_flag = false;
1525 #ifdef HAVE_GNUTLS
1526 /* AKA GNUTLS_INITSTAGE(proc). */
1527 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1528 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1529 #endif
1531 XPROCESS (proc)->adaptive_read_buffering
1532 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1533 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1535 /* Make the process marker point into the process buffer (if any). */
1536 if (BUFFERP (buffer))
1537 set_marker_both (XPROCESS (proc)->mark, buffer,
1538 BUF_ZV (XBUFFER (buffer)),
1539 BUF_ZV_BYTE (XBUFFER (buffer)));
1542 /* Decide coding systems for communicating with the process. Here
1543 we don't setup the structure coding_system nor pay attention to
1544 unibyte mode. They are done in create_process. */
1546 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1547 Lisp_Object coding_systems = Qt;
1548 Lisp_Object val, *args2;
1550 tem = Fplist_get (contact, QCcoding);
1551 if (!NILP (tem))
1553 val = tem;
1554 if (CONSP (val))
1555 val = XCAR (val);
1557 else
1558 val = Vcoding_system_for_read;
1559 if (NILP (val))
1561 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1562 Lisp_Object tem2;
1563 SAFE_ALLOCA_LISP (args2, nargs2);
1564 ptrdiff_t i = 0;
1565 args2[i++] = Qstart_process;
1566 args2[i++] = name;
1567 args2[i++] = buffer;
1568 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1569 args2[i++] = XCAR (tem2);
1570 if (!NILP (program))
1571 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1572 if (CONSP (coding_systems))
1573 val = XCAR (coding_systems);
1574 else if (CONSP (Vdefault_process_coding_system))
1575 val = XCAR (Vdefault_process_coding_system);
1577 pset_decode_coding_system (XPROCESS (proc), val);
1579 if (!NILP (tem))
1581 val = tem;
1582 if (CONSP (val))
1583 val = XCDR (val);
1585 else
1586 val = Vcoding_system_for_write;
1587 if (NILP (val))
1589 if (EQ (coding_systems, Qt))
1591 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1592 Lisp_Object tem2;
1593 SAFE_ALLOCA_LISP (args2, nargs2);
1594 ptrdiff_t i = 0;
1595 args2[i++] = Qstart_process;
1596 args2[i++] = name;
1597 args2[i++] = buffer;
1598 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1599 args2[i++] = XCAR (tem2);
1600 if (!NILP (program))
1601 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1603 if (CONSP (coding_systems))
1604 val = XCDR (coding_systems);
1605 else if (CONSP (Vdefault_process_coding_system))
1606 val = XCDR (Vdefault_process_coding_system);
1608 pset_encode_coding_system (XPROCESS (proc), val);
1609 /* Note: At this moment, the above coding system may leave
1610 text-conversion or eol-conversion unspecified. They will be
1611 decided after we read output from the process and decode it by
1612 some coding system, or just before we actually send a text to
1613 the process. */
1617 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1618 XPROCESS (proc)->decoding_carryover = 0;
1619 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1621 XPROCESS (proc)->inherit_coding_system_flag
1622 = !(NILP (buffer) || !inherit_process_coding_system);
1624 if (!NILP (program))
1626 Lisp_Object program_args = XCDR (command);
1628 /* If program file name is not absolute, search our path for it.
1629 Put the name we will really use in TEM. */
1630 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1631 && !(SCHARS (program) > 1
1632 && IS_DEVICE_SEP (SREF (program, 1))))
1634 tem = Qnil;
1635 openp (Vexec_path, program, Vexec_suffixes, &tem,
1636 make_number (X_OK), false);
1637 if (NILP (tem))
1638 report_file_error ("Searching for program", program);
1639 tem = Fexpand_file_name (tem, Qnil);
1641 else
1643 if (!NILP (Ffile_directory_p (program)))
1644 error ("Specified program for new process is a directory");
1645 tem = program;
1648 /* Remove "/:" from TEM. */
1649 tem = remove_slash_colon (tem);
1651 Lisp_Object arg_encoding = Qnil;
1653 /* Encode the file name and put it in NEW_ARGV.
1654 That's where the child will use it to execute the program. */
1655 tem = list1 (ENCODE_FILE (tem));
1656 ptrdiff_t new_argc = 1;
1658 /* Here we encode arguments by the coding system used for sending
1659 data to the process. We don't support using different coding
1660 systems for encoding arguments and for encoding data sent to the
1661 process. */
1663 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1665 Lisp_Object arg = XCAR (tem2);
1666 CHECK_STRING (arg);
1667 if (STRING_MULTIBYTE (arg))
1669 if (NILP (arg_encoding))
1670 arg_encoding = (complement_process_encoding_system
1671 (XPROCESS (proc)->encode_coding_system));
1672 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1674 tem = Fcons (arg, tem);
1675 new_argc++;
1678 /* Now that everything is encoded we can collect the strings into
1679 NEW_ARGV. */
1680 char **new_argv;
1681 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1682 new_argv[new_argc] = 0;
1684 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1686 new_argv[i] = SSDATA (XCAR (tem));
1687 tem = XCDR (tem);
1690 create_process (proc, new_argv, current_dir);
1692 else
1693 create_pty (proc);
1695 SAFE_FREE ();
1696 return unbind_to (count, proc);
1699 /* This function is the unwind_protect form for Fstart_process. If
1700 PROC doesn't have its pid set, then we know someone has signaled
1701 an error and the process wasn't started successfully, so we should
1702 remove it from the process list. */
1703 static void
1704 start_process_unwind (Lisp_Object proc)
1706 if (!PROCESSP (proc))
1707 emacs_abort ();
1709 /* Was PROC started successfully?
1710 -2 is used for a pty with no process, eg for gdb. */
1711 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1712 remove_process (proc);
1715 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1717 static void
1718 close_process_fd (int *fd_addr)
1720 int fd = *fd_addr;
1721 if (0 <= fd)
1723 *fd_addr = -1;
1724 emacs_close (fd);
1728 /* Indexes of file descriptors in open_fds. */
1729 enum
1731 /* The pipe from Emacs to its subprocess. */
1732 SUBPROCESS_STDIN,
1733 WRITE_TO_SUBPROCESS,
1735 /* The main pipe from the subprocess to Emacs. */
1736 READ_FROM_SUBPROCESS,
1737 SUBPROCESS_STDOUT,
1739 /* The pipe from the subprocess to Emacs that is closed when the
1740 subprocess execs. */
1741 READ_FROM_EXEC_MONITOR,
1742 EXEC_MONITOR_OUTPUT
1745 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1747 static void
1748 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1750 struct Lisp_Process *p = XPROCESS (process);
1751 int inchannel, outchannel;
1752 pid_t pid;
1753 int vfork_errno;
1754 int forkin, forkout, forkerr = -1;
1755 bool pty_flag = 0;
1756 char pty_name[PTY_NAME_SIZE];
1757 Lisp_Object lisp_pty_name = Qnil;
1758 sigset_t oldset;
1760 inchannel = outchannel = -1;
1762 if (p->pty_flag)
1763 outchannel = inchannel = allocate_pty (pty_name);
1765 if (inchannel >= 0)
1767 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1768 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1769 /* On most USG systems it does not work to open the pty's tty here,
1770 then close it and reopen it in the child. */
1771 /* Don't let this terminal become our controlling terminal
1772 (in case we don't have one). */
1773 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1774 if (forkin < 0)
1775 report_file_error ("Opening pty", Qnil);
1776 p->open_fd[SUBPROCESS_STDIN] = forkin;
1777 #else
1778 forkin = forkout = -1;
1779 #endif /* not USG, or USG_SUBTTY_WORKS */
1780 pty_flag = 1;
1781 lisp_pty_name = build_string (pty_name);
1783 else
1785 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1786 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1787 report_file_error ("Creating pipe", Qnil);
1788 forkin = p->open_fd[SUBPROCESS_STDIN];
1789 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1790 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1791 forkout = p->open_fd[SUBPROCESS_STDOUT];
1793 if (!NILP (p->stderrproc))
1795 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1797 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1799 /* Close unnecessary file descriptors. */
1800 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1801 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1805 #ifndef WINDOWSNT
1806 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1807 report_file_error ("Creating pipe", Qnil);
1808 #endif
1810 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1811 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1813 /* Record this as an active process, with its channels. */
1814 chan_process[inchannel] = process;
1815 p->infd = inchannel;
1816 p->outfd = outchannel;
1818 /* Previously we recorded the tty descriptor used in the subprocess.
1819 It was only used for getting the foreground tty process, so now
1820 we just reopen the device (see emacs_get_tty_pgrp) as this is
1821 more portable (see USG_SUBTTY_WORKS above). */
1823 p->pty_flag = pty_flag;
1824 pset_status (p, Qrun);
1826 if (!EQ (p->command, Qt))
1828 FD_SET (inchannel, &input_wait_mask);
1829 FD_SET (inchannel, &non_keyboard_wait_mask);
1832 if (inchannel > max_process_desc)
1833 max_process_desc = inchannel;
1835 /* This may signal an error. */
1836 setup_process_coding_systems (process);
1838 block_input ();
1839 block_child_signal (&oldset);
1841 #ifndef WINDOWSNT
1842 /* vfork, and prevent local vars from being clobbered by the vfork. */
1843 Lisp_Object volatile current_dir_volatile = current_dir;
1844 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1845 char **volatile new_argv_volatile = new_argv;
1846 int volatile forkin_volatile = forkin;
1847 int volatile forkout_volatile = forkout;
1848 int volatile forkerr_volatile = forkerr;
1849 struct Lisp_Process *p_volatile = p;
1851 pid = vfork ();
1853 current_dir = current_dir_volatile;
1854 lisp_pty_name = lisp_pty_name_volatile;
1855 new_argv = new_argv_volatile;
1856 forkin = forkin_volatile;
1857 forkout = forkout_volatile;
1858 forkerr = forkerr_volatile;
1859 p = p_volatile;
1861 pty_flag = p->pty_flag;
1863 if (pid == 0)
1864 #endif /* not WINDOWSNT */
1866 /* Make the pty be the controlling terminal of the process. */
1867 #ifdef HAVE_PTYS
1868 /* First, disconnect its current controlling terminal. */
1869 /* We tried doing setsid only if pty_flag, but it caused
1870 process_set_signal to fail on SGI when using a pipe. */
1871 setsid ();
1872 /* Make the pty's terminal the controlling terminal. */
1873 if (pty_flag && forkin >= 0)
1875 #ifdef TIOCSCTTY
1876 /* We ignore the return value
1877 because faith@cs.unc.edu says that is necessary on Linux. */
1878 ioctl (forkin, TIOCSCTTY, 0);
1879 #endif
1881 #if defined (LDISC1)
1882 if (pty_flag && forkin >= 0)
1884 struct termios t;
1885 tcgetattr (forkin, &t);
1886 t.c_lflag = LDISC1;
1887 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1888 emacs_perror ("create_process/tcsetattr LDISC1");
1890 #else
1891 #if defined (NTTYDISC) && defined (TIOCSETD)
1892 if (pty_flag && forkin >= 0)
1894 /* Use new line discipline. */
1895 int ldisc = NTTYDISC;
1896 ioctl (forkin, TIOCSETD, &ldisc);
1898 #endif
1899 #endif
1900 #ifdef TIOCNOTTY
1901 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1902 can do TIOCSPGRP only to the process's controlling tty. */
1903 if (pty_flag)
1905 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1906 I can't test it since I don't have 4.3. */
1907 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1908 if (j >= 0)
1910 ioctl (j, TIOCNOTTY, 0);
1911 emacs_close (j);
1914 #endif /* TIOCNOTTY */
1916 #if !defined (DONT_REOPEN_PTY)
1917 /*** There is a suggestion that this ought to be a
1918 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1919 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1920 that system does seem to need this code, even though
1921 both TIOCSCTTY is defined. */
1922 /* Now close the pty (if we had it open) and reopen it.
1923 This makes the pty the controlling terminal of the subprocess. */
1924 if (pty_flag)
1927 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1928 would work? */
1929 if (forkin >= 0)
1930 emacs_close (forkin);
1931 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1933 if (forkin < 0)
1935 emacs_perror (SSDATA (lisp_pty_name));
1936 _exit (EXIT_CANCELED);
1940 #endif /* not DONT_REOPEN_PTY */
1942 #ifdef SETUP_SLAVE_PTY
1943 if (pty_flag)
1945 SETUP_SLAVE_PTY;
1947 #endif /* SETUP_SLAVE_PTY */
1948 #endif /* HAVE_PTYS */
1950 signal (SIGINT, SIG_DFL);
1951 signal (SIGQUIT, SIG_DFL);
1952 #ifdef SIGPROF
1953 signal (SIGPROF, SIG_DFL);
1954 #endif
1956 /* Emacs ignores SIGPIPE, but the child should not. */
1957 signal (SIGPIPE, SIG_DFL);
1959 /* Stop blocking SIGCHLD in the child. */
1960 unblock_child_signal (&oldset);
1962 if (pty_flag)
1963 child_setup_tty (forkout);
1965 if (forkerr < 0)
1966 forkerr = forkout;
1967 #ifdef WINDOWSNT
1968 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1969 #else /* not WINDOWSNT */
1970 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1971 #endif /* not WINDOWSNT */
1974 /* Back in the parent process. */
1976 vfork_errno = errno;
1977 p->pid = pid;
1978 if (pid >= 0)
1979 p->alive = 1;
1981 /* Stop blocking in the parent. */
1982 unblock_child_signal (&oldset);
1983 unblock_input ();
1985 if (pid < 0)
1986 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1987 else
1989 /* vfork succeeded. */
1991 /* Close the pipe ends that the child uses, or the child's pty. */
1992 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1993 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1995 #ifdef WINDOWSNT
1996 register_child (pid, inchannel);
1997 #endif /* WINDOWSNT */
1999 pset_tty_name (p, lisp_pty_name);
2001 #ifndef WINDOWSNT
2002 /* Wait for child_setup to complete in case that vfork is
2003 actually defined as fork. The descriptor
2004 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2005 of a pipe is closed at the child side either by close-on-exec
2006 on successful execve or the _exit call in child_setup. */
2008 char dummy;
2010 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2011 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2012 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2014 #endif
2015 if (!NILP (p->stderrproc))
2017 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2018 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2023 static void
2024 create_pty (Lisp_Object process)
2026 struct Lisp_Process *p = XPROCESS (process);
2027 char pty_name[PTY_NAME_SIZE];
2028 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2030 if (pty_fd >= 0)
2032 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2033 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2034 /* On most USG systems it does not work to open the pty's tty here,
2035 then close it and reopen it in the child. */
2036 /* Don't let this terminal become our controlling terminal
2037 (in case we don't have one). */
2038 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2039 if (forkout < 0)
2040 report_file_error ("Opening pty", Qnil);
2041 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2042 #if defined (DONT_REOPEN_PTY)
2043 /* In the case that vfork is defined as fork, the parent process
2044 (Emacs) may send some data before the child process completes
2045 tty options setup. So we setup tty before forking. */
2046 child_setup_tty (forkout);
2047 #endif /* DONT_REOPEN_PTY */
2048 #endif /* not USG, or USG_SUBTTY_WORKS */
2050 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2052 /* Record this as an active process, with its channels.
2053 As a result, child_setup will close Emacs's side of the pipes. */
2054 chan_process[pty_fd] = process;
2055 p->infd = pty_fd;
2056 p->outfd = pty_fd;
2058 /* Previously we recorded the tty descriptor used in the subprocess.
2059 It was only used for getting the foreground tty process, so now
2060 we just reopen the device (see emacs_get_tty_pgrp) as this is
2061 more portable (see USG_SUBTTY_WORKS above). */
2063 p->pty_flag = 1;
2064 pset_status (p, Qrun);
2065 setup_process_coding_systems (process);
2067 FD_SET (pty_fd, &input_wait_mask);
2068 FD_SET (pty_fd, &non_keyboard_wait_mask);
2069 if (pty_fd > max_process_desc)
2070 max_process_desc = pty_fd;
2072 pset_tty_name (p, build_string (pty_name));
2075 p->pid = -2;
2078 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2079 0, MANY, 0,
2080 doc: /* Create and return a bidirectional pipe process.
2082 In Emacs, pipes are represented by process objects, so input and
2083 output work as for subprocesses, and `delete-process' closes a pipe.
2084 However, a pipe process has no process id, it cannot be signaled,
2085 and the status codes are different from normal processes.
2087 Arguments are specified as keyword/argument pairs. The following
2088 arguments are defined:
2090 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2092 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2093 with the process. Process output goes at the end of that buffer,
2094 unless you specify an output stream or filter function to handle the
2095 output. If BUFFER is not given, the value of NAME is used.
2097 :coding CODING -- If CODING is a symbol, it specifies the coding
2098 system used for both reading and writing for this process. If CODING
2099 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2100 ENCODING is used for writing.
2102 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2103 the process is running. If BOOL is not given, query before exiting.
2105 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2106 In the stopped state, a pipe process does not accept incoming data,
2107 but you can send outgoing data. The stopped state is cleared by
2108 `continue-process' and set by `stop-process'.
2110 :filter FILTER -- Install FILTER as the process filter.
2112 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2114 usage: (make-pipe-process &rest ARGS) */)
2115 (ptrdiff_t nargs, Lisp_Object *args)
2117 Lisp_Object proc, contact;
2118 struct Lisp_Process *p;
2119 Lisp_Object name, buffer;
2120 Lisp_Object tem;
2121 ptrdiff_t specpdl_count;
2122 int inchannel, outchannel;
2124 if (nargs == 0)
2125 return Qnil;
2127 contact = Flist (nargs, args);
2129 name = Fplist_get (contact, QCname);
2130 CHECK_STRING (name);
2131 proc = make_process (name);
2132 specpdl_count = SPECPDL_INDEX ();
2133 record_unwind_protect (remove_process, proc);
2134 p = XPROCESS (proc);
2136 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2137 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2138 report_file_error ("Creating pipe", Qnil);
2139 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2140 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2142 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2143 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2145 #ifdef WINDOWSNT
2146 register_aux_fd (inchannel);
2147 #endif
2149 /* Record this as an active process, with its channels. */
2150 chan_process[inchannel] = proc;
2151 p->infd = inchannel;
2152 p->outfd = outchannel;
2154 if (inchannel > max_process_desc)
2155 max_process_desc = inchannel;
2157 buffer = Fplist_get (contact, QCbuffer);
2158 if (NILP (buffer))
2159 buffer = name;
2160 buffer = Fget_buffer_create (buffer);
2161 pset_buffer (p, buffer);
2163 pset_childp (p, contact);
2164 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2165 pset_type (p, Qpipe);
2166 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2167 pset_filter (p, Fplist_get (contact, QCfilter));
2168 pset_log (p, Qnil);
2169 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2170 p->kill_without_query = 1;
2171 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2172 pset_command (p, Qt);
2173 eassert (! p->pty_flag);
2175 if (!EQ (p->command, Qt))
2177 FD_SET (inchannel, &input_wait_mask);
2178 FD_SET (inchannel, &non_keyboard_wait_mask);
2180 p->adaptive_read_buffering
2181 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2182 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2184 /* Make the process marker point into the process buffer (if any). */
2185 if (BUFFERP (buffer))
2186 set_marker_both (p->mark, buffer,
2187 BUF_ZV (XBUFFER (buffer)),
2188 BUF_ZV_BYTE (XBUFFER (buffer)));
2191 /* Setup coding systems for communicating with the network stream. */
2193 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2194 Lisp_Object coding_systems = Qt;
2195 Lisp_Object val;
2197 tem = Fplist_get (contact, QCcoding);
2198 val = Qnil;
2199 if (!NILP (tem))
2201 val = tem;
2202 if (CONSP (val))
2203 val = XCAR (val);
2205 else if (!NILP (Vcoding_system_for_read))
2206 val = Vcoding_system_for_read;
2207 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2208 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2209 /* We dare not decode end-of-line format by setting VAL to
2210 Qraw_text, because the existing Emacs Lisp libraries
2211 assume that they receive bare code including a sequence of
2212 CR LF. */
2213 val = Qnil;
2214 else
2216 if (CONSP (coding_systems))
2217 val = XCAR (coding_systems);
2218 else if (CONSP (Vdefault_process_coding_system))
2219 val = XCAR (Vdefault_process_coding_system);
2220 else
2221 val = Qnil;
2223 pset_decode_coding_system (p, val);
2225 if (!NILP (tem))
2227 val = tem;
2228 if (CONSP (val))
2229 val = XCDR (val);
2231 else if (!NILP (Vcoding_system_for_write))
2232 val = Vcoding_system_for_write;
2233 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2234 val = Qnil;
2235 else
2237 if (CONSP (coding_systems))
2238 val = XCDR (coding_systems);
2239 else if (CONSP (Vdefault_process_coding_system))
2240 val = XCDR (Vdefault_process_coding_system);
2241 else
2242 val = Qnil;
2244 pset_encode_coding_system (p, val);
2246 /* This may signal an error. */
2247 setup_process_coding_systems (proc);
2249 specpdl_ptr = specpdl + specpdl_count;
2251 return proc;
2255 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2256 The address family of sa is not included in the result. */
2258 Lisp_Object
2259 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2261 Lisp_Object address;
2262 ptrdiff_t i;
2263 unsigned char *cp;
2264 struct Lisp_Vector *p;
2266 /* Workaround for a bug in getsockname on BSD: Names bound to
2267 sockets in the UNIX domain are inaccessible; getsockname returns
2268 a zero length name. */
2269 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2270 return empty_unibyte_string;
2272 switch (sa->sa_family)
2274 case AF_INET:
2276 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2277 len = sizeof (sin->sin_addr) + 1;
2278 address = Fmake_vector (make_number (len), Qnil);
2279 p = XVECTOR (address);
2280 p->contents[--len] = make_number (ntohs (sin->sin_port));
2281 cp = (unsigned char *) &sin->sin_addr;
2282 break;
2284 #ifdef AF_INET6
2285 case AF_INET6:
2287 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2288 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2289 len = sizeof (sin6->sin6_addr) / 2 + 1;
2290 address = Fmake_vector (make_number (len), Qnil);
2291 p = XVECTOR (address);
2292 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2293 for (i = 0; i < len; i++)
2294 p->contents[i] = make_number (ntohs (ip6[i]));
2295 return address;
2297 #endif
2298 #ifdef HAVE_LOCAL_SOCKETS
2299 case AF_LOCAL:
2301 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2302 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2303 /* If the first byte is NUL, the name is a Linux abstract
2304 socket name, and the name can contain embedded NULs. If
2305 it's not, we have a NUL-terminated string. Be careful not
2306 to walk past the end of the object looking for the name
2307 terminator, however. */
2308 if (name_length > 0 && sockun->sun_path[0] != '\0')
2310 const char *terminator
2311 = memchr (sockun->sun_path, '\0', name_length);
2313 if (terminator)
2314 name_length = terminator - (const char *) sockun->sun_path;
2317 return make_unibyte_string (sockun->sun_path, name_length);
2319 #endif
2320 default:
2321 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2322 address = Fcons (make_number (sa->sa_family),
2323 Fmake_vector (make_number (len), Qnil));
2324 p = XVECTOR (XCDR (address));
2325 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2326 break;
2329 i = 0;
2330 while (i < len)
2331 p->contents[i++] = make_number (*cp++);
2333 return address;
2337 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2339 static ptrdiff_t
2340 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2342 struct Lisp_Vector *p;
2344 if (VECTORP (address))
2346 p = XVECTOR (address);
2347 if (p->header.size == 5)
2349 *familyp = AF_INET;
2350 return sizeof (struct sockaddr_in);
2352 #ifdef AF_INET6
2353 else if (p->header.size == 9)
2355 *familyp = AF_INET6;
2356 return sizeof (struct sockaddr_in6);
2358 #endif
2360 #ifdef HAVE_LOCAL_SOCKETS
2361 else if (STRINGP (address))
2363 *familyp = AF_LOCAL;
2364 return sizeof (struct sockaddr_un);
2366 #endif
2367 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2368 && VECTORP (XCDR (address)))
2370 struct sockaddr *sa;
2371 p = XVECTOR (XCDR (address));
2372 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2373 return 0;
2374 *familyp = XINT (XCAR (address));
2375 return p->header.size + sizeof (sa->sa_family);
2377 return 0;
2380 /* Convert an address object (vector or string) to an internal sockaddr.
2382 The address format has been basically validated by
2383 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2384 it could have come from user data. So if FAMILY is not valid,
2385 we return after zeroing *SA. */
2387 static void
2388 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2390 register struct Lisp_Vector *p;
2391 register unsigned char *cp = NULL;
2392 register int i;
2393 EMACS_INT hostport;
2395 memset (sa, 0, len);
2397 if (VECTORP (address))
2399 p = XVECTOR (address);
2400 if (family == AF_INET)
2402 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2403 len = sizeof (sin->sin_addr) + 1;
2404 hostport = XINT (p->contents[--len]);
2405 sin->sin_port = htons (hostport);
2406 cp = (unsigned char *)&sin->sin_addr;
2407 sa->sa_family = family;
2409 #ifdef AF_INET6
2410 else if (family == AF_INET6)
2412 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2413 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2414 len = sizeof (sin6->sin6_addr) / 2 + 1;
2415 hostport = XINT (p->contents[--len]);
2416 sin6->sin6_port = htons (hostport);
2417 for (i = 0; i < len; i++)
2418 if (INTEGERP (p->contents[i]))
2420 int j = XFASTINT (p->contents[i]) & 0xffff;
2421 ip6[i] = ntohs (j);
2423 sa->sa_family = family;
2424 return;
2426 #endif
2427 else
2428 return;
2430 else if (STRINGP (address))
2432 #ifdef HAVE_LOCAL_SOCKETS
2433 if (family == AF_LOCAL)
2435 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2436 cp = SDATA (address);
2437 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2438 sockun->sun_path[i] = *cp++;
2439 sa->sa_family = family;
2441 #endif
2442 return;
2444 else
2446 p = XVECTOR (XCDR (address));
2447 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2450 for (i = 0; i < len; i++)
2451 if (INTEGERP (p->contents[i]))
2452 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2455 #ifdef DATAGRAM_SOCKETS
2456 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2457 1, 1, 0,
2458 doc: /* Get the current datagram address associated with PROCESS.
2459 If PROCESS is a non-blocking network process that hasn't been fully
2460 set up yet, this function will block until socket setup has completed. */)
2461 (Lisp_Object process)
2463 int channel;
2465 CHECK_PROCESS (process);
2467 if (NETCONN_P (process))
2468 wait_for_socket_fds (process, "process-datagram-address");
2470 if (!DATAGRAM_CONN_P (process))
2471 return Qnil;
2473 channel = XPROCESS (process)->infd;
2474 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2475 datagram_address[channel].len);
2478 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2479 2, 2, 0,
2480 doc: /* Set the datagram address for PROCESS to ADDRESS.
2481 Return nil upon error setting address, ADDRESS otherwise.
2483 If PROCESS is a non-blocking network process that hasn't been fully
2484 set up yet, this function will block until socket setup has completed. */)
2485 (Lisp_Object process, Lisp_Object address)
2487 int channel;
2488 int family;
2489 ptrdiff_t len;
2491 CHECK_PROCESS (process);
2493 if (NETCONN_P (process))
2494 wait_for_socket_fds (process, "set-process-datagram-address");
2496 if (!DATAGRAM_CONN_P (process))
2497 return Qnil;
2499 channel = XPROCESS (process)->infd;
2501 len = get_lisp_to_sockaddr_size (address, &family);
2502 if (len == 0 || datagram_address[channel].len != len)
2503 return Qnil;
2504 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2505 return address;
2507 #endif
2510 static const struct socket_options {
2511 /* The name of this option. Should be lowercase version of option
2512 name without SO_ prefix. */
2513 const char *name;
2514 /* Option level SOL_... */
2515 int optlevel;
2516 /* Option number SO_... */
2517 int optnum;
2518 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2519 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2520 } socket_options[] =
2522 #ifdef SO_BINDTODEVICE
2523 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2524 #endif
2525 #ifdef SO_BROADCAST
2526 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2527 #endif
2528 #ifdef SO_DONTROUTE
2529 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2530 #endif
2531 #ifdef SO_KEEPALIVE
2532 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2533 #endif
2534 #ifdef SO_LINGER
2535 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2536 #endif
2537 #ifdef SO_OOBINLINE
2538 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2539 #endif
2540 #ifdef SO_PRIORITY
2541 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2542 #endif
2543 #ifdef SO_REUSEADDR
2544 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2545 #endif
2546 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2549 /* Set option OPT to value VAL on socket S.
2551 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2552 Signals an error if setting a known option fails.
2555 static int
2556 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2558 char *name;
2559 const struct socket_options *sopt;
2560 int ret = 0;
2562 CHECK_SYMBOL (opt);
2564 name = SSDATA (SYMBOL_NAME (opt));
2565 for (sopt = socket_options; sopt->name; sopt++)
2566 if (strcmp (name, sopt->name) == 0)
2567 break;
2569 switch (sopt->opttype)
2571 case SOPT_BOOL:
2573 int optval;
2574 optval = NILP (val) ? 0 : 1;
2575 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2576 &optval, sizeof (optval));
2577 break;
2580 case SOPT_INT:
2582 int optval;
2583 if (TYPE_RANGED_INTEGERP (int, val))
2584 optval = XINT (val);
2585 else
2586 error ("Bad option value for %s", name);
2587 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2588 &optval, sizeof (optval));
2589 break;
2592 #ifdef SO_BINDTODEVICE
2593 case SOPT_IFNAME:
2595 char devname[IFNAMSIZ + 1];
2597 /* This is broken, at least in the Linux 2.4 kernel.
2598 To unbind, the arg must be a zero integer, not the empty string.
2599 This should work on all systems. KFS. 2003-09-23. */
2600 memset (devname, 0, sizeof devname);
2601 if (STRINGP (val))
2603 char *arg = SSDATA (val);
2604 int len = min (strlen (arg), IFNAMSIZ);
2605 memcpy (devname, arg, len);
2607 else if (!NILP (val))
2608 error ("Bad option value for %s", name);
2609 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2610 devname, IFNAMSIZ);
2611 break;
2613 #endif
2615 #ifdef SO_LINGER
2616 case SOPT_LINGER:
2618 struct linger linger;
2620 linger.l_onoff = 1;
2621 linger.l_linger = 0;
2622 if (TYPE_RANGED_INTEGERP (int, val))
2623 linger.l_linger = XINT (val);
2624 else
2625 linger.l_onoff = NILP (val) ? 0 : 1;
2626 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2627 &linger, sizeof (linger));
2628 break;
2630 #endif
2632 default:
2633 return 0;
2636 if (ret < 0)
2638 int setsockopt_errno = errno;
2639 report_file_errno ("Cannot set network option", list2 (opt, val),
2640 setsockopt_errno);
2643 return (1 << sopt->optbit);
2647 DEFUN ("set-network-process-option",
2648 Fset_network_process_option, Sset_network_process_option,
2649 3, 4, 0,
2650 doc: /* For network process PROCESS set option OPTION to value VALUE.
2651 See `make-network-process' for a list of options and values.
2652 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2653 OPTION is not a supported option, return nil instead; otherwise return t.
2655 If PROCESS is a non-blocking network process that hasn't been fully
2656 set up yet, this function will block until socket setup has completed. */)
2657 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2659 int s;
2660 struct Lisp_Process *p;
2662 CHECK_PROCESS (process);
2663 p = XPROCESS (process);
2664 if (!NETCONN1_P (p))
2665 error ("Process is not a network process");
2667 wait_for_socket_fds (process, "set-network-process-option");
2669 s = p->infd;
2670 if (s < 0)
2671 error ("Process is not running");
2673 if (set_socket_option (s, option, value))
2675 pset_childp (p, Fplist_put (p->childp, option, value));
2676 return Qt;
2679 if (NILP (no_error))
2680 error ("Unknown or unsupported option");
2682 return Qnil;
2686 DEFUN ("serial-process-configure",
2687 Fserial_process_configure,
2688 Sserial_process_configure,
2689 0, MANY, 0,
2690 doc: /* Configure speed, bytesize, etc. of a serial process.
2692 Arguments are specified as keyword/argument pairs. Attributes that
2693 are not given are re-initialized from the process's current
2694 configuration (available via the function `process-contact') or set to
2695 reasonable default values. The following arguments are defined:
2697 :process PROCESS
2698 :name NAME
2699 :buffer BUFFER
2700 :port PORT
2701 -- Any of these arguments can be given to identify the process that is
2702 to be configured. If none of these arguments is given, the current
2703 buffer's process is used.
2705 :speed SPEED -- SPEED is the speed of the serial port in bits per
2706 second, also called baud rate. Any value can be given for SPEED, but
2707 most serial ports work only at a few defined values between 1200 and
2708 115200, with 9600 being the most common value. If SPEED is nil, the
2709 serial port is not configured any further, i.e., all other arguments
2710 are ignored. This may be useful for special serial ports such as
2711 Bluetooth-to-serial converters which can only be configured through AT
2712 commands. A value of nil for SPEED can be used only when passed
2713 through `make-serial-process' or `serial-term'.
2715 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2716 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2718 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2719 `odd' (use odd parity), or the symbol `even' (use even parity). If
2720 PARITY is not given, no parity is used.
2722 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2723 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2724 is not given or nil, 1 stopbit is used.
2726 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2727 flowcontrol to be used, which is either nil (don't use flowcontrol),
2728 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2729 (use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2730 flowcontrol is used.
2732 `serial-process-configure' is called by `make-serial-process' for the
2733 initial configuration of the serial port.
2735 Examples:
2737 (serial-process-configure :process "/dev/ttyS0" :speed 1200)
2739 (serial-process-configure
2740 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2742 (serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2744 usage: (serial-process-configure &rest ARGS) */)
2745 (ptrdiff_t nargs, Lisp_Object *args)
2747 struct Lisp_Process *p;
2748 Lisp_Object contact = Qnil;
2749 Lisp_Object proc = Qnil;
2751 contact = Flist (nargs, args);
2753 proc = Fplist_get (contact, QCprocess);
2754 if (NILP (proc))
2755 proc = Fplist_get (contact, QCname);
2756 if (NILP (proc))
2757 proc = Fplist_get (contact, QCbuffer);
2758 if (NILP (proc))
2759 proc = Fplist_get (contact, QCport);
2760 proc = get_process (proc);
2761 p = XPROCESS (proc);
2762 if (!EQ (p->type, Qserial))
2763 error ("Not a serial process");
2765 if (NILP (Fplist_get (p->childp, QCspeed)))
2766 return Qnil;
2768 serial_configure (p, contact);
2769 return Qnil;
2772 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2773 0, MANY, 0,
2774 doc: /* Create and return a serial port process.
2776 In Emacs, serial port connections are represented by process objects,
2777 so input and output work as for subprocesses, and `delete-process'
2778 closes a serial port connection. However, a serial process has no
2779 process id, it cannot be signaled, and the status codes are different
2780 from normal processes.
2782 `make-serial-process' creates a process and a buffer, on which you
2783 probably want to use `process-send-string'. Try \\[serial-term] for
2784 an interactive terminal. See below for examples.
2786 Arguments are specified as keyword/argument pairs. The following
2787 arguments are defined:
2789 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2790 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2791 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2792 the backslashes in strings).
2794 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2795 which this function calls.
2797 :name NAME -- NAME is the name of the process. If NAME is not given,
2798 the value of PORT is used.
2800 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2801 with the process. Process output goes at the end of that buffer,
2802 unless you specify an output stream or filter function to handle the
2803 output. If BUFFER is not given, the value of NAME is used.
2805 :coding CODING -- If CODING is a symbol, it specifies the coding
2806 system used for both reading and writing for this process. If CODING
2807 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2808 ENCODING is used for writing.
2810 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2811 the process is running. If BOOL is not given, query before exiting.
2813 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2814 In the stopped state, a serial process does not accept incoming data,
2815 but you can send outgoing data. The stopped state is cleared by
2816 `continue-process' and set by `stop-process'.
2818 :filter FILTER -- Install FILTER as the process filter.
2820 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2822 :plist PLIST -- Install PLIST as the initial plist of the process.
2824 :bytesize
2825 :parity
2826 :stopbits
2827 :flowcontrol
2828 -- This function calls `serial-process-configure' to handle these
2829 arguments.
2831 The original argument list, possibly modified by later configuration,
2832 is available via the function `process-contact'.
2834 Examples:
2836 (make-serial-process :port "/dev/ttyS0" :speed 9600)
2838 (make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2840 (make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2842 (make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2844 usage: (make-serial-process &rest ARGS) */)
2845 (ptrdiff_t nargs, Lisp_Object *args)
2847 int fd = -1;
2848 Lisp_Object proc, contact, port;
2849 struct Lisp_Process *p;
2850 Lisp_Object name, buffer;
2851 Lisp_Object tem, val;
2852 ptrdiff_t specpdl_count;
2854 if (nargs == 0)
2855 return Qnil;
2857 contact = Flist (nargs, args);
2859 port = Fplist_get (contact, QCport);
2860 if (NILP (port))
2861 error ("No port specified");
2862 CHECK_STRING (port);
2864 if (NILP (Fplist_member (contact, QCspeed)))
2865 error (":speed not specified");
2866 if (!NILP (Fplist_get (contact, QCspeed)))
2867 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2869 name = Fplist_get (contact, QCname);
2870 if (NILP (name))
2871 name = port;
2872 CHECK_STRING (name);
2873 proc = make_process (name);
2874 specpdl_count = SPECPDL_INDEX ();
2875 record_unwind_protect (remove_process, proc);
2876 p = XPROCESS (proc);
2878 fd = serial_open (port);
2879 p->open_fd[SUBPROCESS_STDIN] = fd;
2880 p->infd = fd;
2881 p->outfd = fd;
2882 if (fd > max_process_desc)
2883 max_process_desc = fd;
2884 chan_process[fd] = proc;
2886 buffer = Fplist_get (contact, QCbuffer);
2887 if (NILP (buffer))
2888 buffer = name;
2889 buffer = Fget_buffer_create (buffer);
2890 pset_buffer (p, buffer);
2892 pset_childp (p, contact);
2893 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2894 pset_type (p, Qserial);
2895 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2896 pset_filter (p, Fplist_get (contact, QCfilter));
2897 pset_log (p, Qnil);
2898 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2899 p->kill_without_query = 1;
2900 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2901 pset_command (p, Qt);
2902 eassert (! p->pty_flag);
2904 if (!EQ (p->command, Qt))
2906 FD_SET (fd, &input_wait_mask);
2907 FD_SET (fd, &non_keyboard_wait_mask);
2910 if (BUFFERP (buffer))
2912 set_marker_both (p->mark, buffer,
2913 BUF_ZV (XBUFFER (buffer)),
2914 BUF_ZV_BYTE (XBUFFER (buffer)));
2917 tem = Fplist_member (contact, QCcoding);
2918 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2919 tem = Qnil;
2921 val = Qnil;
2922 if (!NILP (tem))
2924 val = XCAR (XCDR (tem));
2925 if (CONSP (val))
2926 val = XCAR (val);
2928 else if (!NILP (Vcoding_system_for_read))
2929 val = Vcoding_system_for_read;
2930 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2931 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2932 val = Qnil;
2933 pset_decode_coding_system (p, val);
2935 val = Qnil;
2936 if (!NILP (tem))
2938 val = XCAR (XCDR (tem));
2939 if (CONSP (val))
2940 val = XCDR (val);
2942 else if (!NILP (Vcoding_system_for_write))
2943 val = Vcoding_system_for_write;
2944 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2945 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2946 val = Qnil;
2947 pset_encode_coding_system (p, val);
2949 setup_process_coding_systems (proc);
2950 pset_decoding_buf (p, empty_unibyte_string);
2951 p->decoding_carryover = 0;
2952 pset_encoding_buf (p, empty_unibyte_string);
2953 p->inherit_coding_system_flag
2954 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2956 Fserial_process_configure (nargs, args);
2958 specpdl_ptr = specpdl + specpdl_count;
2960 return proc;
2963 static void
2964 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
2965 Lisp_Object service, Lisp_Object name)
2967 Lisp_Object tem;
2968 struct Lisp_Process *p = XPROCESS (proc);
2969 Lisp_Object contact = p->childp;
2970 Lisp_Object coding_systems = Qt;
2971 Lisp_Object val;
2973 tem = Fplist_member (contact, QCcoding);
2974 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2975 tem = Qnil; /* No error message (too late!). */
2977 /* Setup coding systems for communicating with the network stream. */
2978 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2980 if (!NILP (tem))
2982 val = XCAR (XCDR (tem));
2983 if (CONSP (val))
2984 val = XCAR (val);
2986 else if (!NILP (Vcoding_system_for_read))
2987 val = Vcoding_system_for_read;
2988 else if ((!NILP (p->buffer)
2989 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
2990 || (NILP (p->buffer)
2991 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2992 /* We dare not decode end-of-line format by setting VAL to
2993 Qraw_text, because the existing Emacs Lisp libraries
2994 assume that they receive bare code including a sequence of
2995 CR LF. */
2996 val = Qnil;
2997 else
2999 if (NILP (host) || NILP (service))
3000 coding_systems = Qnil;
3001 else
3002 coding_systems = CALLN (Ffind_operation_coding_system,
3003 Qopen_network_stream, name, p->buffer,
3004 host, service);
3005 if (CONSP (coding_systems))
3006 val = XCAR (coding_systems);
3007 else if (CONSP (Vdefault_process_coding_system))
3008 val = XCAR (Vdefault_process_coding_system);
3009 else
3010 val = Qnil;
3012 pset_decode_coding_system (p, val);
3014 if (!NILP (tem))
3016 val = XCAR (XCDR (tem));
3017 if (CONSP (val))
3018 val = XCDR (val);
3020 else if (!NILP (Vcoding_system_for_write))
3021 val = Vcoding_system_for_write;
3022 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3023 val = Qnil;
3024 else
3026 if (EQ (coding_systems, Qt))
3028 if (NILP (host) || NILP (service))
3029 coding_systems = Qnil;
3030 else
3031 coding_systems = CALLN (Ffind_operation_coding_system,
3032 Qopen_network_stream, name, p->buffer,
3033 host, service);
3035 if (CONSP (coding_systems))
3036 val = XCDR (coding_systems);
3037 else if (CONSP (Vdefault_process_coding_system))
3038 val = XCDR (Vdefault_process_coding_system);
3039 else
3040 val = Qnil;
3042 pset_encode_coding_system (p, val);
3044 pset_decoding_buf (p, empty_unibyte_string);
3045 p->decoding_carryover = 0;
3046 pset_encoding_buf (p, empty_unibyte_string);
3048 p->inherit_coding_system_flag
3049 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3052 #ifdef HAVE_GNUTLS
3053 static void
3054 finish_after_tls_connection (Lisp_Object proc)
3056 struct Lisp_Process *p = XPROCESS (proc);
3057 Lisp_Object contact = p->childp;
3058 Lisp_Object result = Qt;
3060 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3061 result = call3 (Qnsm_verify_connection,
3062 proc,
3063 Fplist_get (contact, QChost),
3064 Fplist_get (contact, QCservice));
3066 if (NILP (result))
3068 pset_status (p, list2 (Qfailed,
3069 build_string ("The Network Security Manager stopped the connections")));
3070 deactivate_process (proc);
3072 else
3074 /* If we cleared the connection wait mask before we did
3075 the TLS setup, then we have to say that the process
3076 is finally "open" here. */
3077 if (! FD_ISSET (p->outfd, &connect_wait_mask))
3079 pset_status (p, Qrun);
3080 /* Execute the sentinel here. If we had relied on
3081 status_notify to do it later, it will read input
3082 from the process before calling the sentinel. */
3083 exec_sentinel (proc, build_string ("open\n"));
3087 #endif
3089 static void
3090 connect_network_socket (Lisp_Object proc, Lisp_Object ip_addresses)
3092 ptrdiff_t count = SPECPDL_INDEX ();
3093 ptrdiff_t count1;
3094 int s = -1, outch, inch;
3095 int xerrno = 0;
3096 Lisp_Object ip_address;
3097 int family;
3098 struct sockaddr *sa = NULL;
3099 int ret;
3100 ptrdiff_t addrlen;
3101 struct Lisp_Process *p = XPROCESS (proc);
3102 Lisp_Object contact = p->childp;
3103 int optbits = 0;
3105 /* Do this in case we never enter the while-loop below. */
3106 count1 = SPECPDL_INDEX ();
3107 s = -1;
3109 while (!NILP (ip_addresses))
3111 ip_address = XCAR (ip_addresses);
3112 ip_addresses = XCDR (ip_addresses);
3114 #ifdef WINDOWSNT
3115 retry_connect:
3116 #endif
3118 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3119 if (sa)
3120 free (sa);
3121 sa = xmalloc (addrlen);
3122 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3124 s = socket (family, p->socktype | SOCK_CLOEXEC, p->ai_protocol);
3125 if (s < 0)
3127 xerrno = errno;
3128 continue;
3131 #ifdef DATAGRAM_SOCKETS
3132 if (!p->is_server && p->socktype == SOCK_DGRAM)
3133 break;
3134 #endif /* DATAGRAM_SOCKETS */
3136 #ifdef NON_BLOCKING_CONNECT
3137 if (p->is_non_blocking_client)
3139 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3140 if (ret < 0)
3142 xerrno = errno;
3143 emacs_close (s);
3144 s = -1;
3145 continue;
3148 #endif
3150 /* Make us close S if quit. */
3151 record_unwind_protect_int (close_file_unwind, s);
3153 /* Parse network options in the arg list. We simply ignore anything
3154 which isn't a known option (including other keywords). An error
3155 is signaled if setting a known option fails. */
3157 Lisp_Object params = contact, key, val;
3159 while (!NILP (params))
3161 key = XCAR (params);
3162 params = XCDR (params);
3163 val = XCAR (params);
3164 params = XCDR (params);
3165 optbits |= set_socket_option (s, key, val);
3169 if (p->is_server)
3171 /* Configure as a server socket. */
3173 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3174 explicit :reuseaddr key to override this. */
3175 #ifdef HAVE_LOCAL_SOCKETS
3176 if (family != AF_LOCAL)
3177 #endif
3178 if (!(optbits & (1 << OPIX_REUSEADDR)))
3180 int optval = 1;
3181 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3182 report_file_error ("Cannot set reuse option on server socket", Qnil);
3185 if (bind (s, sa, addrlen))
3186 report_file_error ("Cannot bind server socket", Qnil);
3188 #ifdef HAVE_GETSOCKNAME
3189 if (p->port == 0)
3191 struct sockaddr_in sa1;
3192 socklen_t len1 = sizeof (sa1);
3193 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3195 Lisp_Object service;
3196 service = make_number (ntohs (sa1.sin_port));
3197 contact = Fplist_put (contact, QCservice, service);
3198 /* Save the port number so that we can stash it in
3199 the process object later. */
3200 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3203 #endif
3205 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3206 report_file_error ("Cannot listen on server socket", Qnil);
3208 break;
3211 immediate_quit = 1;
3212 QUIT;
3214 ret = connect (s, sa, addrlen);
3215 xerrno = errno;
3217 if (ret == 0 || xerrno == EISCONN)
3219 /* The unwind-protect will be discarded afterwards.
3220 Likewise for immediate_quit. */
3221 break;
3224 #ifdef NON_BLOCKING_CONNECT
3225 #ifdef EINPROGRESS
3226 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3227 break;
3228 #else
3229 #ifdef EWOULDBLOCK
3230 if (p->is_non_blocking_client && xerrno == EWOULDBLOCK)
3231 break;
3232 #endif
3233 #endif
3234 #endif
3236 #ifndef WINDOWSNT
3237 if (xerrno == EINTR)
3239 /* Unlike most other syscalls connect() cannot be called
3240 again. (That would return EALREADY.) The proper way to
3241 wait for completion is pselect(). */
3242 int sc;
3243 socklen_t len;
3244 fd_set fdset;
3245 retry_select:
3246 FD_ZERO (&fdset);
3247 FD_SET (s, &fdset);
3248 QUIT;
3249 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3250 if (sc == -1)
3252 if (errno == EINTR)
3253 goto retry_select;
3254 else
3255 report_file_error ("Failed select", Qnil);
3257 eassert (sc > 0);
3259 len = sizeof xerrno;
3260 eassert (FD_ISSET (s, &fdset));
3261 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3262 report_file_error ("Failed getsockopt", Qnil);
3263 if (xerrno)
3264 report_file_errno ("Failed connect", Qnil, xerrno);
3265 break;
3267 #endif /* !WINDOWSNT */
3269 immediate_quit = 0;
3271 /* Discard the unwind protect closing S. */
3272 specpdl_ptr = specpdl + count1;
3273 emacs_close (s);
3274 s = -1;
3276 #ifdef WINDOWSNT
3277 if (xerrno == EINTR)
3278 goto retry_connect;
3279 #endif
3282 if (s >= 0)
3284 #ifdef DATAGRAM_SOCKETS
3285 if (p->socktype == SOCK_DGRAM)
3287 if (datagram_address[s].sa)
3288 emacs_abort ();
3290 datagram_address[s].sa = xmalloc (addrlen);
3291 datagram_address[s].len = addrlen;
3292 if (p->is_server)
3294 Lisp_Object remote;
3295 memset (datagram_address[s].sa, 0, addrlen);
3296 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3298 int rfamily;
3299 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3300 if (rlen != 0 && rfamily == family
3301 && rlen == addrlen)
3302 conv_lisp_to_sockaddr (rfamily, remote,
3303 datagram_address[s].sa, rlen);
3306 else
3307 memcpy (datagram_address[s].sa, sa, addrlen);
3309 #endif
3311 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3312 conv_sockaddr_to_lisp (sa, addrlen));
3313 #ifdef HAVE_GETSOCKNAME
3314 if (!p->is_server)
3316 struct sockaddr_in sa1;
3317 socklen_t len1 = sizeof (sa1);
3318 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3319 contact = Fplist_put (contact, QClocal,
3320 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3322 #endif
3325 immediate_quit = 0;
3327 if (s < 0)
3329 /* If non-blocking got this far - and failed - assume non-blocking is
3330 not supported after all. This is probably a wrong assumption, but
3331 the normal blocking calls to open-network-stream handles this error
3332 better. */
3333 if (p->is_non_blocking_client)
3334 return;
3336 report_file_errno ((p->is_server
3337 ? "make server process failed"
3338 : "make client process failed"),
3339 contact, xerrno);
3342 inch = s;
3343 outch = s;
3345 chan_process[inch] = proc;
3347 fcntl (inch, F_SETFL, O_NONBLOCK);
3349 p = XPROCESS (proc);
3350 p->open_fd[SUBPROCESS_STDIN] = inch;
3351 p->infd = inch;
3352 p->outfd = outch;
3354 /* Discard the unwind protect for closing S, if any. */
3355 specpdl_ptr = specpdl + count1;
3357 /* Unwind bind_polling_period and request_sigio. */
3358 unbind_to (count, Qnil);
3360 if (p->is_server && p->socktype != SOCK_DGRAM)
3361 pset_status (p, Qlisten);
3363 /* Make the process marker point into the process buffer (if any). */
3364 if (BUFFERP (p->buffer))
3365 set_marker_both (p->mark, p->buffer,
3366 BUF_ZV (XBUFFER (p->buffer)),
3367 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3369 #ifdef NON_BLOCKING_CONNECT
3370 if (p->is_non_blocking_client)
3372 /* We may get here if connect did succeed immediately. However,
3373 in that case, we still need to signal this like a non-blocking
3374 connection. */
3375 pset_status (p, Qconnect);
3376 if (!FD_ISSET (inch, &connect_wait_mask))
3378 FD_SET (inch, &connect_wait_mask);
3379 FD_SET (inch, &write_mask);
3380 num_pending_connects++;
3383 else
3384 #endif
3385 /* A server may have a client filter setting of Qt, but it must
3386 still listen for incoming connects unless it is stopped. */
3387 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3388 || (EQ (p->status, Qlisten) && NILP (p->command)))
3390 FD_SET (inch, &input_wait_mask);
3391 FD_SET (inch, &non_keyboard_wait_mask);
3394 if (inch > max_process_desc)
3395 max_process_desc = inch;
3397 /* Set up the masks based on the process filter. */
3398 set_process_filter_masks (p);
3400 setup_process_coding_systems (proc);
3402 #ifdef HAVE_GNUTLS
3403 /* Continue the asynchronous connection. */
3404 if (!NILP (p->gnutls_boot_parameters))
3406 Lisp_Object boot, params = p->gnutls_boot_parameters;
3408 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3409 p->gnutls_boot_parameters = Qnil;
3411 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3412 /* Run sentinels, etc. */
3413 finish_after_tls_connection (proc);
3414 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3416 deactivate_process (proc);
3417 if (NILP (boot))
3418 pset_status (p, list2 (Qfailed,
3419 build_string ("TLS negotiation failed")));
3420 else
3421 pset_status (p, list2 (Qfailed, boot));
3424 #endif
3428 /* Create a network stream/datagram client/server process. Treated
3429 exactly like a normal process when reading and writing. Primary
3430 differences are in status display and process deletion. A network
3431 connection has no PID; you cannot signal it. All you can do is
3432 stop/continue it and deactivate/close it via delete-process. */
3434 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3435 0, MANY, 0,
3436 doc: /* Create and return a network server or client process.
3438 In Emacs, network connections are represented by process objects, so
3439 input and output work as for subprocesses and `delete-process' closes
3440 a network connection. However, a network process has no process id,
3441 it cannot be signaled, and the status codes are different from normal
3442 processes.
3444 Arguments are specified as keyword/argument pairs. The following
3445 arguments are defined:
3447 :name NAME -- NAME is name for process. It is modified if necessary
3448 to make it unique.
3450 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3451 with the process. Process output goes at end of that buffer, unless
3452 you specify an output stream or filter function to handle the output.
3453 BUFFER may be also nil, meaning that this process is not associated
3454 with any buffer.
3456 :host HOST -- HOST is name of the host to connect to, or its IP
3457 address. The symbol `local' specifies the local host. If specified
3458 for a server process, it must be a valid name or address for the local
3459 host, and only clients connecting to that address will be accepted.
3461 :service SERVICE -- SERVICE is name of the service desired, or an
3462 integer specifying a port number to connect to. If SERVICE is t,
3463 a random port number is selected for the server. A port number can
3464 be specified as an integer string, e.g., "80", as well as an integer.
3466 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3467 stream type connection, `datagram' creates a datagram type connection,
3468 `seqpacket' creates a reliable datagram connection.
3470 :family FAMILY -- FAMILY is the address (and protocol) family for the
3471 service specified by HOST and SERVICE. The default (nil) is to use
3472 whatever address family (IPv4 or IPv6) that is defined for the host
3473 and port number specified by HOST and SERVICE. Other address families
3474 supported are:
3475 local -- for a local (i.e. UNIX) address specified by SERVICE.
3476 ipv4 -- use IPv4 address family only.
3477 ipv6 -- use IPv6 address family only.
3479 :local ADDRESS -- ADDRESS is the local address used for the connection.
3480 This parameter is ignored when opening a client process. When specified
3481 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3483 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3484 connection. This parameter is ignored when opening a stream server
3485 process. For a datagram server process, it specifies the initial
3486 setting of the remote datagram address. When specified for a client
3487 process, the FAMILY, HOST, and SERVICE args are ignored.
3489 The format of ADDRESS depends on the address family:
3490 - An IPv4 address is represented as an vector of integers [A B C D P]
3491 corresponding to numeric IP address A.B.C.D and port number P.
3492 - A local address is represented as a string with the address in the
3493 local address space.
3494 - An "unsupported family" address is represented by a cons (F . AV)
3495 where F is the family number and AV is a vector containing the socket
3496 address data with one element per address data byte. Do not rely on
3497 this format in portable code, as it may depend on implementation
3498 defined constants, data sizes, and data structure alignment.
3500 :coding CODING -- If CODING is a symbol, it specifies the coding
3501 system used for both reading and writing for this process. If CODING
3502 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3503 ENCODING is used for writing.
3505 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3506 process, return without waiting for the connection to complete;
3507 instead, the sentinel function will be called with second arg matching
3508 "open" (if successful) or "failed" when the connect completes.
3509 Default is to use a blocking connect (i.e. wait) for stream type
3510 connections.
3512 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3513 running when Emacs is exited.
3515 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3516 In the stopped state, a server process does not accept new
3517 connections, and a client process does not handle incoming traffic.
3518 The stopped state is cleared by `continue-process' and set by
3519 `stop-process'.
3521 :filter FILTER -- Install FILTER as the process filter.
3523 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3524 process filter are multibyte, otherwise they are unibyte.
3525 If this keyword is not specified, the strings are multibyte if
3526 the default value of `enable-multibyte-characters' is non-nil.
3528 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3530 :log LOG -- Install LOG as the server process log function. This
3531 function is called when the server accepts a network connection from a
3532 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3533 is the server process, CLIENT is the new process for the connection,
3534 and MESSAGE is a string.
3536 :plist PLIST -- Install PLIST as the new process's initial plist.
3538 :tls-parameters LIST -- is a list that should be supplied if you're
3539 opening a TLS connection. The first element is the TLS type (either
3540 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3541 be a keyword list accepted by gnutls-boot (as returned by
3542 `gnutls-boot-parameters').
3544 :server QLEN -- if QLEN is non-nil, create a server process for the
3545 specified FAMILY, SERVICE, and connection type (stream or datagram).
3546 If QLEN is an integer, it is used as the max. length of the server's
3547 pending connection queue (also known as the backlog); the default
3548 queue length is 5. Default is to create a client process.
3550 The following network options can be specified for this connection:
3552 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3553 :dontroute BOOL -- Only send to directly connected hosts.
3554 :keepalive BOOL -- Send keep-alive messages on network stream.
3555 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3556 :oobinline BOOL -- Place out-of-band data in receive data stream.
3557 :priority INT -- Set protocol defined priority for sent packets.
3558 :reuseaddr BOOL -- Allow reusing a recently used local address
3559 (this is allowed by default for a server process).
3560 :bindtodevice NAME -- bind to interface NAME. Using this may require
3561 special privileges on some systems.
3563 Consult the relevant system programmer's manual pages for more
3564 information on using these options.
3567 A server process will listen for and accept connections from clients.
3568 When a client connection is accepted, a new network process is created
3569 for the connection with the following parameters:
3571 - The client's process name is constructed by concatenating the server
3572 process's NAME and a client identification string.
3573 - If the FILTER argument is non-nil, the client process will not get a
3574 separate process buffer; otherwise, the client's process buffer is a newly
3575 created buffer named after the server process's BUFFER name or process
3576 NAME concatenated with the client identification string.
3577 - The connection type and the process filter and sentinel parameters are
3578 inherited from the server process's TYPE, FILTER and SENTINEL.
3579 - The client process's contact info is set according to the client's
3580 addressing information (typically an IP address and a port number).
3581 - The client process's plist is initialized from the server's plist.
3583 Notice that the FILTER and SENTINEL args are never used directly by
3584 the server process. Also, the BUFFER argument is not used directly by
3585 the server process, but via the optional :log function, accepted (and
3586 failed) connections may be logged in the server process's buffer.
3588 The original argument list, modified with the actual connection
3589 information, is available via the `process-contact' function.
3591 usage: (make-network-process &rest ARGS) */)
3592 (ptrdiff_t nargs, Lisp_Object *args)
3594 Lisp_Object proc;
3595 Lisp_Object contact;
3596 struct Lisp_Process *p;
3597 const char *portstring;
3598 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3599 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3600 #ifdef HAVE_LOCAL_SOCKETS
3601 struct sockaddr_un address_un;
3602 #endif
3603 EMACS_INT port = 0;
3604 Lisp_Object tem;
3605 Lisp_Object name, buffer, host, service, address;
3606 Lisp_Object filter, sentinel;
3607 Lisp_Object ip_addresses = Qnil;
3608 int socktype;
3609 int family = -1;
3610 int ai_protocol = 0;
3611 #ifdef HAVE_GETADDRINFO_A
3612 struct gaicb *dns_request = NULL;
3613 #endif
3614 ptrdiff_t count = SPECPDL_INDEX ();
3616 if (nargs == 0)
3617 return Qnil;
3619 /* Save arguments for process-contact and clone-process. */
3620 contact = Flist (nargs, args);
3622 #ifdef WINDOWSNT
3623 /* Ensure socket support is loaded if available. */
3624 init_winsock (TRUE);
3625 #endif
3627 /* :type TYPE (nil: stream, datagram */
3628 tem = Fplist_get (contact, QCtype);
3629 if (NILP (tem))
3630 socktype = SOCK_STREAM;
3631 #ifdef DATAGRAM_SOCKETS
3632 else if (EQ (tem, Qdatagram))
3633 socktype = SOCK_DGRAM;
3634 #endif
3635 #ifdef HAVE_SEQPACKET
3636 else if (EQ (tem, Qseqpacket))
3637 socktype = SOCK_SEQPACKET;
3638 #endif
3639 else
3640 error ("Unsupported connection type");
3642 name = Fplist_get (contact, QCname);
3643 buffer = Fplist_get (contact, QCbuffer);
3644 filter = Fplist_get (contact, QCfilter);
3645 sentinel = Fplist_get (contact, QCsentinel);
3647 CHECK_STRING (name);
3649 /* :local ADDRESS or :remote ADDRESS */
3650 tem = Fplist_get (contact, QCserver);
3651 if (!NILP (tem))
3652 address = Fplist_get (contact, QCremote);
3653 else
3654 address = Fplist_get (contact, QClocal);
3655 if (!NILP (address))
3657 host = service = Qnil;
3659 if (!get_lisp_to_sockaddr_size (address, &family))
3660 error ("Malformed :address");
3662 ip_addresses = list1 (address);
3663 goto open_socket;
3666 /* :family FAMILY -- nil (for Inet), local, or integer. */
3667 tem = Fplist_get (contact, QCfamily);
3668 if (NILP (tem))
3670 #ifdef AF_INET6
3671 family = AF_UNSPEC;
3672 #else
3673 family = AF_INET;
3674 #endif
3676 #ifdef HAVE_LOCAL_SOCKETS
3677 else if (EQ (tem, Qlocal))
3678 family = AF_LOCAL;
3679 #endif
3680 #ifdef AF_INET6
3681 else if (EQ (tem, Qipv6))
3682 family = AF_INET6;
3683 #endif
3684 else if (EQ (tem, Qipv4))
3685 family = AF_INET;
3686 else if (TYPE_RANGED_INTEGERP (int, tem))
3687 family = XINT (tem);
3688 else
3689 error ("Unknown address family");
3691 /* :service SERVICE -- string, integer (port number), or t (random port). */
3692 service = Fplist_get (contact, QCservice);
3694 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3695 host = Fplist_get (contact, QChost);
3696 if (NILP (host))
3698 /* The "connection" function gets it bind info from the address we're
3699 given, so use this dummy address if nothing is specified. */
3700 #ifdef HAVE_LOCAL_SOCKETS
3701 if (family != AF_LOCAL)
3702 #endif
3703 host = build_string ("127.0.0.1");
3705 else
3707 if (EQ (host, Qlocal))
3708 /* Depending on setup, "localhost" may map to different IPv4 and/or
3709 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3710 host = build_string ("127.0.0.1");
3711 CHECK_STRING (host);
3714 #ifdef HAVE_LOCAL_SOCKETS
3715 if (family == AF_LOCAL)
3717 if (!NILP (host))
3719 message (":family local ignores the :host property");
3720 contact = Fplist_put (contact, QChost, Qnil);
3721 host = Qnil;
3723 CHECK_STRING (service);
3724 if (sizeof address_un.sun_path <= SBYTES (service))
3725 error ("Service name too long");
3726 ip_addresses = list1 (service);
3727 goto open_socket;
3729 #endif
3731 /* Slow down polling to every ten seconds.
3732 Some kernels have a bug which causes retrying connect to fail
3733 after a connect. Polling can interfere with gethostbyname too. */
3734 #ifdef POLL_FOR_INPUT
3735 if (socktype != SOCK_DGRAM)
3737 record_unwind_protect_void (run_all_atimers);
3738 bind_polling_period (10);
3740 #endif
3742 if (!NILP (host))
3744 /* SERVICE can either be a string or int.
3745 Convert to a C string for later use by getaddrinfo. */
3746 if (EQ (service, Qt))
3748 portstring = "0";
3749 portstringlen = 1;
3751 else if (INTEGERP (service))
3753 portstring = portbuf;
3754 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3756 else
3758 CHECK_STRING (service);
3759 portstring = SSDATA (service);
3760 portstringlen = SBYTES (service);
3764 #ifdef HAVE_GETADDRINFO_A
3765 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3767 ptrdiff_t hostlen = SBYTES (host);
3768 struct req
3770 struct gaicb gaicb;
3771 struct addrinfo hints;
3772 char str[FLEXIBLE_ARRAY_MEMBER];
3773 } *req = xmalloc (offsetof (struct req, str)
3774 + hostlen + 1 + portstringlen + 1);
3775 dns_request = &req->gaicb;
3776 dns_request->ar_name = req->str;
3777 dns_request->ar_service = req->str + hostlen + 1;
3778 dns_request->ar_request = &req->hints;
3779 dns_request->ar_result = NULL;
3780 memset (&req->hints, 0, sizeof req->hints);
3781 req->hints.ai_family = family;
3782 req->hints.ai_socktype = socktype;
3783 strcpy (req->str, SSDATA (host));
3784 strcpy (req->str + hostlen + 1, portstring);
3786 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3787 if (ret)
3788 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3790 goto open_socket;
3792 #endif /* HAVE_GETADDRINFO_A */
3794 /* If we have a host, use getaddrinfo to resolve both host and service.
3795 Otherwise, use getservbyname to lookup the service. */
3797 if (!NILP (host))
3799 struct addrinfo *res, *lres;
3800 int ret;
3802 immediate_quit = 1;
3803 QUIT;
3805 struct addrinfo hints;
3806 memset (&hints, 0, sizeof hints);
3807 hints.ai_family = family;
3808 hints.ai_socktype = socktype;
3810 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3811 if (ret)
3812 #ifdef HAVE_GAI_STRERROR
3814 synchronize_system_messages_locale ();
3815 char const *str = gai_strerror (ret);
3816 if (! NILP (Vlocale_coding_system))
3817 str = SSDATA (code_convert_string_norecord
3818 (build_string (str), Vlocale_coding_system, 0));
3819 error ("%s/%s %s", SSDATA (host), portstring, str);
3821 #else
3822 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3823 #endif
3824 immediate_quit = 0;
3826 for (lres = res; lres; lres = lres->ai_next)
3828 ip_addresses = Fcons (conv_sockaddr_to_lisp
3829 (lres->ai_addr, lres->ai_addrlen),
3830 ip_addresses);
3831 ai_protocol = lres->ai_protocol;
3834 ip_addresses = Fnreverse (ip_addresses);
3836 freeaddrinfo (res);
3838 goto open_socket;
3841 /* No hostname has been specified (e.g., a local server process). */
3843 if (EQ (service, Qt))
3844 port = 0;
3845 else if (INTEGERP (service))
3846 port = XINT (service);
3847 else
3849 CHECK_STRING (service);
3851 port = -1;
3852 if (SBYTES (service) != 0)
3854 /* Allow the service to be a string containing the port number,
3855 because that's allowed if you have getaddrbyname. */
3856 char *service_end;
3857 long int lport = strtol (SSDATA (service), &service_end, 10);
3858 if (service_end == SSDATA (service) + SBYTES (service))
3859 port = lport;
3860 else
3862 struct servent *svc_info
3863 = getservbyname (SSDATA (service),
3864 socktype == SOCK_DGRAM ? "udp" : "tcp");
3865 if (svc_info)
3866 port = ntohs (svc_info->s_port);
3871 if (! (0 <= port && port < 1 << 16))
3873 AUTO_STRING (unknown_service, "Unknown service: %s");
3874 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
3877 open_socket:
3879 if (!NILP (buffer))
3880 buffer = Fget_buffer_create (buffer);
3881 proc = make_process (name);
3882 p = XPROCESS (proc);
3883 pset_childp (p, contact);
3884 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3885 pset_type (p, Qnetwork);
3887 pset_buffer (p, buffer);
3888 pset_sentinel (p, sentinel);
3889 pset_filter (p, filter);
3890 pset_log (p, Fplist_get (contact, QClog));
3891 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3892 p->kill_without_query = 1;
3893 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3894 pset_command (p, Qt);
3895 p->pid = 0;
3896 p->backlog = 5;
3897 p->is_non_blocking_client = 0;
3898 p->is_server = 0;
3899 p->port = port;
3900 p->socktype = socktype;
3901 p->ai_protocol = ai_protocol;
3902 #ifdef HAVE_GETADDRINFO_A
3903 p->dns_request = NULL;
3904 #endif
3905 #ifdef HAVE_GNUTLS
3906 tem = Fplist_get (contact, QCtls_parameters);
3907 CHECK_LIST (tem);
3908 p->gnutls_boot_parameters = tem;
3909 #endif
3911 set_network_socket_coding_system (proc, service, host, name);
3913 unbind_to (count, Qnil);
3915 /* :server BOOL */
3916 tem = Fplist_get (contact, QCserver);
3917 if (!NILP (tem))
3919 /* Don't support network sockets when non-blocking mode is
3920 not available, since a blocked Emacs is not useful. */
3921 p->is_server = 1;
3922 if (TYPE_RANGED_INTEGERP (int, tem))
3923 p->backlog = XINT (tem);
3926 /* :nowait BOOL */
3927 if (!p->is_server && socktype != SOCK_DGRAM
3928 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3930 #ifndef NON_BLOCKING_CONNECT
3931 error ("Non-blocking connect not supported");
3932 #else
3933 p->is_non_blocking_client = 1;
3934 #endif
3937 #ifdef HAVE_GETADDRINFO_A
3938 /* With async address resolution, the list of addresses is empty, so
3939 postpone connecting to the server. */
3940 if (!p->is_server && NILP (ip_addresses))
3942 p->dns_request = dns_request;
3943 p->status = Qconnect;
3944 return proc;
3946 #endif
3948 connect_network_socket (proc, ip_addresses);
3949 return proc;
3953 #ifdef HAVE_NET_IF_H
3955 #ifdef SIOCGIFCONF
3956 static Lisp_Object
3957 network_interface_list (void)
3959 struct ifconf ifconf;
3960 struct ifreq *ifreq;
3961 void *buf = NULL;
3962 ptrdiff_t buf_size = 512;
3963 int s;
3964 Lisp_Object res;
3965 ptrdiff_t count;
3967 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3968 if (s < 0)
3969 return Qnil;
3970 count = SPECPDL_INDEX ();
3971 record_unwind_protect_int (close_file_unwind, s);
3975 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3976 ifconf.ifc_buf = buf;
3977 ifconf.ifc_len = buf_size;
3978 if (ioctl (s, SIOCGIFCONF, &ifconf))
3980 emacs_close (s);
3981 xfree (buf);
3982 return Qnil;
3985 while (ifconf.ifc_len == buf_size);
3987 res = unbind_to (count, Qnil);
3988 ifreq = ifconf.ifc_req;
3989 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3991 struct ifreq *ifq = ifreq;
3992 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3993 #define SIZEOF_IFREQ(sif) \
3994 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3995 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3997 int len = SIZEOF_IFREQ (ifq);
3998 #else
3999 int len = sizeof (*ifreq);
4000 #endif
4001 char namebuf[sizeof (ifq->ifr_name) + 1];
4002 ifreq = (struct ifreq *) ((char *) ifreq + len);
4004 if (ifq->ifr_addr.sa_family != AF_INET)
4005 continue;
4007 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4008 namebuf[sizeof (ifq->ifr_name)] = 0;
4009 res = Fcons (Fcons (build_string (namebuf),
4010 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4011 sizeof (struct sockaddr))),
4012 res);
4015 xfree (buf);
4016 return res;
4018 #endif /* SIOCGIFCONF */
4020 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4022 struct ifflag_def {
4023 int flag_bit;
4024 const char *flag_sym;
4027 static const struct ifflag_def ifflag_table[] = {
4028 #ifdef IFF_UP
4029 { IFF_UP, "up" },
4030 #endif
4031 #ifdef IFF_BROADCAST
4032 { IFF_BROADCAST, "broadcast" },
4033 #endif
4034 #ifdef IFF_DEBUG
4035 { IFF_DEBUG, "debug" },
4036 #endif
4037 #ifdef IFF_LOOPBACK
4038 { IFF_LOOPBACK, "loopback" },
4039 #endif
4040 #ifdef IFF_POINTOPOINT
4041 { IFF_POINTOPOINT, "pointopoint" },
4042 #endif
4043 #ifdef IFF_RUNNING
4044 { IFF_RUNNING, "running" },
4045 #endif
4046 #ifdef IFF_NOARP
4047 { IFF_NOARP, "noarp" },
4048 #endif
4049 #ifdef IFF_PROMISC
4050 { IFF_PROMISC, "promisc" },
4051 #endif
4052 #ifdef IFF_NOTRAILERS
4053 #ifdef NS_IMPL_COCOA
4054 /* Really means smart, notrailers is obsolete. */
4055 { IFF_NOTRAILERS, "smart" },
4056 #else
4057 { IFF_NOTRAILERS, "notrailers" },
4058 #endif
4059 #endif
4060 #ifdef IFF_ALLMULTI
4061 { IFF_ALLMULTI, "allmulti" },
4062 #endif
4063 #ifdef IFF_MASTER
4064 { IFF_MASTER, "master" },
4065 #endif
4066 #ifdef IFF_SLAVE
4067 { IFF_SLAVE, "slave" },
4068 #endif
4069 #ifdef IFF_MULTICAST
4070 { IFF_MULTICAST, "multicast" },
4071 #endif
4072 #ifdef IFF_PORTSEL
4073 { IFF_PORTSEL, "portsel" },
4074 #endif
4075 #ifdef IFF_AUTOMEDIA
4076 { IFF_AUTOMEDIA, "automedia" },
4077 #endif
4078 #ifdef IFF_DYNAMIC
4079 { IFF_DYNAMIC, "dynamic" },
4080 #endif
4081 #ifdef IFF_OACTIVE
4082 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4083 #endif
4084 #ifdef IFF_SIMPLEX
4085 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4086 #endif
4087 #ifdef IFF_LINK0
4088 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4089 #endif
4090 #ifdef IFF_LINK1
4091 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4092 #endif
4093 #ifdef IFF_LINK2
4094 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4095 #endif
4096 { 0, 0 }
4099 static Lisp_Object
4100 network_interface_info (Lisp_Object ifname)
4102 struct ifreq rq;
4103 Lisp_Object res = Qnil;
4104 Lisp_Object elt;
4105 int s;
4106 bool any = 0;
4107 ptrdiff_t count;
4108 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4109 && defined HAVE_GETIFADDRS && defined LLADDR)
4110 struct ifaddrs *ifap;
4111 #endif
4113 CHECK_STRING (ifname);
4115 if (sizeof rq.ifr_name <= SBYTES (ifname))
4116 error ("interface name too long");
4117 lispstpcpy (rq.ifr_name, ifname);
4119 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4120 if (s < 0)
4121 return Qnil;
4122 count = SPECPDL_INDEX ();
4123 record_unwind_protect_int (close_file_unwind, s);
4125 elt = Qnil;
4126 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4127 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4129 int flags = rq.ifr_flags;
4130 const struct ifflag_def *fp;
4131 int fnum;
4133 /* If flags is smaller than int (i.e. short) it may have the high bit set
4134 due to IFF_MULTICAST. In that case, sign extending it into
4135 an int is wrong. */
4136 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4137 flags = (unsigned short) rq.ifr_flags;
4139 any = 1;
4140 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4142 if (flags & fp->flag_bit)
4144 elt = Fcons (intern (fp->flag_sym), elt);
4145 flags -= fp->flag_bit;
4148 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4150 if (flags & 1)
4152 elt = Fcons (make_number (fnum), elt);
4156 #endif
4157 res = Fcons (elt, res);
4159 elt = Qnil;
4160 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4161 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4163 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4164 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4165 int n;
4167 any = 1;
4168 for (n = 0; n < 6; n++)
4169 p->contents[n] = make_number (((unsigned char *)
4170 &rq.ifr_hwaddr.sa_data[0])
4171 [n]);
4172 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4174 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4175 if (getifaddrs (&ifap) != -1)
4177 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4178 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4179 struct ifaddrs *it;
4181 for (it = ifap; it != NULL; it = it->ifa_next)
4183 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4184 unsigned char linkaddr[6];
4185 int n;
4187 if (it->ifa_addr->sa_family != AF_LINK
4188 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4189 || sdl->sdl_alen != 6)
4190 continue;
4192 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4193 for (n = 0; n < 6; n++)
4194 p->contents[n] = make_number (linkaddr[n]);
4196 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4197 break;
4200 #ifdef HAVE_FREEIFADDRS
4201 freeifaddrs (ifap);
4202 #endif
4204 #endif /* HAVE_GETIFADDRS && LLADDR */
4206 res = Fcons (elt, res);
4208 elt = Qnil;
4209 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4210 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4212 any = 1;
4213 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4214 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4215 #else
4216 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4217 #endif
4219 #endif
4220 res = Fcons (elt, res);
4222 elt = Qnil;
4223 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4224 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4226 any = 1;
4227 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4229 #endif
4230 res = Fcons (elt, res);
4232 elt = Qnil;
4233 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4234 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4236 any = 1;
4237 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4239 #endif
4240 res = Fcons (elt, res);
4242 return unbind_to (count, any ? res : Qnil);
4244 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4245 #endif /* defined (HAVE_NET_IF_H) */
4247 DEFUN ("network-interface-list", Fnetwork_interface_list,
4248 Snetwork_interface_list, 0, 0, 0,
4249 doc: /* Return an alist of all network interfaces and their network address.
4250 Each element is a cons, the car of which is a string containing the
4251 interface name, and the cdr is the network address in internal
4252 format; see the description of ADDRESS in `make-network-process'.
4254 If the information is not available, return nil. */)
4255 (void)
4257 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4258 return network_interface_list ();
4259 #else
4260 return Qnil;
4261 #endif
4264 DEFUN ("network-interface-info", Fnetwork_interface_info,
4265 Snetwork_interface_info, 1, 1, 0,
4266 doc: /* Return information about network interface named IFNAME.
4267 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4268 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4269 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4270 FLAGS is the current flags of the interface.
4272 Data that is unavailable is returned as nil. */)
4273 (Lisp_Object ifname)
4275 #if ((defined HAVE_NET_IF_H \
4276 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4277 || defined SIOCGIFFLAGS)) \
4278 || defined WINDOWSNT)
4279 return network_interface_info (ifname);
4280 #else
4281 return Qnil;
4282 #endif
4285 /* If program file NAME starts with /: for quoting a magic
4286 name, remove that, preserving the multibyteness of NAME. */
4288 Lisp_Object
4289 remove_slash_colon (Lisp_Object name)
4291 return
4292 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4293 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4294 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4295 : name);
4298 /* Turn off input and output for process PROC. */
4300 static void
4301 deactivate_process (Lisp_Object proc)
4303 int inchannel;
4304 struct Lisp_Process *p = XPROCESS (proc);
4305 int i;
4307 #ifdef HAVE_GNUTLS
4308 /* Delete GnuTLS structures in PROC, if any. */
4309 emacs_gnutls_deinit (proc);
4310 #endif /* HAVE_GNUTLS */
4312 if (p->read_output_delay > 0)
4314 if (--process_output_delay_count < 0)
4315 process_output_delay_count = 0;
4316 p->read_output_delay = 0;
4317 p->read_output_skip = 0;
4320 /* Beware SIGCHLD hereabouts. */
4322 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4323 close_process_fd (&p->open_fd[i]);
4325 inchannel = p->infd;
4326 if (inchannel >= 0)
4328 p->infd = -1;
4329 p->outfd = -1;
4330 #ifdef DATAGRAM_SOCKETS
4331 if (DATAGRAM_CHAN_P (inchannel))
4333 xfree (datagram_address[inchannel].sa);
4334 datagram_address[inchannel].sa = 0;
4335 datagram_address[inchannel].len = 0;
4337 #endif
4338 chan_process[inchannel] = Qnil;
4339 FD_CLR (inchannel, &input_wait_mask);
4340 FD_CLR (inchannel, &non_keyboard_wait_mask);
4341 #ifdef NON_BLOCKING_CONNECT
4342 if (FD_ISSET (inchannel, &connect_wait_mask))
4344 FD_CLR (inchannel, &connect_wait_mask);
4345 FD_CLR (inchannel, &write_mask);
4346 if (--num_pending_connects < 0)
4347 emacs_abort ();
4349 #endif
4350 if (inchannel == max_process_desc)
4352 /* We just closed the highest-numbered process input descriptor,
4353 so recompute the highest-numbered one now. */
4354 int i = inchannel;
4356 i--;
4357 while (0 <= i && NILP (chan_process[i]));
4359 max_process_desc = i;
4365 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4366 0, 4, 0,
4367 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4368 It is given to their filter functions.
4369 Optional argument PROCESS means do not return until output has been
4370 received from PROCESS.
4372 Optional second argument SECONDS and third argument MILLISEC
4373 specify a timeout; return after that much time even if there is
4374 no subprocess output. If SECONDS is a floating point number,
4375 it specifies a fractional number of seconds to wait.
4376 The MILLISEC argument is obsolete and should be avoided.
4378 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4379 from PROCESS only, suspending reading output from other processes.
4380 If JUST-THIS-ONE is an integer, don't run any timers either.
4381 Return non-nil if we received any output from PROCESS (or, if PROCESS
4382 is nil, from any process) before the timeout expired. */)
4383 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4385 intmax_t secs;
4386 int nsecs;
4388 if (! NILP (process))
4389 CHECK_PROCESS (process);
4390 else
4391 just_this_one = Qnil;
4393 if (!NILP (millisec))
4394 { /* Obsolete calling convention using integers rather than floats. */
4395 CHECK_NUMBER (millisec);
4396 if (NILP (seconds))
4397 seconds = make_float (XINT (millisec) / 1000.0);
4398 else
4400 CHECK_NUMBER (seconds);
4401 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4405 secs = 0;
4406 nsecs = -1;
4408 if (!NILP (seconds))
4410 if (INTEGERP (seconds))
4412 if (XINT (seconds) > 0)
4414 secs = XINT (seconds);
4415 nsecs = 0;
4418 else if (FLOATP (seconds))
4420 if (XFLOAT_DATA (seconds) > 0)
4422 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4423 secs = min (t.tv_sec, WAIT_READING_MAX);
4424 nsecs = t.tv_nsec;
4427 else
4428 wrong_type_argument (Qnumberp, seconds);
4430 else if (! NILP (process))
4431 nsecs = 0;
4433 return
4434 ((wait_reading_process_output (secs, nsecs, 0, 0,
4435 Qnil,
4436 !NILP (process) ? XPROCESS (process) : NULL,
4437 (NILP (just_this_one) ? 0
4438 : !INTEGERP (just_this_one) ? 1 : -1))
4439 <= 0)
4440 ? Qnil : Qt);
4443 /* Accept a connection for server process SERVER on CHANNEL. */
4445 static EMACS_INT connect_counter = 0;
4447 static void
4448 server_accept_connection (Lisp_Object server, int channel)
4450 Lisp_Object proc, caller, name, buffer;
4451 Lisp_Object contact, host, service;
4452 struct Lisp_Process *ps = XPROCESS (server);
4453 struct Lisp_Process *p;
4454 int s;
4455 union u_sockaddr {
4456 struct sockaddr sa;
4457 struct sockaddr_in in;
4458 #ifdef AF_INET6
4459 struct sockaddr_in6 in6;
4460 #endif
4461 #ifdef HAVE_LOCAL_SOCKETS
4462 struct sockaddr_un un;
4463 #endif
4464 } saddr;
4465 socklen_t len = sizeof saddr;
4466 ptrdiff_t count;
4468 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4470 if (s < 0)
4472 int code = errno;
4474 if (code == EAGAIN)
4475 return;
4476 #ifdef EWOULDBLOCK
4477 if (code == EWOULDBLOCK)
4478 return;
4479 #endif
4481 if (!NILP (ps->log))
4482 call3 (ps->log, server, Qnil,
4483 concat3 (build_string ("accept failed with code"),
4484 Fnumber_to_string (make_number (code)),
4485 build_string ("\n")));
4486 return;
4489 count = SPECPDL_INDEX ();
4490 record_unwind_protect_int (close_file_unwind, s);
4492 connect_counter++;
4494 /* Setup a new process to handle the connection. */
4496 /* Generate a unique identification of the caller, and build contact
4497 information for this process. */
4498 host = Qt;
4499 service = Qnil;
4500 switch (saddr.sa.sa_family)
4502 case AF_INET:
4504 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4506 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4507 host = CALLN (Fformat, ipv4_format,
4508 make_number (ip[0]), make_number (ip[1]),
4509 make_number (ip[2]), make_number (ip[3]));
4510 service = make_number (ntohs (saddr.in.sin_port));
4511 AUTO_STRING (caller_format, " <%s:%d>");
4512 caller = CALLN (Fformat, caller_format, host, service);
4514 break;
4516 #ifdef AF_INET6
4517 case AF_INET6:
4519 Lisp_Object args[9];
4520 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4521 int i;
4523 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4524 args[0] = ipv6_format;
4525 for (i = 0; i < 8; i++)
4526 args[i + 1] = make_number (ntohs (ip6[i]));
4527 host = CALLMANY (Fformat, args);
4528 service = make_number (ntohs (saddr.in.sin_port));
4529 AUTO_STRING (caller_format, " <[%s]:%d>");
4530 caller = CALLN (Fformat, caller_format, host, service);
4532 break;
4533 #endif
4535 #ifdef HAVE_LOCAL_SOCKETS
4536 case AF_LOCAL:
4537 #endif
4538 default:
4539 caller = Fnumber_to_string (make_number (connect_counter));
4540 AUTO_STRING (space_less_than, " <");
4541 AUTO_STRING (greater_than, ">");
4542 caller = concat3 (space_less_than, caller, greater_than);
4543 break;
4546 /* Create a new buffer name for this process if it doesn't have a
4547 filter. The new buffer name is based on the buffer name or
4548 process name of the server process concatenated with the caller
4549 identification. */
4551 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4552 || EQ (ps->filter, Qt)))
4553 buffer = Qnil;
4554 else
4556 buffer = ps->buffer;
4557 if (!NILP (buffer))
4558 buffer = Fbuffer_name (buffer);
4559 else
4560 buffer = ps->name;
4561 if (!NILP (buffer))
4563 buffer = concat2 (buffer, caller);
4564 buffer = Fget_buffer_create (buffer);
4568 /* Generate a unique name for the new server process. Combine the
4569 server process name with the caller identification. */
4571 name = concat2 (ps->name, caller);
4572 proc = make_process (name);
4574 chan_process[s] = proc;
4576 fcntl (s, F_SETFL, O_NONBLOCK);
4578 p = XPROCESS (proc);
4580 /* Build new contact information for this setup. */
4581 contact = Fcopy_sequence (ps->childp);
4582 contact = Fplist_put (contact, QCserver, Qnil);
4583 contact = Fplist_put (contact, QChost, host);
4584 if (!NILP (service))
4585 contact = Fplist_put (contact, QCservice, service);
4586 contact = Fplist_put (contact, QCremote,
4587 conv_sockaddr_to_lisp (&saddr.sa, len));
4588 #ifdef HAVE_GETSOCKNAME
4589 len = sizeof saddr;
4590 if (getsockname (s, &saddr.sa, &len) == 0)
4591 contact = Fplist_put (contact, QClocal,
4592 conv_sockaddr_to_lisp (&saddr.sa, len));
4593 #endif
4595 pset_childp (p, contact);
4596 pset_plist (p, Fcopy_sequence (ps->plist));
4597 pset_type (p, Qnetwork);
4599 pset_buffer (p, buffer);
4600 pset_sentinel (p, ps->sentinel);
4601 pset_filter (p, ps->filter);
4602 pset_command (p, Qnil);
4603 p->pid = 0;
4605 /* Discard the unwind protect for closing S. */
4606 specpdl_ptr = specpdl + count;
4608 p->open_fd[SUBPROCESS_STDIN] = s;
4609 p->infd = s;
4610 p->outfd = s;
4611 pset_status (p, Qrun);
4613 /* Client processes for accepted connections are not stopped initially. */
4614 if (!EQ (p->filter, Qt))
4616 FD_SET (s, &input_wait_mask);
4617 FD_SET (s, &non_keyboard_wait_mask);
4620 if (s > max_process_desc)
4621 max_process_desc = s;
4623 /* Setup coding system for new process based on server process.
4624 This seems to be the proper thing to do, as the coding system
4625 of the new process should reflect the settings at the time the
4626 server socket was opened; not the current settings. */
4628 pset_decode_coding_system (p, ps->decode_coding_system);
4629 pset_encode_coding_system (p, ps->encode_coding_system);
4630 setup_process_coding_systems (proc);
4632 pset_decoding_buf (p, empty_unibyte_string);
4633 p->decoding_carryover = 0;
4634 pset_encoding_buf (p, empty_unibyte_string);
4636 p->inherit_coding_system_flag
4637 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4639 AUTO_STRING (dash, "-");
4640 AUTO_STRING (nl, "\n");
4641 Lisp_Object host_string = STRINGP (host) ? host : dash;
4643 if (!NILP (ps->log))
4645 AUTO_STRING (accept_from, "accept from ");
4646 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4649 AUTO_STRING (open_from, "open from ");
4650 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4653 #ifdef HAVE_GETADDRINFO_A
4654 static Lisp_Object
4655 check_for_dns (Lisp_Object proc)
4657 struct Lisp_Process *p = XPROCESS (proc);
4658 Lisp_Object ip_addresses = Qnil;
4660 /* Sanity check. */
4661 if (! p->dns_request)
4662 return Qnil;
4664 int ret = gai_error (p->dns_request);
4665 if (ret == EAI_INPROGRESS)
4666 return Qt;
4668 /* We got a response. */
4669 if (ret == 0)
4671 struct addrinfo *res;
4673 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4675 ip_addresses = Fcons (conv_sockaddr_to_lisp
4676 (res->ai_addr, res->ai_addrlen),
4677 ip_addresses);
4680 ip_addresses = Fnreverse (ip_addresses);
4682 /* The DNS lookup failed. */
4683 else if (EQ (p->status, Qconnect))
4685 deactivate_process (proc);
4686 pset_status (p, (list2
4687 (Qfailed,
4688 concat3 (build_string ("Name lookup of "),
4689 build_string (p->dns_request->ar_name),
4690 build_string (" failed")))));
4693 free_dns_request (proc);
4695 /* This process should not already be connected (or killed). */
4696 if (!EQ (p->status, Qconnect))
4697 return Qnil;
4699 return ip_addresses;
4702 #endif /* HAVE_GETADDRINFO_A */
4704 static void
4705 wait_for_socket_fds (Lisp_Object process, char const *name)
4707 while (XPROCESS (process)->infd < 0
4708 && EQ (XPROCESS (process)->status, Qconnect))
4710 add_to_log ("Waiting for socket from %s...", build_string (name));
4711 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4715 static void
4716 wait_while_connecting (Lisp_Object process)
4718 while (EQ (XPROCESS (process)->status, Qconnect))
4720 add_to_log ("Waiting for connection...");
4721 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4725 static void
4726 wait_for_tls_negotiation (Lisp_Object process)
4728 #ifdef HAVE_GNUTLS
4729 while (XPROCESS (process)->gnutls_p
4730 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4732 add_to_log ("Waiting for TLS...");
4733 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4735 #endif
4738 /* This variable is different from waiting_for_input in keyboard.c.
4739 It is used to communicate to a lisp process-filter/sentinel (via the
4740 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4741 for user-input when that process-filter was called.
4742 waiting_for_input cannot be used as that is by definition 0 when
4743 lisp code is being evalled.
4744 This is also used in record_asynch_buffer_change.
4745 For that purpose, this must be 0
4746 when not inside wait_reading_process_output. */
4747 static int waiting_for_user_input_p;
4749 static void
4750 wait_reading_process_output_unwind (int data)
4752 waiting_for_user_input_p = data;
4755 /* This is here so breakpoints can be put on it. */
4756 static void
4757 wait_reading_process_output_1 (void)
4761 /* Read and dispose of subprocess output while waiting for timeout to
4762 elapse and/or keyboard input to be available.
4764 TIME_LIMIT is:
4765 timeout in seconds
4766 If negative, gobble data immediately available but don't wait for any.
4768 NSECS is:
4769 an additional duration to wait, measured in nanoseconds
4770 If TIME_LIMIT is zero, then:
4771 If NSECS == 0, there is no limit.
4772 If NSECS > 0, the timeout consists of NSECS only.
4773 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4775 READ_KBD is:
4776 0 to ignore keyboard input, or
4777 1 to return when input is available, or
4778 -1 meaning caller will actually read the input, so don't throw to
4779 the quit handler, or
4781 DO_DISPLAY means redisplay should be done to show subprocess
4782 output that arrives.
4784 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4785 (and gobble terminal input into the buffer if any arrives).
4787 If WAIT_PROC is specified, wait until something arrives from that
4788 process.
4790 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4791 (suspending output from other processes). A negative value
4792 means don't run any timers either.
4794 Return positive if we received input from WAIT_PROC (or from any
4795 process if WAIT_PROC is null), zero if we attempted to receive
4796 input but got none, and negative if we didn't even try. */
4799 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4800 bool do_display,
4801 Lisp_Object wait_for_cell,
4802 struct Lisp_Process *wait_proc, int just_wait_proc)
4804 int channel, nfds;
4805 fd_set Available;
4806 fd_set Writeok;
4807 bool check_write;
4808 int check_delay;
4809 bool no_avail;
4810 int xerrno;
4811 Lisp_Object proc;
4812 struct timespec timeout, end_time, timer_delay;
4813 struct timespec got_output_end_time = invalid_timespec ();
4814 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4815 int got_some_output = -1;
4816 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4817 bool retry_for_async;
4818 #endif
4819 ptrdiff_t count = SPECPDL_INDEX ();
4821 /* Close to the current time if known, an invalid timespec otherwise. */
4822 struct timespec now = invalid_timespec ();
4824 FD_ZERO (&Available);
4825 FD_ZERO (&Writeok);
4827 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4828 && !(CONSP (wait_proc->status)
4829 && EQ (XCAR (wait_proc->status), Qexit)))
4830 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4832 record_unwind_protect_int (wait_reading_process_output_unwind,
4833 waiting_for_user_input_p);
4834 waiting_for_user_input_p = read_kbd;
4836 if (TYPE_MAXIMUM (time_t) < time_limit)
4837 time_limit = TYPE_MAXIMUM (time_t);
4839 if (time_limit < 0 || nsecs < 0)
4840 wait = MINIMUM;
4841 else if (time_limit > 0 || nsecs > 0)
4843 wait = TIMEOUT;
4844 now = current_timespec ();
4845 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4847 else
4848 wait = INFINITY;
4850 while (1)
4852 bool process_skipped = false;
4854 /* If calling from keyboard input, do not quit
4855 since we want to return C-g as an input character.
4856 Otherwise, do pending quit if requested. */
4857 if (read_kbd >= 0)
4858 QUIT;
4859 else if (pending_signals)
4860 process_pending_signals ();
4862 /* Exit now if the cell we're waiting for became non-nil. */
4863 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4864 break;
4866 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4868 Lisp_Object process_list_head, aproc;
4869 struct Lisp_Process *p;
4871 retry_for_async = false;
4872 FOR_EACH_PROCESS(process_list_head, aproc)
4874 p = XPROCESS (aproc);
4876 if (! wait_proc || p == wait_proc)
4878 #ifdef HAVE_GETADDRINFO_A
4879 /* Check for pending DNS requests. */
4880 if (p->dns_request)
4882 Lisp_Object ip_addresses = check_for_dns (aproc);
4883 if (!NILP (ip_addresses) && !EQ (ip_addresses, Qt))
4884 connect_network_socket (aproc, ip_addresses);
4885 else
4886 retry_for_async = true;
4888 #endif
4889 #ifdef HAVE_GNUTLS
4890 /* Continue TLS negotiation. */
4891 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
4892 && p->is_non_blocking_client)
4894 gnutls_try_handshake (p);
4895 p->gnutls_handshakes_tried++;
4897 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
4899 gnutls_verify_boot (aproc, Qnil);
4900 finish_after_tls_connection (aproc);
4902 else
4904 retry_for_async = true;
4905 if (p->gnutls_handshakes_tried
4906 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
4908 deactivate_process (aproc);
4909 pset_status (p, list2 (Qfailed,
4910 build_string ("TLS negotiation failed")));
4914 #endif
4918 #endif /* GETADDRINFO_A or GNUTLS */
4920 /* Compute time from now till when time limit is up. */
4921 /* Exit if already run out. */
4922 if (wait == TIMEOUT)
4924 if (!timespec_valid_p (now))
4925 now = current_timespec ();
4926 if (timespec_cmp (end_time, now) <= 0)
4927 break;
4928 timeout = timespec_sub (end_time, now);
4930 else
4931 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4933 /* Normally we run timers here.
4934 But not if wait_for_cell; in those cases,
4935 the wait is supposed to be short,
4936 and those callers cannot handle running arbitrary Lisp code here. */
4937 if (NILP (wait_for_cell)
4938 && just_wait_proc >= 0)
4942 unsigned old_timers_run = timers_run;
4943 struct buffer *old_buffer = current_buffer;
4944 Lisp_Object old_window = selected_window;
4946 timer_delay = timer_check ();
4948 /* If a timer has run, this might have changed buffers
4949 an alike. Make read_key_sequence aware of that. */
4950 if (timers_run != old_timers_run
4951 && (old_buffer != current_buffer
4952 || !EQ (old_window, selected_window))
4953 && waiting_for_user_input_p == -1)
4954 record_asynch_buffer_change ();
4956 if (timers_run != old_timers_run && do_display)
4957 /* We must retry, since a timer may have requeued itself
4958 and that could alter the time_delay. */
4959 redisplay_preserve_echo_area (9);
4960 else
4961 break;
4963 while (!detect_input_pending ());
4965 /* If there is unread keyboard input, also return. */
4966 if (read_kbd != 0
4967 && requeued_events_pending_p ())
4968 break;
4970 /* This is so a breakpoint can be put here. */
4971 if (!timespec_valid_p (timer_delay))
4972 wait_reading_process_output_1 ();
4975 /* Cause C-g and alarm signals to take immediate action,
4976 and cause input available signals to zero out timeout.
4978 It is important that we do this before checking for process
4979 activity. If we get a SIGCHLD after the explicit checks for
4980 process activity, timeout is the only way we will know. */
4981 if (read_kbd < 0)
4982 set_waiting_for_input (&timeout);
4984 /* If status of something has changed, and no input is
4985 available, notify the user of the change right away. After
4986 this explicit check, we'll let the SIGCHLD handler zap
4987 timeout to get our attention. */
4988 if (update_tick != process_tick)
4990 fd_set Atemp;
4991 fd_set Ctemp;
4993 if (kbd_on_hold_p ())
4994 FD_ZERO (&Atemp);
4995 else
4996 Atemp = input_wait_mask;
4997 Ctemp = write_mask;
4999 timeout = make_timespec (0, 0);
5000 if ((pselect (max (max_process_desc, max_input_desc) + 1,
5001 &Atemp,
5002 #ifdef NON_BLOCKING_CONNECT
5003 (num_pending_connects > 0 ? &Ctemp : NULL),
5004 #else
5005 NULL,
5006 #endif
5007 NULL, &timeout, NULL)
5008 <= 0))
5010 /* It's okay for us to do this and then continue with
5011 the loop, since timeout has already been zeroed out. */
5012 clear_waiting_for_input ();
5013 got_some_output = status_notify (NULL, wait_proc);
5014 if (do_display) redisplay_preserve_echo_area (13);
5018 /* Don't wait for output from a non-running process. Just
5019 read whatever data has already been received. */
5020 if (wait_proc && wait_proc->raw_status_new)
5021 update_status (wait_proc);
5022 if (wait_proc
5023 && ! EQ (wait_proc->status, Qrun)
5024 && ! EQ (wait_proc->status, Qconnect))
5026 bool read_some_bytes = false;
5028 clear_waiting_for_input ();
5030 /* If data can be read from the process, do so until exhausted. */
5031 if (wait_proc->infd >= 0)
5033 XSETPROCESS (proc, wait_proc);
5035 while (true)
5037 int nread = read_process_output (proc, wait_proc->infd);
5038 if (nread < 0)
5040 if (errno == EIO || errno == EAGAIN)
5041 break;
5042 #ifdef EWOULDBLOCK
5043 if (errno == EWOULDBLOCK)
5044 break;
5045 #endif
5047 else
5049 if (got_some_output < nread)
5050 got_some_output = nread;
5051 if (nread == 0)
5052 break;
5053 read_some_bytes = true;
5058 if (read_some_bytes && do_display)
5059 redisplay_preserve_echo_area (10);
5061 break;
5064 /* Wait till there is something to do. */
5066 if (wait_proc && just_wait_proc)
5068 if (wait_proc->infd < 0) /* Terminated. */
5069 break;
5070 FD_SET (wait_proc->infd, &Available);
5071 check_delay = 0;
5072 check_write = 0;
5074 else if (!NILP (wait_for_cell))
5076 Available = non_process_wait_mask;
5077 check_delay = 0;
5078 check_write = 0;
5080 else
5082 if (! read_kbd)
5083 Available = non_keyboard_wait_mask;
5084 else
5085 Available = input_wait_mask;
5086 Writeok = write_mask;
5087 check_delay = wait_proc ? 0 : process_output_delay_count;
5088 check_write = true;
5091 /* If frame size has changed or the window is newly mapped,
5092 redisplay now, before we start to wait. There is a race
5093 condition here; if a SIGIO arrives between now and the select
5094 and indicates that a frame is trashed, the select may block
5095 displaying a trashed screen. */
5096 if (frame_garbaged && do_display)
5098 clear_waiting_for_input ();
5099 redisplay_preserve_echo_area (11);
5100 if (read_kbd < 0)
5101 set_waiting_for_input (&timeout);
5104 /* Skip the `select' call if input is available and we're
5105 waiting for keyboard input or a cell change (which can be
5106 triggered by processing X events). In the latter case, set
5107 nfds to 1 to avoid breaking the loop. */
5108 no_avail = 0;
5109 if ((read_kbd || !NILP (wait_for_cell))
5110 && detect_input_pending ())
5112 nfds = read_kbd ? 0 : 1;
5113 no_avail = 1;
5114 FD_ZERO (&Available);
5116 else
5118 /* Set the timeout for adaptive read buffering if any
5119 process has non-zero read_output_skip and non-zero
5120 read_output_delay, and we are not reading output for a
5121 specific process. It is not executed if
5122 Vprocess_adaptive_read_buffering is nil. */
5123 if (process_output_skip && check_delay > 0)
5125 int adaptive_nsecs = timeout.tv_nsec;
5126 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5127 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5128 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
5130 proc = chan_process[channel];
5131 if (NILP (proc))
5132 continue;
5133 /* Find minimum non-zero read_output_delay among the
5134 processes with non-zero read_output_skip. */
5135 if (XPROCESS (proc)->read_output_delay > 0)
5137 check_delay--;
5138 if (!XPROCESS (proc)->read_output_skip)
5139 continue;
5140 FD_CLR (channel, &Available);
5141 process_skipped = true;
5142 XPROCESS (proc)->read_output_skip = 0;
5143 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5144 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5147 timeout = make_timespec (0, adaptive_nsecs);
5148 process_output_skip = 0;
5151 /* If we've got some output and haven't limited our timeout
5152 with adaptive read buffering, limit it. */
5153 if (got_some_output > 0 && !process_skipped
5154 && (timeout.tv_sec
5155 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5156 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5159 if (NILP (wait_for_cell) && just_wait_proc >= 0
5160 && timespec_valid_p (timer_delay)
5161 && timespec_cmp (timer_delay, timeout) < 0)
5163 if (!timespec_valid_p (now))
5164 now = current_timespec ();
5165 struct timespec timeout_abs = timespec_add (now, timeout);
5166 if (!timespec_valid_p (got_output_end_time)
5167 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5168 got_output_end_time = timeout_abs;
5169 timeout = timer_delay;
5171 else
5172 got_output_end_time = invalid_timespec ();
5174 /* NOW can become inaccurate if time can pass during pselect. */
5175 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5176 now = invalid_timespec ();
5178 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5179 if (retry_for_async
5180 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5182 timeout.tv_sec = 0;
5183 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5185 #endif
5187 #if defined (HAVE_NS)
5188 nfds = ns_select
5189 #elif defined (HAVE_GLIB)
5190 nfds = xg_select
5191 #else
5192 nfds = pselect
5193 #endif
5194 (max (max_process_desc, max_input_desc) + 1,
5195 &Available,
5196 (check_write ? &Writeok : 0),
5197 NULL, &timeout, NULL);
5199 #ifdef HAVE_GNUTLS
5200 /* GnuTLS buffers data internally. In lowat mode it leaves
5201 some data in the TCP buffers so that select works, but
5202 with custom pull/push functions we need to check if some
5203 data is available in the buffers manually. */
5204 if (nfds == 0)
5206 fd_set tls_available;
5207 int set = 0;
5209 FD_ZERO (&tls_available);
5210 if (! wait_proc)
5212 /* We're not waiting on a specific process, so loop
5213 through all the channels and check for data.
5214 This is a workaround needed for some versions of
5215 the gnutls library -- 2.12.14 has been confirmed
5216 to need it. See
5217 http://comments.gmane.org/gmane.emacs.devel/145074 */
5218 for (channel = 0; channel < FD_SETSIZE; ++channel)
5219 if (! NILP (chan_process[channel]))
5221 struct Lisp_Process *p =
5222 XPROCESS (chan_process[channel]);
5223 if (p && p->gnutls_p && p->gnutls_state
5224 && ((emacs_gnutls_record_check_pending
5225 (p->gnutls_state))
5226 > 0))
5228 nfds++;
5229 eassert (p->infd == channel);
5230 FD_SET (p->infd, &tls_available);
5231 set++;
5235 else
5237 /* Check this specific channel. */
5238 if (wait_proc->gnutls_p /* Check for valid process. */
5239 && wait_proc->gnutls_state
5240 /* Do we have pending data? */
5241 && ((emacs_gnutls_record_check_pending
5242 (wait_proc->gnutls_state))
5243 > 0))
5245 nfds = 1;
5246 eassert (0 <= wait_proc->infd);
5247 /* Set to Available. */
5248 FD_SET (wait_proc->infd, &tls_available);
5249 set++;
5252 if (set)
5253 Available = tls_available;
5255 #endif
5258 xerrno = errno;
5260 /* Make C-g and alarm signals set flags again. */
5261 clear_waiting_for_input ();
5263 /* If we woke up due to SIGWINCH, actually change size now. */
5264 do_pending_window_change (0);
5266 if (nfds == 0)
5268 /* Exit the main loop if we've passed the requested timeout,
5269 or aren't skipping processes and got some output and
5270 haven't lowered our timeout due to timers or SIGIO and
5271 have waited a long amount of time due to repeated
5272 timers. */
5273 if (wait < TIMEOUT)
5274 break;
5275 struct timespec cmp_time
5276 = (wait == TIMEOUT
5277 ? end_time
5278 : (!process_skipped && got_some_output > 0
5279 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5280 ? got_output_end_time
5281 : invalid_timespec ());
5282 if (timespec_valid_p (cmp_time))
5284 now = current_timespec ();
5285 if (timespec_cmp (cmp_time, now) <= 0)
5286 break;
5290 if (nfds < 0)
5292 if (xerrno == EINTR)
5293 no_avail = 1;
5294 else if (xerrno == EBADF)
5295 emacs_abort ();
5296 else
5297 report_file_errno ("Failed select", Qnil, xerrno);
5300 /* Check for keyboard input. */
5301 /* If there is any, return immediately
5302 to give it higher priority than subprocesses. */
5304 if (read_kbd != 0)
5306 unsigned old_timers_run = timers_run;
5307 struct buffer *old_buffer = current_buffer;
5308 Lisp_Object old_window = selected_window;
5309 bool leave = false;
5311 if (detect_input_pending_run_timers (do_display))
5313 swallow_events (do_display);
5314 if (detect_input_pending_run_timers (do_display))
5315 leave = true;
5318 /* If a timer has run, this might have changed buffers
5319 an alike. Make read_key_sequence aware of that. */
5320 if (timers_run != old_timers_run
5321 && waiting_for_user_input_p == -1
5322 && (old_buffer != current_buffer
5323 || !EQ (old_window, selected_window)))
5324 record_asynch_buffer_change ();
5326 if (leave)
5327 break;
5330 /* If there is unread keyboard input, also return. */
5331 if (read_kbd != 0
5332 && requeued_events_pending_p ())
5333 break;
5335 /* If we are not checking for keyboard input now,
5336 do process events (but don't run any timers).
5337 This is so that X events will be processed.
5338 Otherwise they may have to wait until polling takes place.
5339 That would causes delays in pasting selections, for example.
5341 (We used to do this only if wait_for_cell.) */
5342 if (read_kbd == 0 && detect_input_pending ())
5344 swallow_events (do_display);
5345 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5346 if (detect_input_pending ())
5347 break;
5348 #endif
5351 /* Exit now if the cell we're waiting for became non-nil. */
5352 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5353 break;
5355 #ifdef USABLE_SIGIO
5356 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5357 go read it. This can happen with X on BSD after logging out.
5358 In that case, there really is no input and no SIGIO,
5359 but select says there is input. */
5361 if (read_kbd && interrupt_input
5362 && keyboard_bit_set (&Available) && ! noninteractive)
5363 handle_input_available_signal (SIGIO);
5364 #endif
5366 /* If checking input just got us a size-change event from X,
5367 obey it now if we should. */
5368 if (read_kbd || ! NILP (wait_for_cell))
5369 do_pending_window_change (0);
5371 /* Check for data from a process. */
5372 if (no_avail || nfds == 0)
5373 continue;
5375 for (channel = 0; channel <= max_input_desc; ++channel)
5377 struct fd_callback_data *d = &fd_callback_info[channel];
5378 if (d->func
5379 && ((d->condition & FOR_READ
5380 && FD_ISSET (channel, &Available))
5381 || (d->condition & FOR_WRITE
5382 && FD_ISSET (channel, &write_mask))))
5383 d->func (channel, d->data);
5386 for (channel = 0; channel <= max_process_desc; channel++)
5388 if (FD_ISSET (channel, &Available)
5389 && FD_ISSET (channel, &non_keyboard_wait_mask)
5390 && !FD_ISSET (channel, &non_process_wait_mask))
5392 int nread;
5394 /* If waiting for this channel, arrange to return as
5395 soon as no more input to be processed. No more
5396 waiting. */
5397 proc = chan_process[channel];
5398 if (NILP (proc))
5399 continue;
5401 /* If this is a server stream socket, accept connection. */
5402 if (EQ (XPROCESS (proc)->status, Qlisten))
5404 server_accept_connection (proc, channel);
5405 continue;
5408 /* Read data from the process, starting with our
5409 buffered-ahead character if we have one. */
5411 nread = read_process_output (proc, channel);
5412 if ((!wait_proc || wait_proc == XPROCESS (proc))
5413 && got_some_output < nread)
5414 got_some_output = nread;
5415 if (nread > 0)
5417 /* Vacuum up any leftovers without waiting. */
5418 if (wait_proc == XPROCESS (proc))
5419 wait = MINIMUM;
5420 /* Since read_process_output can run a filter,
5421 which can call accept-process-output,
5422 don't try to read from any other processes
5423 before doing the select again. */
5424 FD_ZERO (&Available);
5426 if (do_display)
5427 redisplay_preserve_echo_area (12);
5429 #ifdef EWOULDBLOCK
5430 else if (nread == -1 && errno == EWOULDBLOCK)
5432 #endif
5433 else if (nread == -1 && errno == EAGAIN)
5435 #ifdef WINDOWSNT
5436 /* FIXME: Is this special case still needed? */
5437 /* Note that we cannot distinguish between no input
5438 available now and a closed pipe.
5439 With luck, a closed pipe will be accompanied by
5440 subprocess termination and SIGCHLD. */
5441 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5442 && !PIPECONN_P (proc))
5444 #endif
5445 #ifdef HAVE_PTYS
5446 /* On some OSs with ptys, when the process on one end of
5447 a pty exits, the other end gets an error reading with
5448 errno = EIO instead of getting an EOF (0 bytes read).
5449 Therefore, if we get an error reading and errno =
5450 EIO, just continue, because the child process has
5451 exited and should clean itself up soon (e.g. when we
5452 get a SIGCHLD). */
5453 else if (nread == -1 && errno == EIO)
5455 struct Lisp_Process *p = XPROCESS (proc);
5457 /* Clear the descriptor now, so we only raise the
5458 signal once. */
5459 FD_CLR (channel, &input_wait_mask);
5460 FD_CLR (channel, &non_keyboard_wait_mask);
5462 if (p->pid == -2)
5464 /* If the EIO occurs on a pty, the SIGCHLD handler's
5465 waitpid call will not find the process object to
5466 delete. Do it here. */
5467 p->tick = ++process_tick;
5468 pset_status (p, Qfailed);
5471 #endif /* HAVE_PTYS */
5472 /* If we can detect process termination, don't consider the
5473 process gone just because its pipe is closed. */
5474 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5475 && !PIPECONN_P (proc))
5477 else if (nread == 0 && PIPECONN_P (proc))
5479 /* Preserve status of processes already terminated. */
5480 XPROCESS (proc)->tick = ++process_tick;
5481 deactivate_process (proc);
5482 if (EQ (XPROCESS (proc)->status, Qrun))
5483 pset_status (XPROCESS (proc),
5484 list2 (Qexit, make_number (0)));
5486 else
5488 /* Preserve status of processes already terminated. */
5489 XPROCESS (proc)->tick = ++process_tick;
5490 deactivate_process (proc);
5491 if (XPROCESS (proc)->raw_status_new)
5492 update_status (XPROCESS (proc));
5493 if (EQ (XPROCESS (proc)->status, Qrun))
5494 pset_status (XPROCESS (proc),
5495 list2 (Qexit, make_number (256)));
5498 #ifdef NON_BLOCKING_CONNECT
5499 if (FD_ISSET (channel, &Writeok)
5500 && FD_ISSET (channel, &connect_wait_mask))
5502 struct Lisp_Process *p;
5504 FD_CLR (channel, &connect_wait_mask);
5505 FD_CLR (channel, &write_mask);
5506 if (--num_pending_connects < 0)
5507 emacs_abort ();
5509 proc = chan_process[channel];
5510 if (NILP (proc))
5511 continue;
5513 p = XPROCESS (proc);
5515 #ifdef GNU_LINUX
5516 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5517 So only use it on systems where it is known to work. */
5519 socklen_t xlen = sizeof (xerrno);
5520 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5521 xerrno = errno;
5523 #else
5525 struct sockaddr pname;
5526 socklen_t pnamelen = sizeof (pname);
5528 /* If connection failed, getpeername will fail. */
5529 xerrno = 0;
5530 if (getpeername (channel, &pname, &pnamelen) < 0)
5532 /* Obtain connect failure code through error slippage. */
5533 char dummy;
5534 xerrno = errno;
5535 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5536 xerrno = errno;
5539 #endif
5540 if (xerrno)
5542 p->tick = ++process_tick;
5543 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5544 deactivate_process (proc);
5546 else
5548 #ifdef HAVE_GNUTLS
5549 /* If we have an incompletely set up TLS connection,
5550 then defer the sentinel signalling until
5551 later. */
5552 if (NILP (p->gnutls_boot_parameters)
5553 && !p->gnutls_p)
5554 #endif
5556 pset_status (p, Qrun);
5557 /* Execute the sentinel here. If we had relied on
5558 status_notify to do it later, it will read input
5559 from the process before calling the sentinel. */
5560 exec_sentinel (proc, build_string ("open\n"));
5563 if (0 <= p->infd && !EQ (p->filter, Qt)
5564 && !EQ (p->command, Qt))
5566 FD_SET (p->infd, &input_wait_mask);
5567 FD_SET (p->infd, &non_keyboard_wait_mask);
5571 #endif /* NON_BLOCKING_CONNECT */
5572 } /* End for each file descriptor. */
5573 } /* End while exit conditions not met. */
5575 unbind_to (count, Qnil);
5577 /* If calling from keyboard input, do not quit
5578 since we want to return C-g as an input character.
5579 Otherwise, do pending quit if requested. */
5580 if (read_kbd >= 0)
5582 /* Prevent input_pending from remaining set if we quit. */
5583 clear_input_pending ();
5584 QUIT;
5587 return got_some_output;
5590 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5592 static Lisp_Object
5593 read_process_output_call (Lisp_Object fun_and_args)
5595 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5598 static Lisp_Object
5599 read_process_output_error_handler (Lisp_Object error_val)
5601 cmd_error_internal (error_val, "error in process filter: ");
5602 Vinhibit_quit = Qt;
5603 update_echo_area ();
5604 Fsleep_for (make_number (2), Qnil);
5605 return Qt;
5608 static void
5609 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5610 ssize_t nbytes,
5611 struct coding_system *coding);
5613 /* Read pending output from the process channel,
5614 starting with our buffered-ahead character if we have one.
5615 Yield number of decoded characters read.
5617 This function reads at most 4096 characters.
5618 If you want to read all available subprocess output,
5619 you must call it repeatedly until it returns zero.
5621 The characters read are decoded according to PROC's coding-system
5622 for decoding. */
5624 static int
5625 read_process_output (Lisp_Object proc, int channel)
5627 ssize_t nbytes;
5628 struct Lisp_Process *p = XPROCESS (proc);
5629 struct coding_system *coding = proc_decode_coding_system[channel];
5630 int carryover = p->decoding_carryover;
5631 enum { readmax = 4096 };
5632 ptrdiff_t count = SPECPDL_INDEX ();
5633 Lisp_Object odeactivate;
5634 char chars[sizeof coding->carryover + readmax];
5636 if (carryover)
5637 /* See the comment above. */
5638 memcpy (chars, SDATA (p->decoding_buf), carryover);
5640 #ifdef DATAGRAM_SOCKETS
5641 /* We have a working select, so proc_buffered_char is always -1. */
5642 if (DATAGRAM_CHAN_P (channel))
5644 socklen_t len = datagram_address[channel].len;
5645 nbytes = recvfrom (channel, chars + carryover, readmax,
5646 0, datagram_address[channel].sa, &len);
5648 else
5649 #endif
5651 bool buffered = proc_buffered_char[channel] >= 0;
5652 if (buffered)
5654 chars[carryover] = proc_buffered_char[channel];
5655 proc_buffered_char[channel] = -1;
5657 #ifdef HAVE_GNUTLS
5658 if (p->gnutls_p && p->gnutls_state)
5659 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5660 readmax - buffered);
5661 else
5662 #endif
5663 nbytes = emacs_read (channel, chars + carryover + buffered,
5664 readmax - buffered);
5665 if (nbytes > 0 && p->adaptive_read_buffering)
5667 int delay = p->read_output_delay;
5668 if (nbytes < 256)
5670 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5672 if (delay == 0)
5673 process_output_delay_count++;
5674 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5677 else if (delay > 0 && nbytes == readmax - buffered)
5679 delay -= READ_OUTPUT_DELAY_INCREMENT;
5680 if (delay == 0)
5681 process_output_delay_count--;
5683 p->read_output_delay = delay;
5684 if (delay)
5686 p->read_output_skip = 1;
5687 process_output_skip = 1;
5690 nbytes += buffered;
5691 nbytes += buffered && nbytes <= 0;
5694 p->decoding_carryover = 0;
5696 /* At this point, NBYTES holds number of bytes just received
5697 (including the one in proc_buffered_char[channel]). */
5698 if (nbytes <= 0)
5700 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5701 return nbytes;
5702 coding->mode |= CODING_MODE_LAST_BLOCK;
5705 /* Now set NBYTES how many bytes we must decode. */
5706 nbytes += carryover;
5708 odeactivate = Vdeactivate_mark;
5709 /* There's no good reason to let process filters change the current
5710 buffer, and many callers of accept-process-output, sit-for, and
5711 friends don't expect current-buffer to be changed from under them. */
5712 record_unwind_current_buffer ();
5714 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5716 /* Handling the process output should not deactivate the mark. */
5717 Vdeactivate_mark = odeactivate;
5719 unbind_to (count, Qnil);
5720 return nbytes;
5723 static void
5724 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5725 ssize_t nbytes,
5726 struct coding_system *coding)
5728 Lisp_Object outstream = p->filter;
5729 Lisp_Object text;
5730 bool outer_running_asynch_code = running_asynch_code;
5731 int waiting = waiting_for_user_input_p;
5733 #if 0
5734 Lisp_Object obuffer, okeymap;
5735 XSETBUFFER (obuffer, current_buffer);
5736 okeymap = BVAR (current_buffer, keymap);
5737 #endif
5739 /* We inhibit quit here instead of just catching it so that
5740 hitting ^G when a filter happens to be running won't screw
5741 it up. */
5742 specbind (Qinhibit_quit, Qt);
5743 specbind (Qlast_nonmenu_event, Qt);
5745 /* In case we get recursively called,
5746 and we already saved the match data nonrecursively,
5747 save the same match data in safely recursive fashion. */
5748 if (outer_running_asynch_code)
5750 Lisp_Object tem;
5751 /* Don't clobber the CURRENT match data, either! */
5752 tem = Fmatch_data (Qnil, Qnil, Qnil);
5753 restore_search_regs ();
5754 record_unwind_save_match_data ();
5755 Fset_match_data (tem, Qt);
5758 /* For speed, if a search happens within this code,
5759 save the match data in a special nonrecursive fashion. */
5760 running_asynch_code = 1;
5762 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5763 text = coding->dst_object;
5764 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5765 /* A new coding system might be found. */
5766 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5768 pset_decode_coding_system (p, Vlast_coding_system_used);
5770 /* Don't call setup_coding_system for
5771 proc_decode_coding_system[channel] here. It is done in
5772 detect_coding called via decode_coding above. */
5774 /* If a coding system for encoding is not yet decided, we set
5775 it as the same as coding-system for decoding.
5777 But, before doing that we must check if
5778 proc_encode_coding_system[p->outfd] surely points to a
5779 valid memory because p->outfd will be changed once EOF is
5780 sent to the process. */
5781 if (NILP (p->encode_coding_system) && p->outfd >= 0
5782 && proc_encode_coding_system[p->outfd])
5784 pset_encode_coding_system
5785 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5786 setup_coding_system (p->encode_coding_system,
5787 proc_encode_coding_system[p->outfd]);
5791 if (coding->carryover_bytes > 0)
5793 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5794 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5795 memcpy (SDATA (p->decoding_buf), coding->carryover,
5796 coding->carryover_bytes);
5797 p->decoding_carryover = coding->carryover_bytes;
5799 if (SBYTES (text) > 0)
5800 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5801 sometimes it's simply wrong to wrap (e.g. when called from
5802 accept-process-output). */
5803 internal_condition_case_1 (read_process_output_call,
5804 list3 (outstream, make_lisp_proc (p), text),
5805 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5806 read_process_output_error_handler);
5808 /* If we saved the match data nonrecursively, restore it now. */
5809 restore_search_regs ();
5810 running_asynch_code = outer_running_asynch_code;
5812 /* Restore waiting_for_user_input_p as it was
5813 when we were called, in case the filter clobbered it. */
5814 waiting_for_user_input_p = waiting;
5816 #if 0 /* Call record_asynch_buffer_change unconditionally,
5817 because we might have changed minor modes or other things
5818 that affect key bindings. */
5819 if (! EQ (Fcurrent_buffer (), obuffer)
5820 || ! EQ (current_buffer->keymap, okeymap))
5821 #endif
5822 /* But do it only if the caller is actually going to read events.
5823 Otherwise there's no need to make him wake up, and it could
5824 cause trouble (for example it would make sit_for return). */
5825 if (waiting_for_user_input_p == -1)
5826 record_asynch_buffer_change ();
5829 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5830 Sinternal_default_process_filter, 2, 2, 0,
5831 doc: /* Function used as default process filter.
5832 This inserts the process's output into its buffer, if there is one.
5833 Otherwise it discards the output. */)
5834 (Lisp_Object proc, Lisp_Object text)
5836 struct Lisp_Process *p;
5837 ptrdiff_t opoint;
5839 CHECK_PROCESS (proc);
5840 p = XPROCESS (proc);
5841 CHECK_STRING (text);
5843 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5845 Lisp_Object old_read_only;
5846 ptrdiff_t old_begv, old_zv;
5847 ptrdiff_t old_begv_byte, old_zv_byte;
5848 ptrdiff_t before, before_byte;
5849 ptrdiff_t opoint_byte;
5850 struct buffer *b;
5852 Fset_buffer (p->buffer);
5853 opoint = PT;
5854 opoint_byte = PT_BYTE;
5855 old_read_only = BVAR (current_buffer, read_only);
5856 old_begv = BEGV;
5857 old_zv = ZV;
5858 old_begv_byte = BEGV_BYTE;
5859 old_zv_byte = ZV_BYTE;
5861 bset_read_only (current_buffer, Qnil);
5863 /* Insert new output into buffer at the current end-of-output
5864 marker, thus preserving logical ordering of input and output. */
5865 if (XMARKER (p->mark)->buffer)
5866 set_point_from_marker (p->mark);
5867 else
5868 SET_PT_BOTH (ZV, ZV_BYTE);
5869 before = PT;
5870 before_byte = PT_BYTE;
5872 /* If the output marker is outside of the visible region, save
5873 the restriction and widen. */
5874 if (! (BEGV <= PT && PT <= ZV))
5875 Fwiden ();
5877 /* Adjust the multibyteness of TEXT to that of the buffer. */
5878 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5879 != ! STRING_MULTIBYTE (text))
5880 text = (STRING_MULTIBYTE (text)
5881 ? Fstring_as_unibyte (text)
5882 : Fstring_to_multibyte (text));
5883 /* Insert before markers in case we are inserting where
5884 the buffer's mark is, and the user's next command is Meta-y. */
5885 insert_from_string_before_markers (text, 0, 0,
5886 SCHARS (text), SBYTES (text), 0);
5888 /* Make sure the process marker's position is valid when the
5889 process buffer is changed in the signal_after_change above.
5890 W3 is known to do that. */
5891 if (BUFFERP (p->buffer)
5892 && (b = XBUFFER (p->buffer), b != current_buffer))
5893 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5894 else
5895 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5897 update_mode_lines = 23;
5899 /* Make sure opoint and the old restrictions
5900 float ahead of any new text just as point would. */
5901 if (opoint >= before)
5903 opoint += PT - before;
5904 opoint_byte += PT_BYTE - before_byte;
5906 if (old_begv > before)
5908 old_begv += PT - before;
5909 old_begv_byte += PT_BYTE - before_byte;
5911 if (old_zv >= before)
5913 old_zv += PT - before;
5914 old_zv_byte += PT_BYTE - before_byte;
5917 /* If the restriction isn't what it should be, set it. */
5918 if (old_begv != BEGV || old_zv != ZV)
5919 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5921 bset_read_only (current_buffer, old_read_only);
5922 SET_PT_BOTH (opoint, opoint_byte);
5924 return Qnil;
5927 /* Sending data to subprocess. */
5929 /* In send_process, when a write fails temporarily,
5930 wait_reading_process_output is called. It may execute user code,
5931 e.g. timers, that attempts to write new data to the same process.
5932 We must ensure that data is sent in the right order, and not
5933 interspersed half-completed with other writes (Bug#10815). This is
5934 handled by the write_queue element of struct process. It is a list
5935 with each entry having the form
5937 (string . (offset . length))
5939 where STRING is a lisp string, OFFSET is the offset into the
5940 string's byte sequence from which we should begin to send, and
5941 LENGTH is the number of bytes left to send. */
5943 /* Create a new entry in write_queue.
5944 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5945 BUF is a pointer to the string sequence of the input_obj or a C
5946 string in case of Qt or Qnil. */
5948 static void
5949 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5950 const char *buf, ptrdiff_t len, bool front)
5952 ptrdiff_t offset;
5953 Lisp_Object entry, obj;
5955 if (STRINGP (input_obj))
5957 offset = buf - SSDATA (input_obj);
5958 obj = input_obj;
5960 else
5962 offset = 0;
5963 obj = make_unibyte_string (buf, len);
5966 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5968 if (front)
5969 pset_write_queue (p, Fcons (entry, p->write_queue));
5970 else
5971 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5974 /* Remove the first element in the write_queue of process P, put its
5975 contents in OBJ, BUF and LEN, and return true. If the
5976 write_queue is empty, return false. */
5978 static bool
5979 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5980 const char **buf, ptrdiff_t *len)
5982 Lisp_Object entry, offset_length;
5983 ptrdiff_t offset;
5985 if (NILP (p->write_queue))
5986 return 0;
5988 entry = XCAR (p->write_queue);
5989 pset_write_queue (p, XCDR (p->write_queue));
5991 *obj = XCAR (entry);
5992 offset_length = XCDR (entry);
5994 *len = XINT (XCDR (offset_length));
5995 offset = XINT (XCAR (offset_length));
5996 *buf = SSDATA (*obj) + offset;
5998 return 1;
6001 /* Send some data to process PROC.
6002 BUF is the beginning of the data; LEN is the number of characters.
6003 OBJECT is the Lisp object that the data comes from. If OBJECT is
6004 nil or t, it means that the data comes from C string.
6006 If OBJECT is not nil, the data is encoded by PROC's coding-system
6007 for encoding before it is sent.
6009 This function can evaluate Lisp code and can garbage collect. */
6011 static void
6012 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6013 Lisp_Object object)
6015 struct Lisp_Process *p = XPROCESS (proc);
6016 ssize_t rv;
6017 struct coding_system *coding;
6019 if (NETCONN_P (proc))
6021 wait_while_connecting (proc);
6022 wait_for_tls_negotiation (proc);
6025 if (p->raw_status_new)
6026 update_status (p);
6027 if (! EQ (p->status, Qrun))
6028 error ("Process %s not running", SDATA (p->name));
6029 if (p->outfd < 0)
6030 error ("Output file descriptor of %s is closed", SDATA (p->name));
6032 coding = proc_encode_coding_system[p->outfd];
6033 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6035 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6036 || (BUFFERP (object)
6037 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6038 || EQ (object, Qt))
6040 pset_encode_coding_system
6041 (p, complement_process_encoding_system (p->encode_coding_system));
6042 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6044 /* The coding system for encoding was changed to raw-text
6045 because we sent a unibyte text previously. Now we are
6046 sending a multibyte text, thus we must encode it by the
6047 original coding system specified for the current process.
6049 Another reason we come here is that the coding system
6050 was just complemented and a new one was returned by
6051 complement_process_encoding_system. */
6052 setup_coding_system (p->encode_coding_system, coding);
6053 Vlast_coding_system_used = p->encode_coding_system;
6055 coding->src_multibyte = 1;
6057 else
6059 coding->src_multibyte = 0;
6060 /* For sending a unibyte text, character code conversion should
6061 not take place but EOL conversion should. So, setup raw-text
6062 or one of the subsidiary if we have not yet done it. */
6063 if (CODING_REQUIRE_ENCODING (coding))
6065 if (CODING_REQUIRE_FLUSHING (coding))
6067 /* But, before changing the coding, we must flush out data. */
6068 coding->mode |= CODING_MODE_LAST_BLOCK;
6069 send_process (proc, "", 0, Qt);
6070 coding->mode &= CODING_MODE_LAST_BLOCK;
6072 setup_coding_system (raw_text_coding_system
6073 (Vlast_coding_system_used),
6074 coding);
6075 coding->src_multibyte = 0;
6078 coding->dst_multibyte = 0;
6080 if (CODING_REQUIRE_ENCODING (coding))
6082 coding->dst_object = Qt;
6083 if (BUFFERP (object))
6085 ptrdiff_t from_byte, from, to;
6086 ptrdiff_t save_pt, save_pt_byte;
6087 struct buffer *cur = current_buffer;
6089 set_buffer_internal (XBUFFER (object));
6090 save_pt = PT, save_pt_byte = PT_BYTE;
6092 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6093 from = BYTE_TO_CHAR (from_byte);
6094 to = BYTE_TO_CHAR (from_byte + len);
6095 TEMP_SET_PT_BOTH (from, from_byte);
6096 encode_coding_object (coding, object, from, from_byte,
6097 to, from_byte + len, Qt);
6098 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6099 set_buffer_internal (cur);
6101 else if (STRINGP (object))
6103 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6104 SBYTES (object), Qt);
6106 else
6108 coding->dst_object = make_unibyte_string (buf, len);
6109 coding->produced = len;
6112 len = coding->produced;
6113 object = coding->dst_object;
6114 buf = SSDATA (object);
6117 /* If there is already data in the write_queue, put the new data
6118 in the back of queue. Otherwise, ignore it. */
6119 if (!NILP (p->write_queue))
6120 write_queue_push (p, object, buf, len, 0);
6122 do /* while !NILP (p->write_queue) */
6124 ptrdiff_t cur_len = -1;
6125 const char *cur_buf;
6126 Lisp_Object cur_object;
6128 /* If write_queue is empty, ignore it. */
6129 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6131 cur_len = len;
6132 cur_buf = buf;
6133 cur_object = object;
6136 while (cur_len > 0)
6138 /* Send this batch, using one or more write calls. */
6139 ptrdiff_t written = 0;
6140 int outfd = p->outfd;
6141 #ifdef DATAGRAM_SOCKETS
6142 if (DATAGRAM_CHAN_P (outfd))
6144 rv = sendto (outfd, cur_buf, cur_len,
6145 0, datagram_address[outfd].sa,
6146 datagram_address[outfd].len);
6147 if (rv >= 0)
6148 written = rv;
6149 else if (errno == EMSGSIZE)
6150 report_file_error ("Sending datagram", proc);
6152 else
6153 #endif
6155 #ifdef HAVE_GNUTLS
6156 if (p->gnutls_p && p->gnutls_state)
6157 written = emacs_gnutls_write (p, cur_buf, cur_len);
6158 else
6159 #endif
6160 written = emacs_write_sig (outfd, cur_buf, cur_len);
6161 rv = (written ? 0 : -1);
6162 if (p->read_output_delay > 0
6163 && p->adaptive_read_buffering == 1)
6165 p->read_output_delay = 0;
6166 process_output_delay_count--;
6167 p->read_output_skip = 0;
6171 if (rv < 0)
6173 if (errno == EAGAIN
6174 #ifdef EWOULDBLOCK
6175 || errno == EWOULDBLOCK
6176 #endif
6178 /* Buffer is full. Wait, accepting input;
6179 that may allow the program
6180 to finish doing output and read more. */
6182 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6183 /* A gross hack to work around a bug in FreeBSD.
6184 In the following sequence, read(2) returns
6185 bogus data:
6187 write(2) 1022 bytes
6188 write(2) 954 bytes, get EAGAIN
6189 read(2) 1024 bytes in process_read_output
6190 read(2) 11 bytes in process_read_output
6192 That is, read(2) returns more bytes than have
6193 ever been written successfully. The 1033 bytes
6194 read are the 1022 bytes written successfully
6195 after processing (for example with CRs added if
6196 the terminal is set up that way which it is
6197 here). The same bytes will be seen again in a
6198 later read(2), without the CRs. */
6200 if (errno == EAGAIN)
6202 int flags = FWRITE;
6203 ioctl (p->outfd, TIOCFLUSH, &flags);
6205 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6207 /* Put what we should have written in wait_queue. */
6208 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6209 wait_reading_process_output (0, 20 * 1000 * 1000,
6210 0, 0, Qnil, NULL, 0);
6211 /* Reread queue, to see what is left. */
6212 break;
6214 else if (errno == EPIPE)
6216 p->raw_status_new = 0;
6217 pset_status (p, list2 (Qexit, make_number (256)));
6218 p->tick = ++process_tick;
6219 deactivate_process (proc);
6220 error ("process %s no longer connected to pipe; closed it",
6221 SDATA (p->name));
6223 else
6224 /* This is a real error. */
6225 report_file_error ("Writing to process", proc);
6227 cur_buf += written;
6228 cur_len -= written;
6231 while (!NILP (p->write_queue));
6234 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6235 3, 3, 0,
6236 doc: /* Send current contents of region as input to PROCESS.
6237 PROCESS may be a process, a buffer, the name of a process or buffer, or
6238 nil, indicating the current buffer's process.
6239 Called from program, takes three arguments, PROCESS, START and END.
6240 If the region is more than 500 characters long,
6241 it is sent in several bunches. This may happen even for shorter regions.
6242 Output from processes can arrive in between bunches.
6244 If PROCESS is a non-blocking network process that hasn't been fully
6245 set up yet, this function will block until socket setup has completed. */)
6246 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6248 Lisp_Object proc = get_process (process);
6249 ptrdiff_t start_byte, end_byte;
6251 validate_region (&start, &end);
6253 start_byte = CHAR_TO_BYTE (XINT (start));
6254 end_byte = CHAR_TO_BYTE (XINT (end));
6256 if (XINT (start) < GPT && XINT (end) > GPT)
6257 move_gap_both (XINT (start), start_byte);
6259 if (NETCONN_P (proc))
6260 wait_while_connecting (proc);
6262 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6263 end_byte - start_byte, Fcurrent_buffer ());
6265 return Qnil;
6268 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6269 2, 2, 0,
6270 doc: /* Send PROCESS the contents of STRING as input.
6271 PROCESS may be a process, a buffer, the name of a process or buffer, or
6272 nil, indicating the current buffer's process.
6273 If STRING is more than 500 characters long,
6274 it is sent in several bunches. This may happen even for shorter strings.
6275 Output from processes can arrive in between bunches.
6277 If PROCESS is a non-blocking network process that hasn't been fully
6278 set up yet, this function will block until socket setup has completed. */)
6279 (Lisp_Object process, Lisp_Object string)
6281 CHECK_STRING (string);
6282 Lisp_Object proc = get_process (process);
6283 send_process (proc, SSDATA (string),
6284 SBYTES (string), string);
6285 return Qnil;
6288 /* Return the foreground process group for the tty/pty that
6289 the process P uses. */
6290 static pid_t
6291 emacs_get_tty_pgrp (struct Lisp_Process *p)
6293 pid_t gid = -1;
6295 #ifdef TIOCGPGRP
6296 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6298 int fd;
6299 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6300 master side. Try the slave side. */
6301 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6303 if (fd != -1)
6305 ioctl (fd, TIOCGPGRP, &gid);
6306 emacs_close (fd);
6309 #endif /* defined (TIOCGPGRP ) */
6311 return gid;
6314 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6315 Sprocess_running_child_p, 0, 1, 0,
6316 doc: /* Return non-nil if PROCESS has given the terminal to a
6317 child. If the operating system does not make it possible to find out,
6318 return t. If we can find out, return the numeric ID of the foreground
6319 process group. */)
6320 (Lisp_Object process)
6322 /* Initialize in case ioctl doesn't exist or gives an error,
6323 in a way that will cause returning t. */
6324 Lisp_Object proc = get_process (process);
6325 struct Lisp_Process *p = XPROCESS (proc);
6327 if (!EQ (p->type, Qreal))
6328 error ("Process %s is not a subprocess",
6329 SDATA (p->name));
6330 if (p->infd < 0)
6331 error ("Process %s is not active",
6332 SDATA (p->name));
6334 pid_t gid = emacs_get_tty_pgrp (p);
6336 if (gid == p->pid)
6337 return Qnil;
6338 if (gid != -1)
6339 return make_number (gid);
6340 return Qt;
6343 /* Send a signal number SIGNO to PROCESS.
6344 If CURRENT_GROUP is t, that means send to the process group
6345 that currently owns the terminal being used to communicate with PROCESS.
6346 This is used for various commands in shell mode.
6347 If CURRENT_GROUP is lambda, that means send to the process group
6348 that currently owns the terminal, but only if it is NOT the shell itself.
6350 If NOMSG is false, insert signal-announcements into process's buffers
6351 right away.
6353 If we can, we try to signal PROCESS by sending control characters
6354 down the pty. This allows us to signal inferiors who have changed
6355 their uid, for which kill would return an EPERM error. */
6357 static void
6358 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6359 bool nomsg)
6361 Lisp_Object proc;
6362 struct Lisp_Process *p;
6363 pid_t gid;
6364 bool no_pgrp = 0;
6366 proc = get_process (process);
6367 p = XPROCESS (proc);
6369 if (!EQ (p->type, Qreal))
6370 error ("Process %s is not a subprocess",
6371 SDATA (p->name));
6372 if (p->infd < 0)
6373 error ("Process %s is not active",
6374 SDATA (p->name));
6376 if (!p->pty_flag)
6377 current_group = Qnil;
6379 /* If we are using pgrps, get a pgrp number and make it negative. */
6380 if (NILP (current_group))
6381 /* Send the signal to the shell's process group. */
6382 gid = p->pid;
6383 else
6385 #ifdef SIGNALS_VIA_CHARACTERS
6386 /* If possible, send signals to the entire pgrp
6387 by sending an input character to it. */
6389 struct termios t;
6390 cc_t *sig_char = NULL;
6392 tcgetattr (p->infd, &t);
6394 switch (signo)
6396 case SIGINT:
6397 sig_char = &t.c_cc[VINTR];
6398 break;
6400 case SIGQUIT:
6401 sig_char = &t.c_cc[VQUIT];
6402 break;
6404 case SIGTSTP:
6405 #ifdef VSWTCH
6406 sig_char = &t.c_cc[VSWTCH];
6407 #else
6408 sig_char = &t.c_cc[VSUSP];
6409 #endif
6410 break;
6413 if (sig_char && *sig_char != CDISABLE)
6415 send_process (proc, (char *) sig_char, 1, Qnil);
6416 return;
6418 /* If we can't send the signal with a character,
6419 fall through and send it another way. */
6421 /* The code above may fall through if it can't
6422 handle the signal. */
6423 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6425 #ifdef TIOCGPGRP
6426 /* Get the current pgrp using the tty itself, if we have that.
6427 Otherwise, use the pty to get the pgrp.
6428 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6429 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6430 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6431 His patch indicates that if TIOCGPGRP returns an error, then
6432 we should just assume that p->pid is also the process group id. */
6434 gid = emacs_get_tty_pgrp (p);
6436 if (gid == -1)
6437 /* If we can't get the information, assume
6438 the shell owns the tty. */
6439 gid = p->pid;
6441 /* It is not clear whether anything really can set GID to -1.
6442 Perhaps on some system one of those ioctls can or could do so.
6443 Or perhaps this is vestigial. */
6444 if (gid == -1)
6445 no_pgrp = 1;
6446 #else /* ! defined (TIOCGPGRP) */
6447 /* Can't select pgrps on this system, so we know that
6448 the child itself heads the pgrp. */
6449 gid = p->pid;
6450 #endif /* ! defined (TIOCGPGRP) */
6452 /* If current_group is lambda, and the shell owns the terminal,
6453 don't send any signal. */
6454 if (EQ (current_group, Qlambda) && gid == p->pid)
6455 return;
6458 #ifdef SIGCONT
6459 if (signo == SIGCONT)
6461 p->raw_status_new = 0;
6462 pset_status (p, Qrun);
6463 p->tick = ++process_tick;
6464 if (!nomsg)
6466 status_notify (NULL, NULL);
6467 redisplay_preserve_echo_area (13);
6470 #endif
6472 #ifdef TIOCSIGSEND
6473 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6474 We don't know whether the bug is fixed in later HP-UX versions. */
6475 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6476 return;
6477 #endif
6479 /* If we don't have process groups, send the signal to the immediate
6480 subprocess. That isn't really right, but it's better than any
6481 obvious alternative. */
6482 pid_t pid = no_pgrp ? gid : - gid;
6484 /* Do not kill an already-reaped process, as that could kill an
6485 innocent bystander that happens to have the same process ID. */
6486 sigset_t oldset;
6487 block_child_signal (&oldset);
6488 if (p->alive)
6489 kill (pid, signo);
6490 unblock_child_signal (&oldset);
6493 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6494 doc: /* Interrupt process PROCESS.
6495 PROCESS may be a process, a buffer, or the name of a process or buffer.
6496 No arg or nil means current buffer's process.
6497 Second arg CURRENT-GROUP non-nil means send signal to
6498 the current process-group of the process's controlling terminal
6499 rather than to the process's own process group.
6500 If the process is a shell, this means interrupt current subjob
6501 rather than the shell.
6503 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6504 don't send the signal. */)
6505 (Lisp_Object process, Lisp_Object current_group)
6507 process_send_signal (process, SIGINT, current_group, 0);
6508 return process;
6511 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6512 doc: /* Kill process PROCESS. May be process or name of one.
6513 See function `interrupt-process' for more details on usage. */)
6514 (Lisp_Object process, Lisp_Object current_group)
6516 process_send_signal (process, SIGKILL, current_group, 0);
6517 return process;
6520 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6521 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6522 See function `interrupt-process' for more details on usage. */)
6523 (Lisp_Object process, Lisp_Object current_group)
6525 process_send_signal (process, SIGQUIT, current_group, 0);
6526 return process;
6529 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6530 doc: /* Stop process PROCESS. May be process or name of one.
6531 See function `interrupt-process' for more details on usage.
6532 If PROCESS is a network or serial process, inhibit handling of incoming
6533 traffic. */)
6534 (Lisp_Object process, Lisp_Object current_group)
6536 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6537 || PIPECONN_P (process)))
6539 struct Lisp_Process *p;
6541 p = XPROCESS (process);
6542 if (NILP (p->command)
6543 && p->infd >= 0)
6545 FD_CLR (p->infd, &input_wait_mask);
6546 FD_CLR (p->infd, &non_keyboard_wait_mask);
6548 pset_command (p, Qt);
6549 return process;
6551 #ifndef SIGTSTP
6552 error ("No SIGTSTP support");
6553 #else
6554 process_send_signal (process, SIGTSTP, current_group, 0);
6555 #endif
6556 return process;
6559 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6560 doc: /* Continue process PROCESS. May be process or name of one.
6561 See function `interrupt-process' for more details on usage.
6562 If PROCESS is a network or serial process, resume handling of incoming
6563 traffic. */)
6564 (Lisp_Object process, Lisp_Object current_group)
6566 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6567 || PIPECONN_P (process)))
6569 struct Lisp_Process *p;
6571 p = XPROCESS (process);
6572 if (EQ (p->command, Qt)
6573 && p->infd >= 0
6574 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6576 FD_SET (p->infd, &input_wait_mask);
6577 FD_SET (p->infd, &non_keyboard_wait_mask);
6578 #ifdef WINDOWSNT
6579 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6580 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6581 #else /* not WINDOWSNT */
6582 tcflush (p->infd, TCIFLUSH);
6583 #endif /* not WINDOWSNT */
6585 pset_command (p, Qnil);
6586 return process;
6588 #ifdef SIGCONT
6589 process_send_signal (process, SIGCONT, current_group, 0);
6590 #else
6591 error ("No SIGCONT support");
6592 #endif
6593 return process;
6596 /* Return the integer value of the signal whose abbreviation is ABBR,
6597 or a negative number if there is no such signal. */
6598 static int
6599 abbr_to_signal (char const *name)
6601 int i, signo;
6602 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6604 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6605 name += 3;
6607 for (i = 0; i < sizeof sigbuf; i++)
6609 sigbuf[i] = c_toupper (name[i]);
6610 if (! sigbuf[i])
6611 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6614 return -1;
6617 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6618 2, 2, "sProcess (name or number): \nnSignal code: ",
6619 doc: /* Send PROCESS the signal with code SIGCODE.
6620 PROCESS may also be a number specifying the process id of the
6621 process to signal; in this case, the process need not be a child of
6622 this Emacs.
6623 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6624 (Lisp_Object process, Lisp_Object sigcode)
6626 pid_t pid;
6627 int signo;
6629 if (STRINGP (process))
6631 Lisp_Object tem = Fget_process (process);
6632 if (NILP (tem))
6634 Lisp_Object process_number
6635 = string_to_number (SSDATA (process), 10, 1);
6636 if (NUMBERP (process_number))
6637 tem = process_number;
6639 process = tem;
6641 else if (!NUMBERP (process))
6642 process = get_process (process);
6644 if (NILP (process))
6645 return process;
6647 if (NUMBERP (process))
6648 CONS_TO_INTEGER (process, pid_t, pid);
6649 else
6651 CHECK_PROCESS (process);
6652 pid = XPROCESS (process)->pid;
6653 if (pid <= 0)
6654 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6657 if (INTEGERP (sigcode))
6659 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6660 signo = XINT (sigcode);
6662 else
6664 char *name;
6666 CHECK_SYMBOL (sigcode);
6667 name = SSDATA (SYMBOL_NAME (sigcode));
6669 signo = abbr_to_signal (name);
6670 if (signo < 0)
6671 error ("Undefined signal name %s", name);
6674 return make_number (kill (pid, signo));
6677 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6678 doc: /* Make PROCESS see end-of-file in its input.
6679 EOF comes after any text already sent to it.
6680 PROCESS may be a process, a buffer, the name of a process or buffer, or
6681 nil, indicating the current buffer's process.
6682 If PROCESS is a network connection, or is a process communicating
6683 through a pipe (as opposed to a pty), then you cannot send any more
6684 text to PROCESS after you call this function.
6685 If PROCESS is a serial process, wait until all output written to the
6686 process has been transmitted to the serial port. */)
6687 (Lisp_Object process)
6689 Lisp_Object proc;
6690 struct coding_system *coding = NULL;
6691 int outfd;
6693 proc = get_process (process);
6695 if (NETCONN_P (proc))
6696 wait_while_connecting (proc);
6698 if (DATAGRAM_CONN_P (proc))
6699 return process;
6702 outfd = XPROCESS (proc)->outfd;
6703 if (outfd >= 0)
6704 coding = proc_encode_coding_system[outfd];
6706 /* Make sure the process is really alive. */
6707 if (XPROCESS (proc)->raw_status_new)
6708 update_status (XPROCESS (proc));
6709 if (! EQ (XPROCESS (proc)->status, Qrun))
6710 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6712 if (coding && CODING_REQUIRE_FLUSHING (coding))
6714 coding->mode |= CODING_MODE_LAST_BLOCK;
6715 send_process (proc, "", 0, Qnil);
6718 if (XPROCESS (proc)->pty_flag)
6719 send_process (proc, "\004", 1, Qnil);
6720 else if (EQ (XPROCESS (proc)->type, Qserial))
6722 #ifndef WINDOWSNT
6723 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6724 report_file_error ("Failed tcdrain", Qnil);
6725 #endif /* not WINDOWSNT */
6726 /* Do nothing on Windows because writes are blocking. */
6728 else
6730 struct Lisp_Process *p = XPROCESS (proc);
6731 int old_outfd = p->outfd;
6732 int new_outfd;
6734 #ifdef HAVE_SHUTDOWN
6735 /* If this is a network connection, or socketpair is used
6736 for communication with the subprocess, call shutdown to cause EOF.
6737 (In some old system, shutdown to socketpair doesn't work.
6738 Then we just can't win.) */
6739 if (0 <= old_outfd
6740 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6741 shutdown (old_outfd, 1);
6742 #endif
6743 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6744 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6745 if (new_outfd < 0)
6746 report_file_error ("Opening null device", Qnil);
6747 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6748 p->outfd = new_outfd;
6750 if (!proc_encode_coding_system[new_outfd])
6751 proc_encode_coding_system[new_outfd]
6752 = xmalloc (sizeof (struct coding_system));
6753 if (old_outfd >= 0)
6755 *proc_encode_coding_system[new_outfd]
6756 = *proc_encode_coding_system[old_outfd];
6757 memset (proc_encode_coding_system[old_outfd], 0,
6758 sizeof (struct coding_system));
6760 else
6761 setup_coding_system (p->encode_coding_system,
6762 proc_encode_coding_system[new_outfd]);
6764 return process;
6767 /* The main Emacs thread records child processes in three places:
6769 - Vprocess_alist, for asynchronous subprocesses, which are child
6770 processes visible to Lisp.
6772 - deleted_pid_list, for child processes invisible to Lisp,
6773 typically because of delete-process. These are recorded so that
6774 the processes can be reaped when they exit, so that the operating
6775 system's process table is not cluttered by zombies.
6777 - the local variable PID in Fcall_process, call_process_cleanup and
6778 call_process_kill, for synchronous subprocesses.
6779 record_unwind_protect is used to make sure this process is not
6780 forgotten: if the user interrupts call-process and the child
6781 process refuses to exit immediately even with two C-g's,
6782 call_process_kill adds PID's contents to deleted_pid_list before
6783 returning.
6785 The main Emacs thread invokes waitpid only on child processes that
6786 it creates and that have not been reaped. This avoid races on
6787 platforms such as GTK, where other threads create their own
6788 subprocesses which the main thread should not reap. For example,
6789 if the main thread attempted to reap an already-reaped child, it
6790 might inadvertently reap a GTK-created process that happened to
6791 have the same process ID. */
6793 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6794 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6795 keep track of its own children. GNUstep is similar. */
6797 static void dummy_handler (int sig) {}
6798 static signal_handler_t volatile lib_child_handler;
6800 /* Handle a SIGCHLD signal by looking for known child processes of
6801 Emacs whose status have changed. For each one found, record its
6802 new status.
6804 All we do is change the status; we do not run sentinels or print
6805 notifications. That is saved for the next time keyboard input is
6806 done, in order to avoid timing errors.
6808 ** WARNING: this can be called during garbage collection.
6809 Therefore, it must not be fooled by the presence of mark bits in
6810 Lisp objects.
6812 ** USG WARNING: Although it is not obvious from the documentation
6813 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6814 signal() before executing at least one wait(), otherwise the
6815 handler will be called again, resulting in an infinite loop. The
6816 relevant portion of the documentation reads "SIGCLD signals will be
6817 queued and the signal-catching function will be continually
6818 reentered until the queue is empty". Invoking signal() causes the
6819 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6820 Inc.
6822 ** Malloc WARNING: This should never call malloc either directly or
6823 indirectly; if it does, that is a bug. */
6825 static void
6826 handle_child_signal (int sig)
6828 Lisp_Object tail, proc;
6830 /* Find the process that signaled us, and record its status. */
6832 /* The process can have been deleted by Fdelete_process, or have
6833 been started asynchronously by Fcall_process. */
6834 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6836 bool all_pids_are_fixnums
6837 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6838 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6839 Lisp_Object head = XCAR (tail);
6840 Lisp_Object xpid;
6841 if (! CONSP (head))
6842 continue;
6843 xpid = XCAR (head);
6844 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6846 pid_t deleted_pid;
6847 if (INTEGERP (xpid))
6848 deleted_pid = XINT (xpid);
6849 else
6850 deleted_pid = XFLOAT_DATA (xpid);
6851 if (child_status_changed (deleted_pid, 0, 0))
6853 if (STRINGP (XCDR (head)))
6854 unlink (SSDATA (XCDR (head)));
6855 XSETCAR (tail, Qnil);
6860 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6861 FOR_EACH_PROCESS (tail, proc)
6863 struct Lisp_Process *p = XPROCESS (proc);
6864 int status;
6866 if (p->alive
6867 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6869 /* Change the status of the process that was found. */
6870 p->tick = ++process_tick;
6871 p->raw_status = status;
6872 p->raw_status_new = 1;
6874 /* If process has terminated, stop waiting for its output. */
6875 if (WIFSIGNALED (status) || WIFEXITED (status))
6877 bool clear_desc_flag = 0;
6878 p->alive = 0;
6879 if (p->infd >= 0)
6880 clear_desc_flag = 1;
6882 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6883 if (clear_desc_flag)
6885 FD_CLR (p->infd, &input_wait_mask);
6886 FD_CLR (p->infd, &non_keyboard_wait_mask);
6892 lib_child_handler (sig);
6893 #ifdef NS_IMPL_GNUSTEP
6894 /* NSTask in GNUstep sets its child handler each time it is called.
6895 So we must re-set ours. */
6896 catch_child_signal ();
6897 #endif
6900 static void
6901 deliver_child_signal (int sig)
6903 deliver_process_signal (sig, handle_child_signal);
6907 static Lisp_Object
6908 exec_sentinel_error_handler (Lisp_Object error_val)
6910 cmd_error_internal (error_val, "error in process sentinel: ");
6911 Vinhibit_quit = Qt;
6912 update_echo_area ();
6913 Fsleep_for (make_number (2), Qnil);
6914 return Qt;
6917 static void
6918 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6920 Lisp_Object sentinel, odeactivate;
6921 struct Lisp_Process *p = XPROCESS (proc);
6922 ptrdiff_t count = SPECPDL_INDEX ();
6923 bool outer_running_asynch_code = running_asynch_code;
6924 int waiting = waiting_for_user_input_p;
6926 if (inhibit_sentinels)
6927 return;
6929 odeactivate = Vdeactivate_mark;
6930 #if 0
6931 Lisp_Object obuffer, okeymap;
6932 XSETBUFFER (obuffer, current_buffer);
6933 okeymap = BVAR (current_buffer, keymap);
6934 #endif
6936 /* There's no good reason to let sentinels change the current
6937 buffer, and many callers of accept-process-output, sit-for, and
6938 friends don't expect current-buffer to be changed from under them. */
6939 record_unwind_current_buffer ();
6941 sentinel = p->sentinel;
6943 /* Inhibit quit so that random quits don't screw up a running filter. */
6944 specbind (Qinhibit_quit, Qt);
6945 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6947 /* In case we get recursively called,
6948 and we already saved the match data nonrecursively,
6949 save the same match data in safely recursive fashion. */
6950 if (outer_running_asynch_code)
6952 Lisp_Object tem;
6953 tem = Fmatch_data (Qnil, Qnil, Qnil);
6954 restore_search_regs ();
6955 record_unwind_save_match_data ();
6956 Fset_match_data (tem, Qt);
6959 /* For speed, if a search happens within this code,
6960 save the match data in a special nonrecursive fashion. */
6961 running_asynch_code = 1;
6963 internal_condition_case_1 (read_process_output_call,
6964 list3 (sentinel, proc, reason),
6965 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6966 exec_sentinel_error_handler);
6968 /* If we saved the match data nonrecursively, restore it now. */
6969 restore_search_regs ();
6970 running_asynch_code = outer_running_asynch_code;
6972 Vdeactivate_mark = odeactivate;
6974 /* Restore waiting_for_user_input_p as it was
6975 when we were called, in case the filter clobbered it. */
6976 waiting_for_user_input_p = waiting;
6978 #if 0
6979 if (! EQ (Fcurrent_buffer (), obuffer)
6980 || ! EQ (current_buffer->keymap, okeymap))
6981 #endif
6982 /* But do it only if the caller is actually going to read events.
6983 Otherwise there's no need to make him wake up, and it could
6984 cause trouble (for example it would make sit_for return). */
6985 if (waiting_for_user_input_p == -1)
6986 record_asynch_buffer_change ();
6988 unbind_to (count, Qnil);
6991 /* Report all recent events of a change in process status
6992 (either run the sentinel or output a message).
6993 This is usually done while Emacs is waiting for keyboard input
6994 but can be done at other times.
6996 Return positive if any input was received from WAIT_PROC (or from
6997 any process if WAIT_PROC is null), zero if input was attempted but
6998 none received, and negative if we didn't even try. */
7000 static int
7001 status_notify (struct Lisp_Process *deleting_process,
7002 struct Lisp_Process *wait_proc)
7004 Lisp_Object proc;
7005 Lisp_Object tail, msg;
7006 int got_some_output = -1;
7008 tail = Qnil;
7009 msg = Qnil;
7011 /* Set this now, so that if new processes are created by sentinels
7012 that we run, we get called again to handle their status changes. */
7013 update_tick = process_tick;
7015 FOR_EACH_PROCESS (tail, proc)
7017 Lisp_Object symbol;
7018 register struct Lisp_Process *p = XPROCESS (proc);
7020 if (p->tick != p->update_tick)
7022 p->update_tick = p->tick;
7024 /* If process is still active, read any output that remains. */
7025 while (! EQ (p->filter, Qt)
7026 && ! EQ (p->status, Qconnect)
7027 && ! EQ (p->status, Qlisten)
7028 /* Network or serial process not stopped: */
7029 && ! EQ (p->command, Qt)
7030 && p->infd >= 0
7031 && p != deleting_process)
7033 int nread = read_process_output (proc, p->infd);
7034 if ((!wait_proc || wait_proc == XPROCESS (proc))
7035 && got_some_output < nread)
7036 got_some_output = nread;
7037 if (nread <= 0)
7038 break;
7041 /* Get the text to use for the message. */
7042 if (p->raw_status_new)
7043 update_status (p);
7044 msg = status_message (p);
7046 /* If process is terminated, deactivate it or delete it. */
7047 symbol = p->status;
7048 if (CONSP (p->status))
7049 symbol = XCAR (p->status);
7051 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7052 || EQ (symbol, Qclosed))
7054 if (delete_exited_processes)
7055 remove_process (proc);
7056 else
7057 deactivate_process (proc);
7060 /* The actions above may have further incremented p->tick.
7061 So set p->update_tick again so that an error in the sentinel will
7062 not cause this code to be run again. */
7063 p->update_tick = p->tick;
7064 /* Now output the message suitably. */
7065 exec_sentinel (proc, msg);
7066 if (BUFFERP (p->buffer))
7067 /* In case it uses %s in mode-line-format. */
7068 bset_update_mode_line (XBUFFER (p->buffer));
7070 } /* end for */
7072 return got_some_output;
7075 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7076 Sinternal_default_process_sentinel, 2, 2, 0,
7077 doc: /* Function used as default sentinel for processes.
7078 This inserts a status message into the process's buffer, if there is one. */)
7079 (Lisp_Object proc, Lisp_Object msg)
7081 Lisp_Object buffer, symbol;
7082 struct Lisp_Process *p;
7083 CHECK_PROCESS (proc);
7084 p = XPROCESS (proc);
7085 buffer = p->buffer;
7086 symbol = p->status;
7087 if (CONSP (symbol))
7088 symbol = XCAR (symbol);
7090 if (!EQ (symbol, Qrun) && !NILP (buffer))
7092 Lisp_Object tem;
7093 struct buffer *old = current_buffer;
7094 ptrdiff_t opoint, opoint_byte;
7095 ptrdiff_t before, before_byte;
7097 /* Avoid error if buffer is deleted
7098 (probably that's why the process is dead, too). */
7099 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7100 return Qnil;
7101 Fset_buffer (buffer);
7103 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7104 msg = (code_convert_string_norecord
7105 (msg, Vlocale_coding_system, 1));
7107 opoint = PT;
7108 opoint_byte = PT_BYTE;
7109 /* Insert new output into buffer
7110 at the current end-of-output marker,
7111 thus preserving logical ordering of input and output. */
7112 if (XMARKER (p->mark)->buffer)
7113 Fgoto_char (p->mark);
7114 else
7115 SET_PT_BOTH (ZV, ZV_BYTE);
7117 before = PT;
7118 before_byte = PT_BYTE;
7120 tem = BVAR (current_buffer, read_only);
7121 bset_read_only (current_buffer, Qnil);
7122 insert_string ("\nProcess ");
7123 { /* FIXME: temporary kludge. */
7124 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7125 insert_string (" ");
7126 Finsert (1, &msg);
7127 bset_read_only (current_buffer, tem);
7128 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7130 if (opoint >= before)
7131 SET_PT_BOTH (opoint + (PT - before),
7132 opoint_byte + (PT_BYTE - before_byte));
7133 else
7134 SET_PT_BOTH (opoint, opoint_byte);
7136 set_buffer_internal (old);
7138 return Qnil;
7142 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7143 Sset_process_coding_system, 1, 3, 0,
7144 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7145 DECODING will be used to decode subprocess output and ENCODING to
7146 encode subprocess input. */)
7147 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7149 CHECK_PROCESS (process);
7151 struct Lisp_Process *p = XPROCESS (process);
7153 Fcheck_coding_system (decoding);
7154 Fcheck_coding_system (encoding);
7155 encoding = coding_inherit_eol_type (encoding, Qnil);
7156 pset_decode_coding_system (p, decoding);
7157 pset_encode_coding_system (p, encoding);
7159 /* If the sockets haven't been set up yet, the final setup part of
7160 this will be called asynchronously. */
7161 if (p->infd < 0 || p->outfd < 0)
7162 return Qnil;
7164 setup_process_coding_systems (process);
7166 return Qnil;
7169 DEFUN ("process-coding-system",
7170 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7171 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7172 (register Lisp_Object process)
7174 CHECK_PROCESS (process);
7175 return Fcons (XPROCESS (process)->decode_coding_system,
7176 XPROCESS (process)->encode_coding_system);
7179 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7180 Sset_process_filter_multibyte, 2, 2, 0,
7181 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7182 If FLAG is non-nil, the filter is given multibyte strings.
7183 If FLAG is nil, the filter is given unibyte strings. In this case,
7184 all character code conversion except for end-of-line conversion is
7185 suppressed. */)
7186 (Lisp_Object process, Lisp_Object flag)
7188 CHECK_PROCESS (process);
7190 struct Lisp_Process *p = XPROCESS (process);
7191 if (NILP (flag))
7192 pset_decode_coding_system
7193 (p, raw_text_coding_system (p->decode_coding_system));
7195 /* If the sockets haven't been set up yet, the final setup part of
7196 this will be called asynchronously. */
7197 if (p->infd < 0 || p->outfd < 0)
7198 return Qnil;
7200 setup_process_coding_systems (process);
7202 return Qnil;
7205 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7206 Sprocess_filter_multibyte_p, 1, 1, 0,
7207 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7208 (Lisp_Object process)
7210 CHECK_PROCESS (process);
7211 struct Lisp_Process *p = XPROCESS (process);
7212 if (p->infd < 0)
7213 return Qnil;
7214 struct coding_system *coding = proc_decode_coding_system[p->infd];
7215 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7221 # ifdef HAVE_GPM
7223 void
7224 add_gpm_wait_descriptor (int desc)
7226 add_keyboard_wait_descriptor (desc);
7229 void
7230 delete_gpm_wait_descriptor (int desc)
7232 delete_keyboard_wait_descriptor (desc);
7235 # endif
7237 # ifdef USABLE_SIGIO
7239 /* Return true if *MASK has a bit set
7240 that corresponds to one of the keyboard input descriptors. */
7242 static bool
7243 keyboard_bit_set (fd_set *mask)
7245 int fd;
7247 for (fd = 0; fd <= max_input_desc; fd++)
7248 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7249 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7250 return 1;
7252 return 0;
7254 # endif
7256 #else /* not subprocesses */
7258 /* Defined in msdos.c. */
7259 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7260 struct timespec *, void *);
7262 /* Implementation of wait_reading_process_output, assuming that there
7263 are no subprocesses. Used only by the MS-DOS build.
7265 Wait for timeout to elapse and/or keyboard input to be available.
7267 TIME_LIMIT is:
7268 timeout in seconds
7269 If negative, gobble data immediately available but don't wait for any.
7271 NSECS is:
7272 an additional duration to wait, measured in nanoseconds
7273 If TIME_LIMIT is zero, then:
7274 If NSECS == 0, there is no limit.
7275 If NSECS > 0, the timeout consists of NSECS only.
7276 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7278 READ_KBD is:
7279 0 to ignore keyboard input, or
7280 1 to return when input is available, or
7281 -1 means caller will actually read the input, so don't throw to
7282 the quit handler.
7284 see full version for other parameters. We know that wait_proc will
7285 always be NULL, since `subprocesses' isn't defined.
7287 DO_DISPLAY means redisplay should be done to show subprocess
7288 output that arrives.
7290 Return -1 signifying we got no output and did not try. */
7293 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7294 bool do_display,
7295 Lisp_Object wait_for_cell,
7296 struct Lisp_Process *wait_proc, int just_wait_proc)
7298 register int nfds;
7299 struct timespec end_time, timeout;
7300 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7302 if (TYPE_MAXIMUM (time_t) < time_limit)
7303 time_limit = TYPE_MAXIMUM (time_t);
7305 if (time_limit < 0 || nsecs < 0)
7306 wait = MINIMUM;
7307 else if (time_limit > 0 || nsecs > 0)
7309 wait = TIMEOUT;
7310 end_time = timespec_add (current_timespec (),
7311 make_timespec (time_limit, nsecs));
7313 else
7314 wait = INFINITY;
7316 /* Turn off periodic alarms (in case they are in use)
7317 and then turn off any other atimers,
7318 because the select emulator uses alarms. */
7319 stop_polling ();
7320 turn_on_atimers (0);
7322 while (1)
7324 bool timeout_reduced_for_timers = false;
7325 fd_set waitchannels;
7326 int xerrno;
7328 /* If calling from keyboard input, do not quit
7329 since we want to return C-g as an input character.
7330 Otherwise, do pending quit if requested. */
7331 if (read_kbd >= 0)
7332 QUIT;
7334 /* Exit now if the cell we're waiting for became non-nil. */
7335 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7336 break;
7338 /* Compute time from now till when time limit is up. */
7339 /* Exit if already run out. */
7340 if (wait == TIMEOUT)
7342 struct timespec now = current_timespec ();
7343 if (timespec_cmp (end_time, now) <= 0)
7344 break;
7345 timeout = timespec_sub (end_time, now);
7347 else
7348 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7350 /* If our caller will not immediately handle keyboard events,
7351 run timer events directly.
7352 (Callers that will immediately read keyboard events
7353 call timer_delay on their own.) */
7354 if (NILP (wait_for_cell))
7356 struct timespec timer_delay;
7360 unsigned old_timers_run = timers_run;
7361 timer_delay = timer_check ();
7362 if (timers_run != old_timers_run && do_display)
7363 /* We must retry, since a timer may have requeued itself
7364 and that could alter the time delay. */
7365 redisplay_preserve_echo_area (14);
7366 else
7367 break;
7369 while (!detect_input_pending ());
7371 /* If there is unread keyboard input, also return. */
7372 if (read_kbd != 0
7373 && requeued_events_pending_p ())
7374 break;
7376 if (timespec_valid_p (timer_delay))
7378 if (timespec_cmp (timer_delay, timeout) < 0)
7380 timeout = timer_delay;
7381 timeout_reduced_for_timers = true;
7386 /* Cause C-g and alarm signals to take immediate action,
7387 and cause input available signals to zero out timeout. */
7388 if (read_kbd < 0)
7389 set_waiting_for_input (&timeout);
7391 /* If a frame has been newly mapped and needs updating,
7392 reprocess its display stuff. */
7393 if (frame_garbaged && do_display)
7395 clear_waiting_for_input ();
7396 redisplay_preserve_echo_area (15);
7397 if (read_kbd < 0)
7398 set_waiting_for_input (&timeout);
7401 /* Wait till there is something to do. */
7402 FD_ZERO (&waitchannels);
7403 if (read_kbd && detect_input_pending ())
7404 nfds = 0;
7405 else
7407 if (read_kbd || !NILP (wait_for_cell))
7408 FD_SET (0, &waitchannels);
7409 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7412 xerrno = errno;
7414 /* Make C-g and alarm signals set flags again. */
7415 clear_waiting_for_input ();
7417 /* If we woke up due to SIGWINCH, actually change size now. */
7418 do_pending_window_change (0);
7420 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7421 /* We waited the full specified time, so return now. */
7422 break;
7424 if (nfds == -1)
7426 /* If the system call was interrupted, then go around the
7427 loop again. */
7428 if (xerrno == EINTR)
7429 FD_ZERO (&waitchannels);
7430 else
7431 report_file_errno ("Failed select", Qnil, xerrno);
7434 /* Check for keyboard input. */
7436 if (read_kbd
7437 && detect_input_pending_run_timers (do_display))
7439 swallow_events (do_display);
7440 if (detect_input_pending_run_timers (do_display))
7441 break;
7444 /* If there is unread keyboard input, also return. */
7445 if (read_kbd
7446 && requeued_events_pending_p ())
7447 break;
7449 /* If wait_for_cell. check for keyboard input
7450 but don't run any timers.
7451 ??? (It seems wrong to me to check for keyboard
7452 input at all when wait_for_cell, but the code
7453 has been this way since July 1994.
7454 Try changing this after version 19.31.) */
7455 if (! NILP (wait_for_cell)
7456 && detect_input_pending ())
7458 swallow_events (do_display);
7459 if (detect_input_pending ())
7460 break;
7463 /* Exit now if the cell we're waiting for became non-nil. */
7464 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7465 break;
7468 start_polling ();
7470 return -1;
7473 #endif /* not subprocesses */
7475 /* The following functions are needed even if async subprocesses are
7476 not supported. Some of them are no-op stubs in that case. */
7478 #ifdef HAVE_TIMERFD
7480 /* Add FD, which is a descriptor returned by timerfd_create,
7481 to the set of non-keyboard input descriptors. */
7483 void
7484 add_timer_wait_descriptor (int fd)
7486 FD_SET (fd, &input_wait_mask);
7487 FD_SET (fd, &non_keyboard_wait_mask);
7488 FD_SET (fd, &non_process_wait_mask);
7489 fd_callback_info[fd].func = timerfd_callback;
7490 fd_callback_info[fd].data = NULL;
7491 fd_callback_info[fd].condition |= FOR_READ;
7492 if (fd > max_input_desc)
7493 max_input_desc = fd;
7496 #endif /* HAVE_TIMERFD */
7498 /* Add DESC to the set of keyboard input descriptors. */
7500 void
7501 add_keyboard_wait_descriptor (int desc)
7503 #ifdef subprocesses /* Actually means "not MSDOS". */
7504 FD_SET (desc, &input_wait_mask);
7505 FD_SET (desc, &non_process_wait_mask);
7506 if (desc > max_input_desc)
7507 max_input_desc = desc;
7508 #endif
7511 /* From now on, do not expect DESC to give keyboard input. */
7513 void
7514 delete_keyboard_wait_descriptor (int desc)
7516 #ifdef subprocesses
7517 FD_CLR (desc, &input_wait_mask);
7518 FD_CLR (desc, &non_process_wait_mask);
7519 delete_input_desc (desc);
7520 #endif
7523 /* Setup coding systems of PROCESS. */
7525 void
7526 setup_process_coding_systems (Lisp_Object process)
7528 #ifdef subprocesses
7529 struct Lisp_Process *p = XPROCESS (process);
7530 int inch = p->infd;
7531 int outch = p->outfd;
7532 Lisp_Object coding_system;
7534 if (inch < 0 || outch < 0)
7535 return;
7537 if (!proc_decode_coding_system[inch])
7538 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7539 coding_system = p->decode_coding_system;
7540 if (EQ (p->filter, Qinternal_default_process_filter)
7541 && BUFFERP (p->buffer))
7543 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7544 coding_system = raw_text_coding_system (coding_system);
7546 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7548 if (!proc_encode_coding_system[outch])
7549 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7550 setup_coding_system (p->encode_coding_system,
7551 proc_encode_coding_system[outch]);
7552 #endif
7555 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7556 doc: /* Return the (or a) live process associated with BUFFER.
7557 BUFFER may be a buffer or the name of one.
7558 Return nil if all processes associated with BUFFER have been
7559 deleted or killed. */)
7560 (register Lisp_Object buffer)
7562 #ifdef subprocesses
7563 register Lisp_Object buf, tail, proc;
7565 if (NILP (buffer)) return Qnil;
7566 buf = Fget_buffer (buffer);
7567 if (NILP (buf)) return Qnil;
7569 FOR_EACH_PROCESS (tail, proc)
7570 if (EQ (XPROCESS (proc)->buffer, buf))
7571 return proc;
7572 #endif /* subprocesses */
7573 return Qnil;
7576 DEFUN ("process-inherit-coding-system-flag",
7577 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7578 1, 1, 0,
7579 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7580 If this flag is t, `buffer-file-coding-system' of the buffer
7581 associated with PROCESS will inherit the coding system used to decode
7582 the process output. */)
7583 (register Lisp_Object process)
7585 #ifdef subprocesses
7586 CHECK_PROCESS (process);
7587 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7588 #else
7589 /* Ignore the argument and return the value of
7590 inherit-process-coding-system. */
7591 return inherit_process_coding_system ? Qt : Qnil;
7592 #endif
7595 /* Kill all processes associated with `buffer'.
7596 If `buffer' is nil, kill all processes. */
7598 void
7599 kill_buffer_processes (Lisp_Object buffer)
7601 #ifdef subprocesses
7602 Lisp_Object tail, proc;
7604 FOR_EACH_PROCESS (tail, proc)
7605 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7607 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7608 Fdelete_process (proc);
7609 else if (XPROCESS (proc)->infd >= 0)
7610 process_send_signal (proc, SIGHUP, Qnil, 1);
7612 #else /* subprocesses */
7613 /* Since we have no subprocesses, this does nothing. */
7614 #endif /* subprocesses */
7617 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7618 Swaiting_for_user_input_p, 0, 0, 0,
7619 doc: /* Return non-nil if Emacs is waiting for input from the user.
7620 This is intended for use by asynchronous process output filters and sentinels. */)
7621 (void)
7623 #ifdef subprocesses
7624 return (waiting_for_user_input_p ? Qt : Qnil);
7625 #else
7626 return Qnil;
7627 #endif
7630 /* Stop reading input from keyboard sources. */
7632 void
7633 hold_keyboard_input (void)
7635 kbd_is_on_hold = 1;
7638 /* Resume reading input from keyboard sources. */
7640 void
7641 unhold_keyboard_input (void)
7643 kbd_is_on_hold = 0;
7646 /* Return true if keyboard input is on hold, zero otherwise. */
7648 bool
7649 kbd_on_hold_p (void)
7651 return kbd_is_on_hold;
7655 /* Enumeration of and access to system processes a-la ps(1). */
7657 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7658 0, 0, 0,
7659 doc: /* Return a list of numerical process IDs of all running processes.
7660 If this functionality is unsupported, return nil.
7662 See `process-attributes' for getting attributes of a process given its ID. */)
7663 (void)
7665 return list_system_processes ();
7668 DEFUN ("process-attributes", Fprocess_attributes,
7669 Sprocess_attributes, 1, 1, 0,
7670 doc: /* Return attributes of the process given by its PID, a number.
7672 Value is an alist where each element is a cons cell of the form
7674 (KEY . VALUE)
7676 If this functionality is unsupported, the value is nil.
7678 See `list-system-processes' for getting a list of all process IDs.
7680 The KEYs of the attributes that this function may return are listed
7681 below, together with the type of the associated VALUE (in parentheses).
7682 Not all platforms support all of these attributes; unsupported
7683 attributes will not appear in the returned alist.
7684 Unless explicitly indicated otherwise, numbers can have either
7685 integer or floating point values.
7687 euid -- Effective user User ID of the process (number)
7688 user -- User name corresponding to euid (string)
7689 egid -- Effective user Group ID of the process (number)
7690 group -- Group name corresponding to egid (string)
7691 comm -- Command name (executable name only) (string)
7692 state -- Process state code, such as "S", "R", or "T" (string)
7693 ppid -- Parent process ID (number)
7694 pgrp -- Process group ID (number)
7695 sess -- Session ID, i.e. process ID of session leader (number)
7696 ttname -- Controlling tty name (string)
7697 tpgid -- ID of foreground process group on the process's tty (number)
7698 minflt -- number of minor page faults (number)
7699 majflt -- number of major page faults (number)
7700 cminflt -- cumulative number of minor page faults (number)
7701 cmajflt -- cumulative number of major page faults (number)
7702 utime -- user time used by the process, in (current-time) format,
7703 which is a list of integers (HIGH LOW USEC PSEC)
7704 stime -- system time used by the process (current-time)
7705 time -- sum of utime and stime (current-time)
7706 cutime -- user time used by the process and its children (current-time)
7707 cstime -- system time used by the process and its children (current-time)
7708 ctime -- sum of cutime and cstime (current-time)
7709 pri -- priority of the process (number)
7710 nice -- nice value of the process (number)
7711 thcount -- process thread count (number)
7712 start -- time the process started (current-time)
7713 vsize -- virtual memory size of the process in KB's (number)
7714 rss -- resident set size of the process in KB's (number)
7715 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7716 pcpu -- percents of CPU time used by the process (floating-point number)
7717 pmem -- percents of total physical memory used by process's resident set
7718 (floating-point number)
7719 args -- command line which invoked the process (string). */)
7720 ( Lisp_Object pid)
7722 return system_process_attributes (pid);
7725 #ifdef subprocesses
7726 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7727 Invoke this after init_process_emacs, and after glib and/or GNUstep
7728 futz with the SIGCHLD handler, but before Emacs forks any children.
7729 This function's caller should block SIGCHLD. */
7731 void
7732 catch_child_signal (void)
7734 struct sigaction action, old_action;
7735 sigset_t oldset;
7736 emacs_sigaction_init (&action, deliver_child_signal);
7737 block_child_signal (&oldset);
7738 sigaction (SIGCHLD, &action, &old_action);
7739 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7740 || ! (old_action.sa_flags & SA_SIGINFO));
7742 if (old_action.sa_handler != deliver_child_signal)
7743 lib_child_handler
7744 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7745 ? dummy_handler
7746 : old_action.sa_handler);
7747 unblock_child_signal (&oldset);
7749 #endif /* subprocesses */
7752 /* This is not called "init_process" because that is the name of a
7753 Mach system call, so it would cause problems on Darwin systems. */
7754 void
7755 init_process_emacs (void)
7757 #ifdef subprocesses
7758 register int i;
7760 inhibit_sentinels = 0;
7762 #ifndef CANNOT_DUMP
7763 if (! noninteractive || initialized)
7764 #endif
7766 #if defined HAVE_GLIB && !defined WINDOWSNT
7767 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7768 this should always fail, but is enough to initialize glib's
7769 private SIGCHLD handler, allowing catch_child_signal to copy
7770 it into lib_child_handler. */
7771 g_source_unref (g_child_watch_source_new (getpid ()));
7772 #endif
7773 catch_child_signal ();
7776 FD_ZERO (&input_wait_mask);
7777 FD_ZERO (&non_keyboard_wait_mask);
7778 FD_ZERO (&non_process_wait_mask);
7779 FD_ZERO (&write_mask);
7780 max_process_desc = max_input_desc = -1;
7781 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7783 #ifdef NON_BLOCKING_CONNECT
7784 FD_ZERO (&connect_wait_mask);
7785 num_pending_connects = 0;
7786 #endif
7788 process_output_delay_count = 0;
7789 process_output_skip = 0;
7791 /* Don't do this, it caused infinite select loops. The display
7792 method should call add_keyboard_wait_descriptor on stdin if it
7793 needs that. */
7794 #if 0
7795 FD_SET (0, &input_wait_mask);
7796 #endif
7798 Vprocess_alist = Qnil;
7799 deleted_pid_list = Qnil;
7800 for (i = 0; i < FD_SETSIZE; i++)
7802 chan_process[i] = Qnil;
7803 proc_buffered_char[i] = -1;
7805 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7806 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7807 #ifdef DATAGRAM_SOCKETS
7808 memset (datagram_address, 0, sizeof datagram_address);
7809 #endif
7811 #if defined (DARWIN_OS)
7812 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7813 processes. As such, we only change the default value. */
7814 if (initialized)
7816 char const *release = (STRINGP (Voperating_system_release)
7817 ? SSDATA (Voperating_system_release)
7818 : 0);
7819 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7820 Vprocess_connection_type = Qnil;
7823 #endif
7824 #endif /* subprocesses */
7825 kbd_is_on_hold = 0;
7828 void
7829 syms_of_process (void)
7831 #ifdef subprocesses
7833 DEFSYM (Qprocessp, "processp");
7834 DEFSYM (Qrun, "run");
7835 DEFSYM (Qstop, "stop");
7836 DEFSYM (Qsignal, "signal");
7838 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7839 here again. */
7841 DEFSYM (Qopen, "open");
7842 DEFSYM (Qclosed, "closed");
7843 DEFSYM (Qconnect, "connect");
7844 DEFSYM (Qfailed, "failed");
7845 DEFSYM (Qlisten, "listen");
7846 DEFSYM (Qlocal, "local");
7847 DEFSYM (Qipv4, "ipv4");
7848 #ifdef AF_INET6
7849 DEFSYM (Qipv6, "ipv6");
7850 #endif
7851 DEFSYM (Qdatagram, "datagram");
7852 DEFSYM (Qseqpacket, "seqpacket");
7854 DEFSYM (QCport, ":port");
7855 DEFSYM (QCspeed, ":speed");
7856 DEFSYM (QCprocess, ":process");
7858 DEFSYM (QCbytesize, ":bytesize");
7859 DEFSYM (QCstopbits, ":stopbits");
7860 DEFSYM (QCparity, ":parity");
7861 DEFSYM (Qodd, "odd");
7862 DEFSYM (Qeven, "even");
7863 DEFSYM (QCflowcontrol, ":flowcontrol");
7864 DEFSYM (Qhw, "hw");
7865 DEFSYM (Qsw, "sw");
7866 DEFSYM (QCsummary, ":summary");
7868 DEFSYM (Qreal, "real");
7869 DEFSYM (Qnetwork, "network");
7870 DEFSYM (Qserial, "serial");
7871 DEFSYM (Qpipe, "pipe");
7872 DEFSYM (QCbuffer, ":buffer");
7873 DEFSYM (QChost, ":host");
7874 DEFSYM (QCservice, ":service");
7875 DEFSYM (QClocal, ":local");
7876 DEFSYM (QCremote, ":remote");
7877 DEFSYM (QCcoding, ":coding");
7878 DEFSYM (QCserver, ":server");
7879 DEFSYM (QCnowait, ":nowait");
7880 DEFSYM (QCsentinel, ":sentinel");
7881 DEFSYM (QCtls_parameters, ":tls-parameters");
7882 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
7883 DEFSYM (QClog, ":log");
7884 DEFSYM (QCnoquery, ":noquery");
7885 DEFSYM (QCstop, ":stop");
7886 DEFSYM (QCplist, ":plist");
7887 DEFSYM (QCcommand, ":command");
7888 DEFSYM (QCconnection_type, ":connection-type");
7889 DEFSYM (QCstderr, ":stderr");
7890 DEFSYM (Qpty, "pty");
7891 DEFSYM (Qpipe, "pipe");
7893 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7895 staticpro (&Vprocess_alist);
7896 staticpro (&deleted_pid_list);
7898 #endif /* subprocesses */
7900 DEFSYM (QCname, ":name");
7901 DEFSYM (QCtype, ":type");
7903 DEFSYM (Qeuid, "euid");
7904 DEFSYM (Qegid, "egid");
7905 DEFSYM (Quser, "user");
7906 DEFSYM (Qgroup, "group");
7907 DEFSYM (Qcomm, "comm");
7908 DEFSYM (Qstate, "state");
7909 DEFSYM (Qppid, "ppid");
7910 DEFSYM (Qpgrp, "pgrp");
7911 DEFSYM (Qsess, "sess");
7912 DEFSYM (Qttname, "ttname");
7913 DEFSYM (Qtpgid, "tpgid");
7914 DEFSYM (Qminflt, "minflt");
7915 DEFSYM (Qmajflt, "majflt");
7916 DEFSYM (Qcminflt, "cminflt");
7917 DEFSYM (Qcmajflt, "cmajflt");
7918 DEFSYM (Qutime, "utime");
7919 DEFSYM (Qstime, "stime");
7920 DEFSYM (Qtime, "time");
7921 DEFSYM (Qcutime, "cutime");
7922 DEFSYM (Qcstime, "cstime");
7923 DEFSYM (Qctime, "ctime");
7924 #ifdef subprocesses
7925 DEFSYM (Qinternal_default_process_sentinel,
7926 "internal-default-process-sentinel");
7927 DEFSYM (Qinternal_default_process_filter,
7928 "internal-default-process-filter");
7929 #endif
7930 DEFSYM (Qpri, "pri");
7931 DEFSYM (Qnice, "nice");
7932 DEFSYM (Qthcount, "thcount");
7933 DEFSYM (Qstart, "start");
7934 DEFSYM (Qvsize, "vsize");
7935 DEFSYM (Qrss, "rss");
7936 DEFSYM (Qetime, "etime");
7937 DEFSYM (Qpcpu, "pcpu");
7938 DEFSYM (Qpmem, "pmem");
7939 DEFSYM (Qargs, "args");
7941 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7942 doc: /* Non-nil means delete processes immediately when they exit.
7943 A value of nil means don't delete them until `list-processes' is run. */);
7945 delete_exited_processes = 1;
7947 #ifdef subprocesses
7948 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7949 doc: /* Control type of device used to communicate with subprocesses.
7950 Values are nil to use a pipe, or t or `pty' to use a pty.
7951 The value has no effect if the system has no ptys or if all ptys are busy:
7952 then a pipe is used in any case.
7953 The value takes effect when `start-process' is called. */);
7954 Vprocess_connection_type = Qt;
7956 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7957 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7958 On some systems, when Emacs reads the output from a subprocess, the output data
7959 is read in very small blocks, potentially resulting in very poor performance.
7960 This behavior can be remedied to some extent by setting this variable to a
7961 non-nil value, as it will automatically delay reading from such processes, to
7962 allow them to produce more output before Emacs tries to read it.
7963 If the value is t, the delay is reset after each write to the process; any other
7964 non-nil value means that the delay is not reset on write.
7965 The variable takes effect when `start-process' is called. */);
7966 Vprocess_adaptive_read_buffering = Qt;
7968 defsubr (&Sprocessp);
7969 defsubr (&Sget_process);
7970 defsubr (&Sdelete_process);
7971 defsubr (&Sprocess_status);
7972 defsubr (&Sprocess_exit_status);
7973 defsubr (&Sprocess_id);
7974 defsubr (&Sprocess_name);
7975 defsubr (&Sprocess_tty_name);
7976 defsubr (&Sprocess_command);
7977 defsubr (&Sset_process_buffer);
7978 defsubr (&Sprocess_buffer);
7979 defsubr (&Sprocess_mark);
7980 defsubr (&Sset_process_filter);
7981 defsubr (&Sprocess_filter);
7982 defsubr (&Sset_process_sentinel);
7983 defsubr (&Sprocess_sentinel);
7984 defsubr (&Sset_process_window_size);
7985 defsubr (&Sset_process_inherit_coding_system_flag);
7986 defsubr (&Sset_process_query_on_exit_flag);
7987 defsubr (&Sprocess_query_on_exit_flag);
7988 defsubr (&Sprocess_contact);
7989 defsubr (&Sprocess_plist);
7990 defsubr (&Sset_process_plist);
7991 defsubr (&Sprocess_list);
7992 defsubr (&Smake_process);
7993 defsubr (&Smake_pipe_process);
7994 defsubr (&Sserial_process_configure);
7995 defsubr (&Smake_serial_process);
7996 defsubr (&Sset_network_process_option);
7997 defsubr (&Smake_network_process);
7998 defsubr (&Sformat_network_address);
7999 defsubr (&Snetwork_interface_list);
8000 defsubr (&Snetwork_interface_info);
8001 #ifdef DATAGRAM_SOCKETS
8002 defsubr (&Sprocess_datagram_address);
8003 defsubr (&Sset_process_datagram_address);
8004 #endif
8005 defsubr (&Saccept_process_output);
8006 defsubr (&Sprocess_send_region);
8007 defsubr (&Sprocess_send_string);
8008 defsubr (&Sinterrupt_process);
8009 defsubr (&Skill_process);
8010 defsubr (&Squit_process);
8011 defsubr (&Sstop_process);
8012 defsubr (&Scontinue_process);
8013 defsubr (&Sprocess_running_child_p);
8014 defsubr (&Sprocess_send_eof);
8015 defsubr (&Ssignal_process);
8016 defsubr (&Swaiting_for_user_input_p);
8017 defsubr (&Sprocess_type);
8018 defsubr (&Sinternal_default_process_sentinel);
8019 defsubr (&Sinternal_default_process_filter);
8020 defsubr (&Sset_process_coding_system);
8021 defsubr (&Sprocess_coding_system);
8022 defsubr (&Sset_process_filter_multibyte);
8023 defsubr (&Sprocess_filter_multibyte_p);
8025 #endif /* subprocesses */
8027 defsubr (&Sget_buffer_process);
8028 defsubr (&Sprocess_inherit_coding_system_flag);
8029 defsubr (&Slist_system_processes);
8030 defsubr (&Sprocess_attributes);
8033 Lisp_Object subfeatures = Qnil;
8034 const struct socket_options *sopt;
8036 #define ADD_SUBFEATURE(key, val) \
8037 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8039 #ifdef NON_BLOCKING_CONNECT
8040 ADD_SUBFEATURE (QCnowait, Qt);
8041 #endif
8042 #ifdef DATAGRAM_SOCKETS
8043 ADD_SUBFEATURE (QCtype, Qdatagram);
8044 #endif
8045 #ifdef HAVE_SEQPACKET
8046 ADD_SUBFEATURE (QCtype, Qseqpacket);
8047 #endif
8048 #ifdef HAVE_LOCAL_SOCKETS
8049 ADD_SUBFEATURE (QCfamily, Qlocal);
8050 #endif
8051 ADD_SUBFEATURE (QCfamily, Qipv4);
8052 #ifdef AF_INET6
8053 ADD_SUBFEATURE (QCfamily, Qipv6);
8054 #endif
8055 #ifdef HAVE_GETSOCKNAME
8056 ADD_SUBFEATURE (QCservice, Qt);
8057 #endif
8058 ADD_SUBFEATURE (QCserver, Qt);
8060 for (sopt = socket_options; sopt->name; sopt++)
8061 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8063 Fprovide (intern_c_string ("make-network-process"), subfeatures);