Fix process leak with make-network-process
[emacs.git] / src / process.c
blob69d1b2a11ba9a5d57eb3e58c597906a6b664580d
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <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.3.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_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
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
153 #ifndef SOCK_NONBLOCK
154 # define SOCK_NONBLOCK 0
155 #endif
157 /* True if ERRNUM represents an error where the system call would
158 block if a blocking variant were used. */
159 static bool
160 would_block (int errnum)
162 #ifdef EWOULDBLOCK
163 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
164 return true;
165 #endif
166 return errnum == EAGAIN;
169 #ifndef HAVE_ACCEPT4
171 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
173 static int
174 close_on_exec (int fd)
176 if (0 <= fd)
177 fcntl (fd, F_SETFD, FD_CLOEXEC);
178 return fd;
181 # undef accept4
182 # define accept4(sockfd, addr, addrlen, flags) \
183 process_accept4 (sockfd, addr, addrlen, flags)
184 static int
185 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
187 return close_on_exec (accept (sockfd, addr, addrlen));
190 static int
191 process_socket (int domain, int type, int protocol)
193 return close_on_exec (socket (domain, type, protocol));
195 # undef socket
196 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
197 #endif
199 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
200 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
201 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
202 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
203 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
204 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
206 /* Number of events of change of status of a process. */
207 static EMACS_INT process_tick;
208 /* Number of events for which the user or sentinel has been notified. */
209 static EMACS_INT update_tick;
211 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
212 this system. We need to read full packets, so we need a
213 "non-destructive" select. So we require either native select,
214 or emulation of select using FIONREAD. */
216 #ifndef BROKEN_DATAGRAM_SOCKETS
217 # if defined HAVE_SELECT || defined USABLE_FIONREAD
218 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
219 # define DATAGRAM_SOCKETS
220 # endif
221 # endif
222 #endif
224 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
225 # define HAVE_SEQPACKET
226 #endif
228 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
229 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
230 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
232 /* Number of processes which have a non-zero read_output_delay,
233 and therefore might be delayed for adaptive read buffering. */
235 static int process_output_delay_count;
237 /* True if any process has non-nil read_output_skip. */
239 static bool process_output_skip;
241 static void start_process_unwind (Lisp_Object);
242 static void create_process (Lisp_Object, char **, Lisp_Object);
243 #ifdef USABLE_SIGIO
244 static bool keyboard_bit_set (fd_set *);
245 #endif
246 static void deactivate_process (Lisp_Object);
247 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
248 static int read_process_output (Lisp_Object, int);
249 static void create_pty (Lisp_Object);
250 static void exec_sentinel (Lisp_Object, Lisp_Object);
252 /* Mask of bits indicating the descriptors that we wait for input on. */
254 static fd_set input_wait_mask;
256 /* Mask that excludes keyboard input descriptor(s). */
258 static fd_set non_keyboard_wait_mask;
260 /* Mask that excludes process input descriptor(s). */
262 static fd_set non_process_wait_mask;
264 /* Mask for selecting for write. */
266 static fd_set write_mask;
268 /* Mask of bits indicating the descriptors that we wait for connect to
269 complete on. Once they complete, they are removed from this mask
270 and added to the input_wait_mask and non_keyboard_wait_mask. */
272 static fd_set connect_wait_mask;
274 /* Number of bits set in connect_wait_mask. */
275 static int num_pending_connects;
277 /* The largest descriptor currently in use for a process object; -1 if none. */
278 static int max_process_desc;
280 /* The largest descriptor currently in use for input; -1 if none. */
281 static int max_input_desc;
283 /* Set the external socket descriptor for Emacs to use when
284 `make-network-process' is called with a non-nil
285 `:use-external-socket' option. The value should be either -1, or
286 the file descriptor of a socket that is already bound. */
287 static int external_sock_fd;
289 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
290 static Lisp_Object chan_process[FD_SETSIZE];
291 static void wait_for_socket_fds (Lisp_Object, char const *);
293 /* Alist of elements (NAME . PROCESS). */
294 static Lisp_Object Vprocess_alist;
296 /* Buffered-ahead input char from process, indexed by channel.
297 -1 means empty (no char is buffered).
298 Used on sys V where the only way to tell if there is any
299 output from the process is to read at least one char.
300 Always -1 on systems that support FIONREAD. */
302 static int proc_buffered_char[FD_SETSIZE];
304 /* Table of `struct coding-system' for each process. */
305 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
306 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
308 #ifdef DATAGRAM_SOCKETS
309 /* Table of `partner address' for datagram sockets. */
310 static struct sockaddr_and_len {
311 struct sockaddr *sa;
312 ptrdiff_t len;
313 } datagram_address[FD_SETSIZE];
314 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
315 #define DATAGRAM_CONN_P(proc) \
316 (PROCESSP (proc) && \
317 XPROCESS (proc)->infd >= 0 && \
318 datagram_address[XPROCESS (proc)->infd].sa != 0)
319 #else
320 #define DATAGRAM_CONN_P(proc) (0)
321 #endif
323 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
324 a `for' loop which iterates over processes from Vprocess_alist. */
326 #define FOR_EACH_PROCESS(list_var, proc_var) \
327 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
329 /* These setters are used only in this file, so they can be private. */
330 static void
331 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
333 p->buffer = val;
335 static void
336 pset_command (struct Lisp_Process *p, Lisp_Object val)
338 p->command = val;
340 static void
341 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
343 p->decode_coding_system = val;
345 static void
346 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
348 p->decoding_buf = val;
350 static void
351 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
353 p->encode_coding_system = val;
355 static void
356 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
358 p->encoding_buf = val;
360 static void
361 pset_filter (struct Lisp_Process *p, Lisp_Object val)
363 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
365 static void
366 pset_log (struct Lisp_Process *p, Lisp_Object val)
368 p->log = val;
370 static void
371 pset_mark (struct Lisp_Process *p, Lisp_Object val)
373 p->mark = val;
375 static void
376 pset_name (struct Lisp_Process *p, Lisp_Object val)
378 p->name = val;
380 static void
381 pset_plist (struct Lisp_Process *p, Lisp_Object val)
383 p->plist = val;
385 static void
386 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
388 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
390 static void
391 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
393 p->tty_name = val;
395 static void
396 pset_type (struct Lisp_Process *p, Lisp_Object val)
398 p->type = val;
400 static void
401 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
403 p->write_queue = val;
405 static void
406 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
408 p->stderrproc = val;
412 static Lisp_Object
413 make_lisp_proc (struct Lisp_Process *p)
415 return make_lisp_ptr (p, Lisp_Vectorlike);
418 static struct fd_callback_data
420 fd_callback func;
421 void *data;
422 #define FOR_READ 1
423 #define FOR_WRITE 2
424 int condition; /* Mask of the defines above. */
425 } fd_callback_info[FD_SETSIZE];
428 /* Add a file descriptor FD to be monitored for when read is possible.
429 When read is possible, call FUNC with argument DATA. */
431 void
432 add_read_fd (int fd, fd_callback func, void *data)
434 add_keyboard_wait_descriptor (fd);
436 fd_callback_info[fd].func = func;
437 fd_callback_info[fd].data = data;
438 fd_callback_info[fd].condition |= FOR_READ;
441 /* Stop monitoring file descriptor FD for when read is possible. */
443 void
444 delete_read_fd (int fd)
446 delete_keyboard_wait_descriptor (fd);
448 fd_callback_info[fd].condition &= ~FOR_READ;
449 if (fd_callback_info[fd].condition == 0)
451 fd_callback_info[fd].func = 0;
452 fd_callback_info[fd].data = 0;
456 /* Add a file descriptor FD to be monitored for when write is possible.
457 When write is possible, call FUNC with argument DATA. */
459 void
460 add_write_fd (int fd, fd_callback func, void *data)
462 FD_SET (fd, &write_mask);
463 if (fd > max_input_desc)
464 max_input_desc = fd;
466 fd_callback_info[fd].func = func;
467 fd_callback_info[fd].data = data;
468 fd_callback_info[fd].condition |= FOR_WRITE;
471 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
473 static void
474 delete_input_desc (int fd)
476 if (fd == max_input_desc)
479 fd--;
480 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
481 || FD_ISSET (fd, &write_mask)));
483 max_input_desc = fd;
487 /* Stop monitoring file descriptor FD for when write is possible. */
489 void
490 delete_write_fd (int fd)
492 FD_CLR (fd, &write_mask);
493 fd_callback_info[fd].condition &= ~FOR_WRITE;
494 if (fd_callback_info[fd].condition == 0)
496 fd_callback_info[fd].func = 0;
497 fd_callback_info[fd].data = 0;
498 delete_input_desc (fd);
503 /* Compute the Lisp form of the process status, p->status, from
504 the numeric status that was returned by `wait'. */
506 static Lisp_Object status_convert (int);
508 static void
509 update_status (struct Lisp_Process *p)
511 eassert (p->raw_status_new);
512 pset_status (p, status_convert (p->raw_status));
513 p->raw_status_new = 0;
516 /* Convert a process status word in Unix format to
517 the list that we use internally. */
519 static Lisp_Object
520 status_convert (int w)
522 if (WIFSTOPPED (w))
523 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
524 else if (WIFEXITED (w))
525 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
526 WCOREDUMP (w) ? Qt : Qnil));
527 else if (WIFSIGNALED (w))
528 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
529 WCOREDUMP (w) ? Qt : Qnil));
530 else
531 return Qrun;
534 /* True if STATUS is that of a process attempting connection. */
536 static bool
537 connecting_status (Lisp_Object status)
539 return CONSP (status) && EQ (XCAR (status), Qconnect);
542 /* Given a status-list, extract the three pieces of information
543 and store them individually through the three pointers. */
545 static void
546 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
547 bool *coredump)
549 Lisp_Object tem;
551 if (connecting_status (l))
552 l = XCAR (l);
554 if (SYMBOLP (l))
556 *symbol = l;
557 *code = make_number (0);
558 *coredump = 0;
560 else
562 *symbol = XCAR (l);
563 tem = XCDR (l);
564 *code = XCAR (tem);
565 tem = XCDR (tem);
566 *coredump = !NILP (tem);
570 /* Return a string describing a process status list. */
572 static Lisp_Object
573 status_message (struct Lisp_Process *p)
575 Lisp_Object status = p->status;
576 Lisp_Object symbol, code;
577 bool coredump;
578 Lisp_Object string;
580 decode_status (status, &symbol, &code, &coredump);
582 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
584 char const *signame;
585 synchronize_system_messages_locale ();
586 signame = strsignal (XFASTINT (code));
587 if (signame == 0)
588 string = build_string ("unknown");
589 else
591 int c1, c2;
593 string = build_unibyte_string (signame);
594 if (! NILP (Vlocale_coding_system))
595 string = (code_convert_string_norecord
596 (string, Vlocale_coding_system, 0));
597 c1 = STRING_CHAR (SDATA (string));
598 c2 = downcase (c1);
599 if (c1 != c2)
600 Faset (string, make_number (0), make_number (c2));
602 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
603 return concat2 (string, suffix);
605 else if (EQ (symbol, Qexit))
607 if (NETCONN1_P (p))
608 return build_string (XFASTINT (code) == 0
609 ? "deleted\n"
610 : "connection broken by remote peer\n");
611 if (XFASTINT (code) == 0)
612 return build_string ("finished\n");
613 AUTO_STRING (prefix, "exited abnormally with code ");
614 string = Fnumber_to_string (code);
615 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
616 return concat3 (prefix, string, suffix);
618 else if (EQ (symbol, Qfailed))
620 AUTO_STRING (format, "failed with code %s\n");
621 return CALLN (Fformat, format, code);
623 else
624 return Fcopy_sequence (Fsymbol_name (symbol));
627 enum { PTY_NAME_SIZE = 24 };
629 /* Open an available pty, returning a file descriptor.
630 Store into PTY_NAME the file name of the terminal corresponding to the pty.
631 Return -1 on failure. */
633 static int
634 allocate_pty (char pty_name[PTY_NAME_SIZE])
636 #ifdef HAVE_PTYS
637 int fd;
639 #ifdef PTY_ITERATION
640 PTY_ITERATION
641 #else
642 register int c, i;
643 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
644 for (i = 0; i < 16; i++)
645 #endif
647 #ifdef PTY_NAME_SPRINTF
648 PTY_NAME_SPRINTF
649 #else
650 sprintf (pty_name, "/dev/pty%c%x", c, i);
651 #endif /* no PTY_NAME_SPRINTF */
653 #ifdef PTY_OPEN
654 PTY_OPEN;
655 #else /* no PTY_OPEN */
656 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
657 #endif /* no PTY_OPEN */
659 if (fd >= 0)
661 #ifdef PTY_TTY_NAME_SPRINTF
662 PTY_TTY_NAME_SPRINTF
663 #else
664 sprintf (pty_name, "/dev/tty%c%x", c, i);
665 #endif /* no PTY_TTY_NAME_SPRINTF */
667 /* Set FD's close-on-exec flag. This is needed even if
668 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
669 doesn't require support for that combination.
670 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
671 doesn't work if the close-on-exec flag is set (Bug#20555).
672 Multithreaded platforms where posix_openpt ignores
673 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
674 have a race condition between the PTY_OPEN and here. */
675 fcntl (fd, F_SETFD, FD_CLOEXEC);
677 /* Check to make certain that both sides are available.
678 This avoids a nasty yet stupid bug in rlogins. */
679 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
681 emacs_close (fd);
682 # ifndef __sgi
683 continue;
684 # else
685 return -1;
686 # endif /* __sgi */
688 setup_pty (fd);
689 return fd;
692 #endif /* HAVE_PTYS */
693 return -1;
696 /* Allocate basically initialized process. */
698 static struct Lisp_Process *
699 allocate_process (void)
701 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
704 static Lisp_Object
705 make_process (Lisp_Object name)
707 struct Lisp_Process *p = allocate_process ();
708 /* Initialize Lisp data. Note that allocate_process initializes all
709 Lisp data to nil, so do it only for slots which should not be nil. */
710 pset_status (p, Qrun);
711 pset_mark (p, Fmake_marker ());
713 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
714 non-Lisp data, so do it only for slots which should not be zero. */
715 p->infd = -1;
716 p->outfd = -1;
717 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
718 p->open_fd[i] = -1;
720 #ifdef HAVE_GNUTLS
721 verify (GNUTLS_STAGE_EMPTY == 0);
722 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
723 eassert (NILP (p->gnutls_boot_parameters));
724 #endif
726 /* If name is already in use, modify it until it is unused. */
728 Lisp_Object name1 = name;
729 for (printmax_t i = 1; ; i++)
731 Lisp_Object tem = Fget_process (name1);
732 if (NILP (tem))
733 break;
734 char const suffix_fmt[] = "<%"pMd">";
735 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
736 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
737 name1 = concat2 (name, lsuffix);
739 name = name1;
740 pset_name (p, name);
741 pset_sentinel (p, Qinternal_default_process_sentinel);
742 pset_filter (p, Qinternal_default_process_filter);
743 Lisp_Object val;
744 XSETPROCESS (val, p);
745 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
746 return val;
749 static void
750 remove_process (register Lisp_Object proc)
752 register Lisp_Object pair;
754 pair = Frassq (proc, Vprocess_alist);
755 Vprocess_alist = Fdelq (pair, Vprocess_alist);
757 deactivate_process (proc);
760 #ifdef HAVE_GETADDRINFO_A
761 static void
762 free_dns_request (Lisp_Object proc)
764 struct Lisp_Process *p = XPROCESS (proc);
766 if (p->dns_request->ar_result)
767 freeaddrinfo (p->dns_request->ar_result);
768 xfree (p->dns_request);
769 p->dns_request = NULL;
771 #endif
774 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
775 doc: /* Return t if OBJECT is a process. */)
776 (Lisp_Object object)
778 return PROCESSP (object) ? Qt : Qnil;
781 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
782 doc: /* Return the process named NAME, or nil if there is none. */)
783 (register Lisp_Object name)
785 if (PROCESSP (name))
786 return name;
787 CHECK_STRING (name);
788 return Fcdr (Fassoc (name, Vprocess_alist));
791 /* This is how commands for the user decode process arguments. It
792 accepts a process, a process name, a buffer, a buffer name, or nil.
793 Buffers denote the first process in the buffer, and nil denotes the
794 current buffer. */
796 static Lisp_Object
797 get_process (register Lisp_Object name)
799 register Lisp_Object proc, obj;
800 if (STRINGP (name))
802 obj = Fget_process (name);
803 if (NILP (obj))
804 obj = Fget_buffer (name);
805 if (NILP (obj))
806 error ("Process %s does not exist", SDATA (name));
808 else if (NILP (name))
809 obj = Fcurrent_buffer ();
810 else
811 obj = name;
813 /* Now obj should be either a buffer object or a process object. */
814 if (BUFFERP (obj))
816 if (NILP (BVAR (XBUFFER (obj), name)))
817 error ("Attempt to get process for a dead buffer");
818 proc = Fget_buffer_process (obj);
819 if (NILP (proc))
820 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
822 else
824 CHECK_PROCESS (obj);
825 proc = obj;
827 return proc;
831 /* Fdelete_process promises to immediately forget about the process, but in
832 reality, Emacs needs to remember those processes until they have been
833 treated by the SIGCHLD handler and waitpid has been invoked on them;
834 otherwise they might fill up the kernel's process table.
836 Some processes created by call-process are also put onto this list.
838 Members of this list are (process-ID . filename) pairs. The
839 process-ID is a number; the filename, if a string, is a file that
840 needs to be removed after the process exits. */
841 static Lisp_Object deleted_pid_list;
843 void
844 record_deleted_pid (pid_t pid, Lisp_Object filename)
846 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
847 /* GC treated elements set to nil. */
848 Fdelq (Qnil, deleted_pid_list));
852 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
853 doc: /* Delete PROCESS: kill it and forget about it immediately.
854 PROCESS may be a process, a buffer, the name of a process or buffer, or
855 nil, indicating the current buffer's process. */)
856 (register Lisp_Object process)
858 register struct Lisp_Process *p;
860 process = get_process (process);
861 p = XPROCESS (process);
863 #ifdef HAVE_GETADDRINFO_A
864 if (p->dns_request)
866 /* Cancel the request. Unless shutting down, wait until
867 completion. Free the request if completely canceled. */
869 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
870 if (!canceled && !inhibit_sentinels)
872 struct gaicb const *req = p->dns_request;
873 while (gai_suspend (&req, 1, NULL) != 0)
874 continue;
875 canceled = true;
877 if (canceled)
878 free_dns_request (process);
880 #endif
882 p->raw_status_new = 0;
883 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
885 pset_status (p, list2 (Qexit, make_number (0)));
886 p->tick = ++process_tick;
887 status_notify (p, NULL);
888 redisplay_preserve_echo_area (13);
890 else
892 if (p->alive)
893 record_kill_process (p, Qnil);
895 if (p->infd >= 0)
897 /* Update P's status, since record_kill_process will make the
898 SIGCHLD handler update deleted_pid_list, not *P. */
899 Lisp_Object symbol;
900 if (p->raw_status_new)
901 update_status (p);
902 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
903 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
904 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
906 p->tick = ++process_tick;
907 status_notify (p, NULL);
908 redisplay_preserve_echo_area (13);
911 remove_process (process);
912 return Qnil;
915 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
916 doc: /* Return the status of PROCESS.
917 The returned value is one of the following symbols:
918 run -- for a process that is running.
919 stop -- for a process stopped but continuable.
920 exit -- for a process that has exited.
921 signal -- for a process that has got a fatal signal.
922 open -- for a network stream connection that is open.
923 listen -- for a network stream server that is listening.
924 closed -- for a network stream connection that is closed.
925 connect -- when waiting for a non-blocking connection to complete.
926 failed -- when a non-blocking connection has failed.
927 nil -- if arg is a process name and no such process exists.
928 PROCESS may be a process, a buffer, the name of a process, or
929 nil, indicating the current buffer's process. */)
930 (register Lisp_Object process)
932 register struct Lisp_Process *p;
933 register Lisp_Object status;
935 if (STRINGP (process))
936 process = Fget_process (process);
937 else
938 process = get_process (process);
940 if (NILP (process))
941 return process;
943 p = XPROCESS (process);
944 if (p->raw_status_new)
945 update_status (p);
946 status = p->status;
947 if (CONSP (status))
948 status = XCAR (status);
949 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
951 if (EQ (status, Qexit))
952 status = Qclosed;
953 else if (EQ (p->command, Qt))
954 status = Qstop;
955 else if (EQ (status, Qrun))
956 status = Qopen;
958 return status;
961 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
962 1, 1, 0,
963 doc: /* Return the exit status of PROCESS or the signal number that killed it.
964 If PROCESS has not yet exited or died, return 0. */)
965 (register Lisp_Object process)
967 CHECK_PROCESS (process);
968 if (XPROCESS (process)->raw_status_new)
969 update_status (XPROCESS (process));
970 if (CONSP (XPROCESS (process)->status))
971 return XCAR (XCDR (XPROCESS (process)->status));
972 return make_number (0);
975 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
976 doc: /* Return the process id of PROCESS.
977 This is the pid of the external process which PROCESS uses or talks to.
978 For a network connection, this value is nil. */)
979 (register Lisp_Object process)
981 pid_t pid;
983 CHECK_PROCESS (process);
984 pid = XPROCESS (process)->pid;
985 return (pid ? make_fixnum_or_float (pid) : Qnil);
988 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
989 doc: /* Return the name of PROCESS, as a string.
990 This is the name of the program invoked in PROCESS,
991 possibly modified to make it unique among process names. */)
992 (register Lisp_Object process)
994 CHECK_PROCESS (process);
995 return XPROCESS (process)->name;
998 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
999 doc: /* Return the command that was executed to start PROCESS.
1000 This is a list of strings, the first string being the program executed
1001 and the rest of the strings being the arguments given to it.
1002 For a network or serial process, this is nil (process is running) or t
1003 \(process is stopped). */)
1004 (register Lisp_Object process)
1006 CHECK_PROCESS (process);
1007 return XPROCESS (process)->command;
1010 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1011 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1012 This is the terminal that the process itself reads and writes on,
1013 not the name of the pty that Emacs uses to talk with that terminal. */)
1014 (register Lisp_Object process)
1016 CHECK_PROCESS (process);
1017 return XPROCESS (process)->tty_name;
1020 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1021 2, 2, 0,
1022 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1023 Return BUFFER. */)
1024 (register Lisp_Object process, Lisp_Object buffer)
1026 struct Lisp_Process *p;
1028 CHECK_PROCESS (process);
1029 if (!NILP (buffer))
1030 CHECK_BUFFER (buffer);
1031 p = XPROCESS (process);
1032 pset_buffer (p, buffer);
1033 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1034 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1035 setup_process_coding_systems (process);
1036 return buffer;
1039 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1040 1, 1, 0,
1041 doc: /* Return the buffer PROCESS is associated with.
1042 The default process filter inserts output from PROCESS into this buffer. */)
1043 (register Lisp_Object process)
1045 CHECK_PROCESS (process);
1046 return XPROCESS (process)->buffer;
1049 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1050 1, 1, 0,
1051 doc: /* Return the marker for the end of the last output from PROCESS. */)
1052 (register Lisp_Object process)
1054 CHECK_PROCESS (process);
1055 return XPROCESS (process)->mark;
1058 static void
1059 set_process_filter_masks (struct Lisp_Process *p)
1061 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1063 FD_CLR (p->infd, &input_wait_mask);
1064 FD_CLR (p->infd, &non_keyboard_wait_mask);
1066 else if (EQ (p->filter, Qt)
1067 /* Network or serial process not stopped: */
1068 && !EQ (p->command, Qt))
1070 FD_SET (p->infd, &input_wait_mask);
1071 FD_SET (p->infd, &non_keyboard_wait_mask);
1075 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1076 2, 2, 0,
1077 doc: /* Give PROCESS the filter function FILTER; nil means default.
1078 A value of t means stop accepting output from the process.
1080 When a process has a non-default filter, its buffer is not used for output.
1081 Instead, each time it does output, the entire string of output is
1082 passed to the filter.
1084 The filter gets two arguments: the process and the string of output.
1085 The string argument is normally a multibyte string, except:
1086 - if the process's input coding system is no-conversion or raw-text,
1087 it is a unibyte string (the non-converted input), or else
1088 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1089 string (the result of converting the decoded input multibyte
1090 string to unibyte with `string-make-unibyte'). */)
1091 (Lisp_Object process, Lisp_Object filter)
1093 CHECK_PROCESS (process);
1094 struct Lisp_Process *p = XPROCESS (process);
1096 /* Don't signal an error if the process's input file descriptor
1097 is closed. This could make debugging Lisp more difficult,
1098 for example when doing something like
1100 (setq process (start-process ...))
1101 (debug)
1102 (set-process-filter process ...) */
1104 if (NILP (filter))
1105 filter = Qinternal_default_process_filter;
1107 pset_filter (p, filter);
1109 if (p->infd >= 0)
1110 set_process_filter_masks (p);
1112 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1113 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1114 setup_process_coding_systems (process);
1115 return filter;
1118 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1119 1, 1, 0,
1120 doc: /* Return the filter function of PROCESS.
1121 See `set-process-filter' for more info on filter functions. */)
1122 (register Lisp_Object process)
1124 CHECK_PROCESS (process);
1125 return XPROCESS (process)->filter;
1128 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1129 2, 2, 0,
1130 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1131 The sentinel is called as a function when the process changes state.
1132 It gets two arguments: the process, and a string describing the change. */)
1133 (register Lisp_Object process, Lisp_Object sentinel)
1135 struct Lisp_Process *p;
1137 CHECK_PROCESS (process);
1138 p = XPROCESS (process);
1140 if (NILP (sentinel))
1141 sentinel = Qinternal_default_process_sentinel;
1143 pset_sentinel (p, sentinel);
1144 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1145 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1146 return sentinel;
1149 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1150 1, 1, 0,
1151 doc: /* Return the sentinel of PROCESS.
1152 See `set-process-sentinel' for more info on sentinels. */)
1153 (register Lisp_Object process)
1155 CHECK_PROCESS (process);
1156 return XPROCESS (process)->sentinel;
1159 DEFUN ("set-process-window-size", Fset_process_window_size,
1160 Sset_process_window_size, 3, 3, 0,
1161 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1162 Value is t if PROCESS was successfully told about the window size,
1163 nil otherwise. */)
1164 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1166 CHECK_PROCESS (process);
1168 /* All known platforms store window sizes as 'unsigned short'. */
1169 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1170 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1172 if (NETCONN_P (process)
1173 || XPROCESS (process)->infd < 0
1174 || (set_window_size (XPROCESS (process)->infd,
1175 XINT (height), XINT (width))
1176 < 0))
1177 return Qnil;
1178 else
1179 return Qt;
1182 DEFUN ("set-process-inherit-coding-system-flag",
1183 Fset_process_inherit_coding_system_flag,
1184 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1185 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1186 If the second argument FLAG is non-nil, then the variable
1187 `buffer-file-coding-system' of the buffer associated with PROCESS
1188 will be bound to the value of the coding system used to decode
1189 the process output.
1191 This is useful when the coding system specified for the process buffer
1192 leaves either the character code conversion or the end-of-line conversion
1193 unspecified, or if the coding system used to decode the process output
1194 is more appropriate for saving the process buffer.
1196 Binding the variable `inherit-process-coding-system' to non-nil before
1197 starting the process is an alternative way of setting the inherit flag
1198 for the process which will run.
1200 This function returns FLAG. */)
1201 (register Lisp_Object process, Lisp_Object flag)
1203 CHECK_PROCESS (process);
1204 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1205 return flag;
1208 DEFUN ("set-process-query-on-exit-flag",
1209 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1210 2, 2, 0,
1211 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1212 If the second argument FLAG is non-nil, Emacs will query the user before
1213 exiting or killing a buffer if PROCESS is running. This function
1214 returns FLAG. */)
1215 (register Lisp_Object process, Lisp_Object flag)
1217 CHECK_PROCESS (process);
1218 XPROCESS (process)->kill_without_query = NILP (flag);
1219 return flag;
1222 DEFUN ("process-query-on-exit-flag",
1223 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1224 1, 1, 0,
1225 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1226 (register Lisp_Object process)
1228 CHECK_PROCESS (process);
1229 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1232 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1233 1, 2, 0,
1234 doc: /* Return the contact info of PROCESS; t for a real child.
1235 For a network or serial connection, the value depends on the optional
1236 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1237 SERVICE) for a network connection or (PORT SPEED) for a serial
1238 connection. If KEY is t, the complete contact information for the
1239 connection is returned, else the specific value for the keyword KEY is
1240 returned. See `make-network-process' or `make-serial-process' for a
1241 list of keywords.
1242 If PROCESS is a non-blocking network process that hasn't been fully
1243 set up yet, this function will block until socket setup has completed. */)
1244 (Lisp_Object process, Lisp_Object key)
1246 Lisp_Object contact;
1248 CHECK_PROCESS (process);
1249 contact = XPROCESS (process)->childp;
1251 #ifdef DATAGRAM_SOCKETS
1253 if (NETCONN_P (process))
1254 wait_for_socket_fds (process, "process-contact");
1256 if (DATAGRAM_CONN_P (process)
1257 && (EQ (key, Qt) || EQ (key, QCremote)))
1258 contact = Fplist_put (contact, QCremote,
1259 Fprocess_datagram_address (process));
1260 #endif
1262 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1263 || EQ (key, Qt))
1264 return contact;
1265 if (NILP (key) && NETCONN_P (process))
1266 return list2 (Fplist_get (contact, QChost),
1267 Fplist_get (contact, QCservice));
1268 if (NILP (key) && SERIALCONN_P (process))
1269 return list2 (Fplist_get (contact, QCport),
1270 Fplist_get (contact, QCspeed));
1271 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1272 if the pipe process is useful for purposes other than receiving
1273 stderr. */
1274 if (NILP (key) && PIPECONN_P (process))
1275 return Qt;
1276 return Fplist_get (contact, key);
1279 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1280 1, 1, 0,
1281 doc: /* Return the plist of PROCESS. */)
1282 (register Lisp_Object process)
1284 CHECK_PROCESS (process);
1285 return XPROCESS (process)->plist;
1288 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1289 2, 2, 0,
1290 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1291 (Lisp_Object process, Lisp_Object plist)
1293 CHECK_PROCESS (process);
1294 CHECK_LIST (plist);
1296 pset_plist (XPROCESS (process), plist);
1297 return plist;
1300 #if 0 /* Turned off because we don't currently record this info
1301 in the process. Perhaps add it. */
1302 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1303 doc: /* Return the connection type of PROCESS.
1304 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1305 a socket connection. */)
1306 (Lisp_Object process)
1308 return XPROCESS (process)->type;
1310 #endif
1312 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1313 doc: /* Return the connection type of PROCESS.
1314 The value is either the symbol `real', `network', or `serial'.
1315 PROCESS may be a process, a buffer, the name of a process or buffer, or
1316 nil, indicating the current buffer's process. */)
1317 (Lisp_Object process)
1319 Lisp_Object proc;
1320 proc = get_process (process);
1321 return XPROCESS (proc)->type;
1324 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1325 1, 2, 0,
1326 doc: /* Convert network ADDRESS from internal format to a string.
1327 A 4 or 5 element vector represents an IPv4 address (with port number).
1328 An 8 or 9 element vector represents an IPv6 address (with port number).
1329 If optional second argument OMIT-PORT is non-nil, don't include a port
1330 number in the string, even when present in ADDRESS.
1331 Return nil if format of ADDRESS is invalid. */)
1332 (Lisp_Object address, Lisp_Object omit_port)
1334 if (NILP (address))
1335 return Qnil;
1337 if (STRINGP (address)) /* AF_LOCAL */
1338 return address;
1340 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1342 register struct Lisp_Vector *p = XVECTOR (address);
1343 ptrdiff_t size = p->header.size;
1344 Lisp_Object args[10];
1345 int nargs, i;
1346 char const *format;
1348 if (size == 4 || (size == 5 && !NILP (omit_port)))
1350 format = "%d.%d.%d.%d";
1351 nargs = 4;
1353 else if (size == 5)
1355 format = "%d.%d.%d.%d:%d";
1356 nargs = 5;
1358 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1360 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1361 nargs = 8;
1363 else if (size == 9)
1365 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1366 nargs = 9;
1368 else
1369 return Qnil;
1371 AUTO_STRING (format_obj, format);
1372 args[0] = format_obj;
1374 for (i = 0; i < nargs; i++)
1376 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1377 return Qnil;
1379 if (nargs <= 5 /* IPv4 */
1380 && i < 4 /* host, not port */
1381 && XINT (p->contents[i]) > 255)
1382 return Qnil;
1384 args[i + 1] = p->contents[i];
1387 return Fformat (nargs + 1, args);
1390 if (CONSP (address))
1392 AUTO_STRING (format, "<Family %d>");
1393 return CALLN (Fformat, format, Fcar (address));
1396 return Qnil;
1399 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1400 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1401 (void)
1403 return Fmapcar (Qcdr, Vprocess_alist);
1406 /* Starting asynchronous inferior processes. */
1408 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1409 doc: /* Start a program in a subprocess. Return the process object for it.
1411 This is similar to `start-process', but arguments are specified as
1412 keyword/argument pairs. The following arguments are defined:
1414 :name NAME -- NAME is name for process. It is modified if necessary
1415 to make it unique.
1417 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1418 with the process. Process output goes at end of that buffer, unless
1419 you specify an output stream or filter function to handle the output.
1420 BUFFER may be also nil, meaning that this process is not associated
1421 with any buffer.
1423 :command COMMAND -- COMMAND is a list starting with the program file
1424 name, followed by strings to give to the program as arguments.
1426 :coding CODING -- If CODING is a symbol, it specifies the coding
1427 system used for both reading and writing for this process. If CODING
1428 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1429 ENCODING is used for writing.
1431 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1432 the process is running. If BOOL is not given, query before exiting.
1434 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1435 In the stopped state, a process does not accept incoming data, but you
1436 can send outgoing data. The stopped state is cleared by
1437 `continue-process' and set by `stop-process'.
1439 :connection-type TYPE -- TYPE is control type of device used to
1440 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1441 to use a pty, or nil to use the default specified through
1442 `process-connection-type'.
1444 :filter FILTER -- Install FILTER as the process filter.
1446 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1448 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1449 to the standard error of subprocess. Specifying this implies
1450 `:connection-type' is set to `pipe'.
1452 usage: (make-process &rest ARGS) */)
1453 (ptrdiff_t nargs, Lisp_Object *args)
1455 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1456 Lisp_Object xstderr, stderrproc;
1457 ptrdiff_t count = SPECPDL_INDEX ();
1459 if (nargs == 0)
1460 return Qnil;
1462 /* Save arguments for process-contact and clone-process. */
1463 contact = Flist (nargs, args);
1465 buffer = Fplist_get (contact, QCbuffer);
1466 if (!NILP (buffer))
1467 buffer = Fget_buffer_create (buffer);
1469 /* Make sure that the child will be able to chdir to the current
1470 buffer's current directory, or its unhandled equivalent. We
1471 can't just have the child check for an error when it does the
1472 chdir, since it's in a vfork. */
1473 current_dir = encode_current_directory ();
1475 name = Fplist_get (contact, QCname);
1476 CHECK_STRING (name);
1478 command = Fplist_get (contact, QCcommand);
1479 if (CONSP (command))
1480 program = XCAR (command);
1481 else
1482 program = Qnil;
1484 if (!NILP (program))
1485 CHECK_STRING (program);
1487 stderrproc = Qnil;
1488 xstderr = Fplist_get (contact, QCstderr);
1489 if (PROCESSP (xstderr))
1491 if (!PIPECONN_P (xstderr))
1492 error ("Process is not a pipe process");
1493 stderrproc = xstderr;
1495 else if (!NILP (xstderr))
1497 CHECK_STRING (program);
1498 stderrproc = CALLN (Fmake_pipe_process,
1499 QCname,
1500 concat2 (name, build_string (" stderr")),
1501 QCbuffer,
1502 Fget_buffer_create (xstderr));
1505 proc = make_process (name);
1506 record_unwind_protect (start_process_unwind, proc);
1508 pset_childp (XPROCESS (proc), Qt);
1509 eassert (NILP (XPROCESS (proc)->plist));
1510 pset_type (XPROCESS (proc), Qreal);
1511 pset_buffer (XPROCESS (proc), buffer);
1512 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1513 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1514 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1516 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1517 XPROCESS (proc)->kill_without_query = 1;
1518 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1519 pset_command (XPROCESS (proc), Qt);
1521 tem = Fplist_get (contact, QCconnection_type);
1522 if (EQ (tem, Qpty))
1523 XPROCESS (proc)->pty_flag = true;
1524 else if (EQ (tem, Qpipe))
1525 XPROCESS (proc)->pty_flag = false;
1526 else if (NILP (tem))
1527 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1528 else
1529 report_file_error ("Unknown connection type", tem);
1531 if (!NILP (stderrproc))
1533 pset_stderrproc (XPROCESS (proc), stderrproc);
1535 XPROCESS (proc)->pty_flag = false;
1538 #ifdef HAVE_GNUTLS
1539 /* AKA GNUTLS_INITSTAGE(proc). */
1540 verify (GNUTLS_STAGE_EMPTY == 0);
1541 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1542 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1543 #endif
1545 XPROCESS (proc)->adaptive_read_buffering
1546 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1547 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1549 /* Make the process marker point into the process buffer (if any). */
1550 if (BUFFERP (buffer))
1551 set_marker_both (XPROCESS (proc)->mark, buffer,
1552 BUF_ZV (XBUFFER (buffer)),
1553 BUF_ZV_BYTE (XBUFFER (buffer)));
1555 USE_SAFE_ALLOCA;
1558 /* Decide coding systems for communicating with the process. Here
1559 we don't setup the structure coding_system nor pay attention to
1560 unibyte mode. They are done in create_process. */
1562 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1563 Lisp_Object coding_systems = Qt;
1564 Lisp_Object val, *args2;
1566 tem = Fplist_get (contact, QCcoding);
1567 if (!NILP (tem))
1569 val = tem;
1570 if (CONSP (val))
1571 val = XCAR (val);
1573 else
1574 val = Vcoding_system_for_read;
1575 if (NILP (val))
1577 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1578 Lisp_Object tem2;
1579 SAFE_ALLOCA_LISP (args2, nargs2);
1580 ptrdiff_t i = 0;
1581 args2[i++] = Qstart_process;
1582 args2[i++] = name;
1583 args2[i++] = buffer;
1584 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1585 args2[i++] = XCAR (tem2);
1586 if (!NILP (program))
1587 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1588 if (CONSP (coding_systems))
1589 val = XCAR (coding_systems);
1590 else if (CONSP (Vdefault_process_coding_system))
1591 val = XCAR (Vdefault_process_coding_system);
1593 pset_decode_coding_system (XPROCESS (proc), val);
1595 if (!NILP (tem))
1597 val = tem;
1598 if (CONSP (val))
1599 val = XCDR (val);
1601 else
1602 val = Vcoding_system_for_write;
1603 if (NILP (val))
1605 if (EQ (coding_systems, Qt))
1607 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1608 Lisp_Object tem2;
1609 SAFE_ALLOCA_LISP (args2, nargs2);
1610 ptrdiff_t i = 0;
1611 args2[i++] = Qstart_process;
1612 args2[i++] = name;
1613 args2[i++] = buffer;
1614 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1615 args2[i++] = XCAR (tem2);
1616 if (!NILP (program))
1617 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1619 if (CONSP (coding_systems))
1620 val = XCDR (coding_systems);
1621 else if (CONSP (Vdefault_process_coding_system))
1622 val = XCDR (Vdefault_process_coding_system);
1624 pset_encode_coding_system (XPROCESS (proc), val);
1625 /* Note: At this moment, the above coding system may leave
1626 text-conversion or eol-conversion unspecified. They will be
1627 decided after we read output from the process and decode it by
1628 some coding system, or just before we actually send a text to
1629 the process. */
1633 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1634 eassert (XPROCESS (proc)->decoding_carryover == 0);
1635 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1637 XPROCESS (proc)->inherit_coding_system_flag
1638 = !(NILP (buffer) || !inherit_process_coding_system);
1640 if (!NILP (program))
1642 Lisp_Object program_args = XCDR (command);
1644 /* If program file name is not absolute, search our path for it.
1645 Put the name we will really use in TEM. */
1646 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1647 && !(SCHARS (program) > 1
1648 && IS_DEVICE_SEP (SREF (program, 1))))
1650 tem = Qnil;
1651 openp (Vexec_path, program, Vexec_suffixes, &tem,
1652 make_number (X_OK), false);
1653 if (NILP (tem))
1654 report_file_error ("Searching for program", program);
1655 tem = Fexpand_file_name (tem, Qnil);
1657 else
1659 if (!NILP (Ffile_directory_p (program)))
1660 error ("Specified program for new process is a directory");
1661 tem = program;
1664 /* Remove "/:" from TEM. */
1665 tem = remove_slash_colon (tem);
1667 Lisp_Object arg_encoding = Qnil;
1669 /* Encode the file name and put it in NEW_ARGV.
1670 That's where the child will use it to execute the program. */
1671 tem = list1 (ENCODE_FILE (tem));
1672 ptrdiff_t new_argc = 1;
1674 /* Here we encode arguments by the coding system used for sending
1675 data to the process. We don't support using different coding
1676 systems for encoding arguments and for encoding data sent to the
1677 process. */
1679 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1681 Lisp_Object arg = XCAR (tem2);
1682 CHECK_STRING (arg);
1683 if (STRING_MULTIBYTE (arg))
1685 if (NILP (arg_encoding))
1686 arg_encoding = (complement_process_encoding_system
1687 (XPROCESS (proc)->encode_coding_system));
1688 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1690 tem = Fcons (arg, tem);
1691 new_argc++;
1694 /* Now that everything is encoded we can collect the strings into
1695 NEW_ARGV. */
1696 char **new_argv;
1697 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1698 new_argv[new_argc] = 0;
1700 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1702 new_argv[i] = SSDATA (XCAR (tem));
1703 tem = XCDR (tem);
1706 create_process (proc, new_argv, current_dir);
1708 else
1709 create_pty (proc);
1711 SAFE_FREE ();
1712 return unbind_to (count, proc);
1715 /* If PROC doesn't have its pid set, then an error was signaled and
1716 the process wasn't started successfully, so remove it. */
1717 static void
1718 start_process_unwind (Lisp_Object proc)
1720 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1721 remove_process (proc);
1724 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1726 static void
1727 close_process_fd (int *fd_addr)
1729 int fd = *fd_addr;
1730 if (0 <= fd)
1732 *fd_addr = -1;
1733 emacs_close (fd);
1737 /* Indexes of file descriptors in open_fds. */
1738 enum
1740 /* The pipe from Emacs to its subprocess. */
1741 SUBPROCESS_STDIN,
1742 WRITE_TO_SUBPROCESS,
1744 /* The main pipe from the subprocess to Emacs. */
1745 READ_FROM_SUBPROCESS,
1746 SUBPROCESS_STDOUT,
1748 /* The pipe from the subprocess to Emacs that is closed when the
1749 subprocess execs. */
1750 READ_FROM_EXEC_MONITOR,
1751 EXEC_MONITOR_OUTPUT
1754 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1756 static void
1757 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1759 struct Lisp_Process *p = XPROCESS (process);
1760 int inchannel, outchannel;
1761 pid_t pid;
1762 int vfork_errno;
1763 int forkin, forkout, forkerr = -1;
1764 bool pty_flag = 0;
1765 char pty_name[PTY_NAME_SIZE];
1766 Lisp_Object lisp_pty_name = Qnil;
1767 sigset_t oldset;
1769 inchannel = outchannel = -1;
1771 if (p->pty_flag)
1772 outchannel = inchannel = allocate_pty (pty_name);
1774 if (inchannel >= 0)
1776 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1777 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1778 /* On most USG systems it does not work to open the pty's tty here,
1779 then close it and reopen it in the child. */
1780 /* Don't let this terminal become our controlling terminal
1781 (in case we don't have one). */
1782 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1783 if (forkin < 0)
1784 report_file_error ("Opening pty", Qnil);
1785 p->open_fd[SUBPROCESS_STDIN] = forkin;
1786 #else
1787 forkin = forkout = -1;
1788 #endif /* not USG, or USG_SUBTTY_WORKS */
1789 pty_flag = 1;
1790 lisp_pty_name = build_string (pty_name);
1792 else
1794 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1795 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1796 report_file_error ("Creating pipe", Qnil);
1797 forkin = p->open_fd[SUBPROCESS_STDIN];
1798 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1799 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1800 forkout = p->open_fd[SUBPROCESS_STDOUT];
1802 if (!NILP (p->stderrproc))
1804 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1806 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1808 /* Close unnecessary file descriptors. */
1809 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1810 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1814 #ifndef WINDOWSNT
1815 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1816 report_file_error ("Creating pipe", Qnil);
1817 #endif
1819 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1820 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1822 /* Record this as an active process, with its channels. */
1823 chan_process[inchannel] = process;
1824 p->infd = inchannel;
1825 p->outfd = outchannel;
1827 /* Previously we recorded the tty descriptor used in the subprocess.
1828 It was only used for getting the foreground tty process, so now
1829 we just reopen the device (see emacs_get_tty_pgrp) as this is
1830 more portable (see USG_SUBTTY_WORKS above). */
1832 p->pty_flag = pty_flag;
1833 pset_status (p, Qrun);
1835 if (!EQ (p->command, Qt))
1837 FD_SET (inchannel, &input_wait_mask);
1838 FD_SET (inchannel, &non_keyboard_wait_mask);
1841 if (inchannel > max_process_desc)
1842 max_process_desc = inchannel;
1844 /* This may signal an error. */
1845 setup_process_coding_systems (process);
1847 block_input ();
1848 block_child_signal (&oldset);
1850 #ifndef WINDOWSNT
1851 /* vfork, and prevent local vars from being clobbered by the vfork. */
1852 Lisp_Object volatile current_dir_volatile = current_dir;
1853 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1854 char **volatile new_argv_volatile = new_argv;
1855 int volatile forkin_volatile = forkin;
1856 int volatile forkout_volatile = forkout;
1857 int volatile forkerr_volatile = forkerr;
1858 struct Lisp_Process *p_volatile = p;
1860 pid = vfork ();
1862 current_dir = current_dir_volatile;
1863 lisp_pty_name = lisp_pty_name_volatile;
1864 new_argv = new_argv_volatile;
1865 forkin = forkin_volatile;
1866 forkout = forkout_volatile;
1867 forkerr = forkerr_volatile;
1868 p = p_volatile;
1870 pty_flag = p->pty_flag;
1872 if (pid == 0)
1873 #endif /* not WINDOWSNT */
1875 /* Make the pty be the controlling terminal of the process. */
1876 #ifdef HAVE_PTYS
1877 /* First, disconnect its current controlling terminal. */
1878 /* We tried doing setsid only if pty_flag, but it caused
1879 process_set_signal to fail on SGI when using a pipe. */
1880 setsid ();
1881 /* Make the pty's terminal the controlling terminal. */
1882 if (pty_flag && forkin >= 0)
1884 #ifdef TIOCSCTTY
1885 /* We ignore the return value
1886 because faith@cs.unc.edu says that is necessary on Linux. */
1887 ioctl (forkin, TIOCSCTTY, 0);
1888 #endif
1890 #if defined (LDISC1)
1891 if (pty_flag && forkin >= 0)
1893 struct termios t;
1894 tcgetattr (forkin, &t);
1895 t.c_lflag = LDISC1;
1896 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1897 emacs_perror ("create_process/tcsetattr LDISC1");
1899 #else
1900 #if defined (NTTYDISC) && defined (TIOCSETD)
1901 if (pty_flag && forkin >= 0)
1903 /* Use new line discipline. */
1904 int ldisc = NTTYDISC;
1905 ioctl (forkin, TIOCSETD, &ldisc);
1907 #endif
1908 #endif
1909 #ifdef TIOCNOTTY
1910 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1911 can do TIOCSPGRP only to the process's controlling tty. */
1912 if (pty_flag)
1914 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1915 I can't test it since I don't have 4.3. */
1916 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1917 if (j >= 0)
1919 ioctl (j, TIOCNOTTY, 0);
1920 emacs_close (j);
1923 #endif /* TIOCNOTTY */
1925 #if !defined (DONT_REOPEN_PTY)
1926 /*** There is a suggestion that this ought to be a
1927 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1928 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1929 that system does seem to need this code, even though
1930 both TIOCSCTTY is defined. */
1931 /* Now close the pty (if we had it open) and reopen it.
1932 This makes the pty the controlling terminal of the subprocess. */
1933 if (pty_flag)
1936 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1937 would work? */
1938 if (forkin >= 0)
1939 emacs_close (forkin);
1940 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1942 if (forkin < 0)
1944 emacs_perror (SSDATA (lisp_pty_name));
1945 _exit (EXIT_CANCELED);
1949 #endif /* not DONT_REOPEN_PTY */
1951 #ifdef SETUP_SLAVE_PTY
1952 if (pty_flag)
1954 SETUP_SLAVE_PTY;
1956 #endif /* SETUP_SLAVE_PTY */
1957 #endif /* HAVE_PTYS */
1959 signal (SIGINT, SIG_DFL);
1960 signal (SIGQUIT, SIG_DFL);
1961 #ifdef SIGPROF
1962 signal (SIGPROF, SIG_DFL);
1963 #endif
1965 /* Emacs ignores SIGPIPE, but the child should not. */
1966 signal (SIGPIPE, SIG_DFL);
1968 /* Stop blocking SIGCHLD in the child. */
1969 unblock_child_signal (&oldset);
1971 if (pty_flag)
1972 child_setup_tty (forkout);
1974 if (forkerr < 0)
1975 forkerr = forkout;
1976 #ifdef WINDOWSNT
1977 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1978 #else /* not WINDOWSNT */
1979 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1980 #endif /* not WINDOWSNT */
1983 /* Back in the parent process. */
1985 vfork_errno = errno;
1986 p->pid = pid;
1987 if (pid >= 0)
1988 p->alive = 1;
1990 /* Stop blocking in the parent. */
1991 unblock_child_signal (&oldset);
1992 unblock_input ();
1994 if (pid < 0)
1995 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1996 else
1998 /* vfork succeeded. */
2000 /* Close the pipe ends that the child uses, or the child's pty. */
2001 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2002 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2004 #ifdef WINDOWSNT
2005 register_child (pid, inchannel);
2006 #endif /* WINDOWSNT */
2008 pset_tty_name (p, lisp_pty_name);
2010 #ifndef WINDOWSNT
2011 /* Wait for child_setup to complete in case that vfork is
2012 actually defined as fork. The descriptor
2013 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2014 of a pipe is closed at the child side either by close-on-exec
2015 on successful execve or the _exit call in child_setup. */
2017 char dummy;
2019 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2020 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2021 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2023 #endif
2024 if (!NILP (p->stderrproc))
2026 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2027 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2032 static void
2033 create_pty (Lisp_Object process)
2035 struct Lisp_Process *p = XPROCESS (process);
2036 char pty_name[PTY_NAME_SIZE];
2037 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2039 if (pty_fd >= 0)
2041 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2042 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2043 /* On most USG systems it does not work to open the pty's tty here,
2044 then close it and reopen it in the child. */
2045 /* Don't let this terminal become our controlling terminal
2046 (in case we don't have one). */
2047 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2048 if (forkout < 0)
2049 report_file_error ("Opening pty", Qnil);
2050 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2051 #if defined (DONT_REOPEN_PTY)
2052 /* In the case that vfork is defined as fork, the parent process
2053 (Emacs) may send some data before the child process completes
2054 tty options setup. So we setup tty before forking. */
2055 child_setup_tty (forkout);
2056 #endif /* DONT_REOPEN_PTY */
2057 #endif /* not USG, or USG_SUBTTY_WORKS */
2059 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2061 /* Record this as an active process, with its channels.
2062 As a result, child_setup will close Emacs's side of the pipes. */
2063 chan_process[pty_fd] = process;
2064 p->infd = pty_fd;
2065 p->outfd = pty_fd;
2067 /* Previously we recorded the tty descriptor used in the subprocess.
2068 It was only used for getting the foreground tty process, so now
2069 we just reopen the device (see emacs_get_tty_pgrp) as this is
2070 more portable (see USG_SUBTTY_WORKS above). */
2072 p->pty_flag = 1;
2073 pset_status (p, Qrun);
2074 setup_process_coding_systems (process);
2076 FD_SET (pty_fd, &input_wait_mask);
2077 FD_SET (pty_fd, &non_keyboard_wait_mask);
2078 if (pty_fd > max_process_desc)
2079 max_process_desc = pty_fd;
2081 pset_tty_name (p, build_string (pty_name));
2084 p->pid = -2;
2087 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2088 0, MANY, 0,
2089 doc: /* Create and return a bidirectional pipe process.
2091 In Emacs, pipes are represented by process objects, so input and
2092 output work as for subprocesses, and `delete-process' closes a pipe.
2093 However, a pipe process has no process id, it cannot be signaled,
2094 and the status codes are different from normal processes.
2096 Arguments are specified as keyword/argument pairs. The following
2097 arguments are defined:
2099 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2101 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2102 with the process. Process output goes at the end of that buffer,
2103 unless you specify an output stream or filter function to handle the
2104 output. If BUFFER is not given, the value of NAME is used.
2106 :coding CODING -- If CODING is a symbol, it specifies the coding
2107 system used for both reading and writing for this process. If CODING
2108 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2109 ENCODING is used for writing.
2111 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2112 the process is running. If BOOL is not given, query before exiting.
2114 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2115 In the stopped state, a pipe process does not accept incoming data,
2116 but you can send outgoing data. The stopped state is cleared by
2117 `continue-process' and set by `stop-process'.
2119 :filter FILTER -- Install FILTER as the process filter.
2121 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2123 usage: (make-pipe-process &rest ARGS) */)
2124 (ptrdiff_t nargs, Lisp_Object *args)
2126 Lisp_Object proc, contact;
2127 struct Lisp_Process *p;
2128 Lisp_Object name, buffer;
2129 Lisp_Object tem;
2130 ptrdiff_t specpdl_count;
2131 int inchannel, outchannel;
2133 if (nargs == 0)
2134 return Qnil;
2136 contact = Flist (nargs, args);
2138 name = Fplist_get (contact, QCname);
2139 CHECK_STRING (name);
2140 proc = make_process (name);
2141 specpdl_count = SPECPDL_INDEX ();
2142 record_unwind_protect (remove_process, proc);
2143 p = XPROCESS (proc);
2145 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2146 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2147 report_file_error ("Creating pipe", Qnil);
2148 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2149 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2151 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2152 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2154 #ifdef WINDOWSNT
2155 register_aux_fd (inchannel);
2156 #endif
2158 /* Record this as an active process, with its channels. */
2159 chan_process[inchannel] = proc;
2160 p->infd = inchannel;
2161 p->outfd = outchannel;
2163 if (inchannel > max_process_desc)
2164 max_process_desc = inchannel;
2166 buffer = Fplist_get (contact, QCbuffer);
2167 if (NILP (buffer))
2168 buffer = name;
2169 buffer = Fget_buffer_create (buffer);
2170 pset_buffer (p, buffer);
2172 pset_childp (p, contact);
2173 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2174 pset_type (p, Qpipe);
2175 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2176 pset_filter (p, Fplist_get (contact, QCfilter));
2177 eassert (NILP (p->log));
2178 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2179 p->kill_without_query = 1;
2180 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2181 pset_command (p, Qt);
2182 eassert (! p->pty_flag);
2184 if (!EQ (p->command, Qt))
2186 FD_SET (inchannel, &input_wait_mask);
2187 FD_SET (inchannel, &non_keyboard_wait_mask);
2189 p->adaptive_read_buffering
2190 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2191 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2193 /* Make the process marker point into the process buffer (if any). */
2194 if (BUFFERP (buffer))
2195 set_marker_both (p->mark, buffer,
2196 BUF_ZV (XBUFFER (buffer)),
2197 BUF_ZV_BYTE (XBUFFER (buffer)));
2200 /* Setup coding systems for communicating with the network stream. */
2202 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2203 Lisp_Object coding_systems = Qt;
2204 Lisp_Object val;
2206 tem = Fplist_get (contact, QCcoding);
2207 val = Qnil;
2208 if (!NILP (tem))
2210 val = tem;
2211 if (CONSP (val))
2212 val = XCAR (val);
2214 else if (!NILP (Vcoding_system_for_read))
2215 val = Vcoding_system_for_read;
2216 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2217 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2218 /* We dare not decode end-of-line format by setting VAL to
2219 Qraw_text, because the existing Emacs Lisp libraries
2220 assume that they receive bare code including a sequence of
2221 CR LF. */
2222 val = Qnil;
2223 else
2225 if (CONSP (coding_systems))
2226 val = XCAR (coding_systems);
2227 else if (CONSP (Vdefault_process_coding_system))
2228 val = XCAR (Vdefault_process_coding_system);
2229 else
2230 val = Qnil;
2232 pset_decode_coding_system (p, val);
2234 if (!NILP (tem))
2236 val = tem;
2237 if (CONSP (val))
2238 val = XCDR (val);
2240 else if (!NILP (Vcoding_system_for_write))
2241 val = Vcoding_system_for_write;
2242 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2243 val = Qnil;
2244 else
2246 if (CONSP (coding_systems))
2247 val = XCDR (coding_systems);
2248 else if (CONSP (Vdefault_process_coding_system))
2249 val = XCDR (Vdefault_process_coding_system);
2250 else
2251 val = Qnil;
2253 pset_encode_coding_system (p, val);
2255 /* This may signal an error. */
2256 setup_process_coding_systems (proc);
2258 specpdl_ptr = specpdl + specpdl_count;
2260 return proc;
2264 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2265 The address family of sa is not included in the result. */
2267 Lisp_Object
2268 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2270 Lisp_Object address;
2271 ptrdiff_t i;
2272 unsigned char *cp;
2273 struct Lisp_Vector *p;
2275 /* Workaround for a bug in getsockname on BSD: Names bound to
2276 sockets in the UNIX domain are inaccessible; getsockname returns
2277 a zero length name. */
2278 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2279 return empty_unibyte_string;
2281 switch (sa->sa_family)
2283 case AF_INET:
2285 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2286 len = sizeof (sin->sin_addr) + 1;
2287 address = Fmake_vector (make_number (len), Qnil);
2288 p = XVECTOR (address);
2289 p->contents[--len] = make_number (ntohs (sin->sin_port));
2290 cp = (unsigned char *) &sin->sin_addr;
2291 break;
2293 #ifdef AF_INET6
2294 case AF_INET6:
2296 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2297 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2298 len = sizeof (sin6->sin6_addr) / 2 + 1;
2299 address = Fmake_vector (make_number (len), Qnil);
2300 p = XVECTOR (address);
2301 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2302 for (i = 0; i < len; i++)
2303 p->contents[i] = make_number (ntohs (ip6[i]));
2304 return address;
2306 #endif
2307 #ifdef HAVE_LOCAL_SOCKETS
2308 case AF_LOCAL:
2310 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2311 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2312 /* If the first byte is NUL, the name is a Linux abstract
2313 socket name, and the name can contain embedded NULs. If
2314 it's not, we have a NUL-terminated string. Be careful not
2315 to walk past the end of the object looking for the name
2316 terminator, however. */
2317 if (name_length > 0 && sockun->sun_path[0] != '\0')
2319 const char *terminator
2320 = memchr (sockun->sun_path, '\0', name_length);
2322 if (terminator)
2323 name_length = terminator - (const char *) sockun->sun_path;
2326 return make_unibyte_string (sockun->sun_path, name_length);
2328 #endif
2329 default:
2330 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2331 address = Fcons (make_number (sa->sa_family),
2332 Fmake_vector (make_number (len), Qnil));
2333 p = XVECTOR (XCDR (address));
2334 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2335 break;
2338 i = 0;
2339 while (i < len)
2340 p->contents[i++] = make_number (*cp++);
2342 return address;
2345 /* Convert an internal struct addrinfo to a Lisp object. */
2347 static Lisp_Object
2348 conv_addrinfo_to_lisp (struct addrinfo *res)
2350 Lisp_Object protocol = make_number (res->ai_protocol);
2351 eassert (XINT (protocol) == res->ai_protocol);
2352 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2356 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2358 static ptrdiff_t
2359 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2361 struct Lisp_Vector *p;
2363 if (VECTORP (address))
2365 p = XVECTOR (address);
2366 if (p->header.size == 5)
2368 *familyp = AF_INET;
2369 return sizeof (struct sockaddr_in);
2371 #ifdef AF_INET6
2372 else if (p->header.size == 9)
2374 *familyp = AF_INET6;
2375 return sizeof (struct sockaddr_in6);
2377 #endif
2379 #ifdef HAVE_LOCAL_SOCKETS
2380 else if (STRINGP (address))
2382 *familyp = AF_LOCAL;
2383 return sizeof (struct sockaddr_un);
2385 #endif
2386 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2387 && VECTORP (XCDR (address)))
2389 struct sockaddr *sa;
2390 p = XVECTOR (XCDR (address));
2391 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2392 return 0;
2393 *familyp = XINT (XCAR (address));
2394 return p->header.size + sizeof (sa->sa_family);
2396 return 0;
2399 /* Convert an address object (vector or string) to an internal sockaddr.
2401 The address format has been basically validated by
2402 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2403 it could have come from user data. So if FAMILY is not valid,
2404 we return after zeroing *SA. */
2406 static void
2407 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2409 register struct Lisp_Vector *p;
2410 register unsigned char *cp = NULL;
2411 register int i;
2412 EMACS_INT hostport;
2414 memset (sa, 0, len);
2416 if (VECTORP (address))
2418 p = XVECTOR (address);
2419 if (family == AF_INET)
2421 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2422 len = sizeof (sin->sin_addr) + 1;
2423 hostport = XINT (p->contents[--len]);
2424 sin->sin_port = htons (hostport);
2425 cp = (unsigned char *)&sin->sin_addr;
2426 sa->sa_family = family;
2428 #ifdef AF_INET6
2429 else if (family == AF_INET6)
2431 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2432 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2433 len = sizeof (sin6->sin6_addr) / 2 + 1;
2434 hostport = XINT (p->contents[--len]);
2435 sin6->sin6_port = htons (hostport);
2436 for (i = 0; i < len; i++)
2437 if (INTEGERP (p->contents[i]))
2439 int j = XFASTINT (p->contents[i]) & 0xffff;
2440 ip6[i] = ntohs (j);
2442 sa->sa_family = family;
2443 return;
2445 #endif
2446 else
2447 return;
2449 else if (STRINGP (address))
2451 #ifdef HAVE_LOCAL_SOCKETS
2452 if (family == AF_LOCAL)
2454 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2455 cp = SDATA (address);
2456 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2457 sockun->sun_path[i] = *cp++;
2458 sa->sa_family = family;
2460 #endif
2461 return;
2463 else
2465 p = XVECTOR (XCDR (address));
2466 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2469 for (i = 0; i < len; i++)
2470 if (INTEGERP (p->contents[i]))
2471 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2474 #ifdef DATAGRAM_SOCKETS
2475 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2476 1, 1, 0,
2477 doc: /* Get the current datagram address associated with PROCESS.
2478 If PROCESS is a non-blocking network process that hasn't been fully
2479 set up yet, this function will block until socket setup has completed. */)
2480 (Lisp_Object process)
2482 int channel;
2484 CHECK_PROCESS (process);
2486 if (NETCONN_P (process))
2487 wait_for_socket_fds (process, "process-datagram-address");
2489 if (!DATAGRAM_CONN_P (process))
2490 return Qnil;
2492 channel = XPROCESS (process)->infd;
2493 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2494 datagram_address[channel].len);
2497 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2498 2, 2, 0,
2499 doc: /* Set the datagram address for PROCESS to ADDRESS.
2500 Return nil upon error setting address, ADDRESS otherwise.
2502 If PROCESS is a non-blocking network process that hasn't been fully
2503 set up yet, this function will block until socket setup has completed. */)
2504 (Lisp_Object process, Lisp_Object address)
2506 int channel;
2507 int family;
2508 ptrdiff_t len;
2510 CHECK_PROCESS (process);
2512 if (NETCONN_P (process))
2513 wait_for_socket_fds (process, "set-process-datagram-address");
2515 if (!DATAGRAM_CONN_P (process))
2516 return Qnil;
2518 channel = XPROCESS (process)->infd;
2520 len = get_lisp_to_sockaddr_size (address, &family);
2521 if (len == 0 || datagram_address[channel].len != len)
2522 return Qnil;
2523 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2524 return address;
2526 #endif
2529 static const struct socket_options {
2530 /* The name of this option. Should be lowercase version of option
2531 name without SO_ prefix. */
2532 const char *name;
2533 /* Option level SOL_... */
2534 int optlevel;
2535 /* Option number SO_... */
2536 int optnum;
2537 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2538 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2539 } socket_options[] =
2541 #ifdef SO_BINDTODEVICE
2542 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2543 #endif
2544 #ifdef SO_BROADCAST
2545 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2546 #endif
2547 #ifdef SO_DONTROUTE
2548 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2549 #endif
2550 #ifdef SO_KEEPALIVE
2551 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2552 #endif
2553 #ifdef SO_LINGER
2554 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2555 #endif
2556 #ifdef SO_OOBINLINE
2557 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2558 #endif
2559 #ifdef SO_PRIORITY
2560 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2561 #endif
2562 #ifdef SO_REUSEADDR
2563 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2564 #endif
2565 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2568 /* Set option OPT to value VAL on socket S.
2570 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2571 Signals an error if setting a known option fails.
2574 static int
2575 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2577 char *name;
2578 const struct socket_options *sopt;
2579 int ret = 0;
2581 CHECK_SYMBOL (opt);
2583 name = SSDATA (SYMBOL_NAME (opt));
2584 for (sopt = socket_options; sopt->name; sopt++)
2585 if (strcmp (name, sopt->name) == 0)
2586 break;
2588 switch (sopt->opttype)
2590 case SOPT_BOOL:
2592 int optval;
2593 optval = NILP (val) ? 0 : 1;
2594 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2595 &optval, sizeof (optval));
2596 break;
2599 case SOPT_INT:
2601 int optval;
2602 if (TYPE_RANGED_INTEGERP (int, val))
2603 optval = XINT (val);
2604 else
2605 error ("Bad option value for %s", name);
2606 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2607 &optval, sizeof (optval));
2608 break;
2611 #ifdef SO_BINDTODEVICE
2612 case SOPT_IFNAME:
2614 char devname[IFNAMSIZ + 1];
2616 /* This is broken, at least in the Linux 2.4 kernel.
2617 To unbind, the arg must be a zero integer, not the empty string.
2618 This should work on all systems. KFS. 2003-09-23. */
2619 memset (devname, 0, sizeof devname);
2620 if (STRINGP (val))
2622 char *arg = SSDATA (val);
2623 int len = min (strlen (arg), IFNAMSIZ);
2624 memcpy (devname, arg, len);
2626 else if (!NILP (val))
2627 error ("Bad option value for %s", name);
2628 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2629 devname, IFNAMSIZ);
2630 break;
2632 #endif
2634 #ifdef SO_LINGER
2635 case SOPT_LINGER:
2637 struct linger linger;
2639 linger.l_onoff = 1;
2640 linger.l_linger = 0;
2641 if (TYPE_RANGED_INTEGERP (int, val))
2642 linger.l_linger = XINT (val);
2643 else
2644 linger.l_onoff = NILP (val) ? 0 : 1;
2645 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2646 &linger, sizeof (linger));
2647 break;
2649 #endif
2651 default:
2652 return 0;
2655 if (ret < 0)
2657 int setsockopt_errno = errno;
2658 report_file_errno ("Cannot set network option", list2 (opt, val),
2659 setsockopt_errno);
2662 return (1 << sopt->optbit);
2666 DEFUN ("set-network-process-option",
2667 Fset_network_process_option, Sset_network_process_option,
2668 3, 4, 0,
2669 doc: /* For network process PROCESS set option OPTION to value VALUE.
2670 See `make-network-process' for a list of options and values.
2671 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2672 OPTION is not a supported option, return nil instead; otherwise return t.
2674 If PROCESS is a non-blocking network process that hasn't been fully
2675 set up yet, this function will block until socket setup has completed. */)
2676 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2678 int s;
2679 struct Lisp_Process *p;
2681 CHECK_PROCESS (process);
2682 p = XPROCESS (process);
2683 if (!NETCONN1_P (p))
2684 error ("Process is not a network process");
2686 wait_for_socket_fds (process, "set-network-process-option");
2688 s = p->infd;
2689 if (s < 0)
2690 error ("Process is not running");
2692 if (set_socket_option (s, option, value))
2694 pset_childp (p, Fplist_put (p->childp, option, value));
2695 return Qt;
2698 if (NILP (no_error))
2699 error ("Unknown or unsupported option");
2701 return Qnil;
2705 DEFUN ("serial-process-configure",
2706 Fserial_process_configure,
2707 Sserial_process_configure,
2708 0, MANY, 0,
2709 doc: /* Configure speed, bytesize, etc. of a serial process.
2711 Arguments are specified as keyword/argument pairs. Attributes that
2712 are not given are re-initialized from the process's current
2713 configuration (available via the function `process-contact') or set to
2714 reasonable default values. The following arguments are defined:
2716 :process PROCESS
2717 :name NAME
2718 :buffer BUFFER
2719 :port PORT
2720 -- Any of these arguments can be given to identify the process that is
2721 to be configured. If none of these arguments is given, the current
2722 buffer's process is used.
2724 :speed SPEED -- SPEED is the speed of the serial port in bits per
2725 second, also called baud rate. Any value can be given for SPEED, but
2726 most serial ports work only at a few defined values between 1200 and
2727 115200, with 9600 being the most common value. If SPEED is nil, the
2728 serial port is not configured any further, i.e., all other arguments
2729 are ignored. This may be useful for special serial ports such as
2730 Bluetooth-to-serial converters which can only be configured through AT
2731 commands. A value of nil for SPEED can be used only when passed
2732 through `make-serial-process' or `serial-term'.
2734 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2735 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2737 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2738 `odd' (use odd parity), or the symbol `even' (use even parity). If
2739 PARITY is not given, no parity is used.
2741 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2742 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2743 is not given or nil, 1 stopbit is used.
2745 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2746 flowcontrol to be used, which is either nil (don't use flowcontrol),
2747 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2748 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2749 flowcontrol is used.
2751 `serial-process-configure' is called by `make-serial-process' for the
2752 initial configuration of the serial port.
2754 Examples:
2756 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2758 \(serial-process-configure
2759 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2761 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2763 usage: (serial-process-configure &rest ARGS) */)
2764 (ptrdiff_t nargs, Lisp_Object *args)
2766 struct Lisp_Process *p;
2767 Lisp_Object contact = Qnil;
2768 Lisp_Object proc = Qnil;
2770 contact = Flist (nargs, args);
2772 proc = Fplist_get (contact, QCprocess);
2773 if (NILP (proc))
2774 proc = Fplist_get (contact, QCname);
2775 if (NILP (proc))
2776 proc = Fplist_get (contact, QCbuffer);
2777 if (NILP (proc))
2778 proc = Fplist_get (contact, QCport);
2779 proc = get_process (proc);
2780 p = XPROCESS (proc);
2781 if (!EQ (p->type, Qserial))
2782 error ("Not a serial process");
2784 if (NILP (Fplist_get (p->childp, QCspeed)))
2785 return Qnil;
2787 serial_configure (p, contact);
2788 return Qnil;
2791 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2792 0, MANY, 0,
2793 doc: /* Create and return a serial port process.
2795 In Emacs, serial port connections are represented by process objects,
2796 so input and output work as for subprocesses, and `delete-process'
2797 closes a serial port connection. However, a serial process has no
2798 process id, it cannot be signaled, and the status codes are different
2799 from normal processes.
2801 `make-serial-process' creates a process and a buffer, on which you
2802 probably want to use `process-send-string'. Try \\[serial-term] for
2803 an interactive terminal. See below for examples.
2805 Arguments are specified as keyword/argument pairs. The following
2806 arguments are defined:
2808 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2809 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2810 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2811 the backslashes in strings).
2813 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2814 which this function calls.
2816 :name NAME -- NAME is the name of the process. If NAME is not given,
2817 the value of PORT is used.
2819 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2820 with the process. Process output goes at the end of that buffer,
2821 unless you specify an output stream or filter function to handle the
2822 output. If BUFFER is not given, the value of NAME is used.
2824 :coding CODING -- If CODING is a symbol, it specifies the coding
2825 system used for both reading and writing for this process. If CODING
2826 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2827 ENCODING is used for writing.
2829 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2830 the process is running. If BOOL is not given, query before exiting.
2832 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2833 In the stopped state, a serial process does not accept incoming data,
2834 but you can send outgoing data. The stopped state is cleared by
2835 `continue-process' and set by `stop-process'.
2837 :filter FILTER -- Install FILTER as the process filter.
2839 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2841 :plist PLIST -- Install PLIST as the initial plist of the process.
2843 :bytesize
2844 :parity
2845 :stopbits
2846 :flowcontrol
2847 -- This function calls `serial-process-configure' to handle these
2848 arguments.
2850 The original argument list, possibly modified by later configuration,
2851 is available via the function `process-contact'.
2853 Examples:
2855 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2857 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2859 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2861 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2863 usage: (make-serial-process &rest ARGS) */)
2864 (ptrdiff_t nargs, Lisp_Object *args)
2866 int fd = -1;
2867 Lisp_Object proc, contact, port;
2868 struct Lisp_Process *p;
2869 Lisp_Object name, buffer;
2870 Lisp_Object tem, val;
2871 ptrdiff_t specpdl_count;
2873 if (nargs == 0)
2874 return Qnil;
2876 contact = Flist (nargs, args);
2878 port = Fplist_get (contact, QCport);
2879 if (NILP (port))
2880 error ("No port specified");
2881 CHECK_STRING (port);
2883 if (NILP (Fplist_member (contact, QCspeed)))
2884 error (":speed not specified");
2885 if (!NILP (Fplist_get (contact, QCspeed)))
2886 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2888 name = Fplist_get (contact, QCname);
2889 if (NILP (name))
2890 name = port;
2891 CHECK_STRING (name);
2892 proc = make_process (name);
2893 specpdl_count = SPECPDL_INDEX ();
2894 record_unwind_protect (remove_process, proc);
2895 p = XPROCESS (proc);
2897 fd = serial_open (port);
2898 p->open_fd[SUBPROCESS_STDIN] = fd;
2899 p->infd = fd;
2900 p->outfd = fd;
2901 if (fd > max_process_desc)
2902 max_process_desc = fd;
2903 chan_process[fd] = proc;
2905 buffer = Fplist_get (contact, QCbuffer);
2906 if (NILP (buffer))
2907 buffer = name;
2908 buffer = Fget_buffer_create (buffer);
2909 pset_buffer (p, buffer);
2911 pset_childp (p, contact);
2912 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2913 pset_type (p, Qserial);
2914 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2915 pset_filter (p, Fplist_get (contact, QCfilter));
2916 eassert (NILP (p->log));
2917 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2918 p->kill_without_query = 1;
2919 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2920 pset_command (p, Qt);
2921 eassert (! p->pty_flag);
2923 if (!EQ (p->command, Qt))
2925 FD_SET (fd, &input_wait_mask);
2926 FD_SET (fd, &non_keyboard_wait_mask);
2929 if (BUFFERP (buffer))
2931 set_marker_both (p->mark, buffer,
2932 BUF_ZV (XBUFFER (buffer)),
2933 BUF_ZV_BYTE (XBUFFER (buffer)));
2936 tem = Fplist_member (contact, QCcoding);
2937 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2938 tem = Qnil;
2940 val = Qnil;
2941 if (!NILP (tem))
2943 val = XCAR (XCDR (tem));
2944 if (CONSP (val))
2945 val = XCAR (val);
2947 else if (!NILP (Vcoding_system_for_read))
2948 val = Vcoding_system_for_read;
2949 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2950 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2951 val = Qnil;
2952 pset_decode_coding_system (p, val);
2954 val = Qnil;
2955 if (!NILP (tem))
2957 val = XCAR (XCDR (tem));
2958 if (CONSP (val))
2959 val = XCDR (val);
2961 else if (!NILP (Vcoding_system_for_write))
2962 val = Vcoding_system_for_write;
2963 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2964 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2965 val = Qnil;
2966 pset_encode_coding_system (p, val);
2968 setup_process_coding_systems (proc);
2969 pset_decoding_buf (p, empty_unibyte_string);
2970 eassert (p->decoding_carryover == 0);
2971 pset_encoding_buf (p, empty_unibyte_string);
2972 p->inherit_coding_system_flag
2973 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2975 Fserial_process_configure (nargs, args);
2977 specpdl_ptr = specpdl + specpdl_count;
2979 return proc;
2982 static void
2983 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
2984 Lisp_Object service, Lisp_Object name)
2986 Lisp_Object tem;
2987 struct Lisp_Process *p = XPROCESS (proc);
2988 Lisp_Object contact = p->childp;
2989 Lisp_Object coding_systems = Qt;
2990 Lisp_Object val;
2992 tem = Fplist_member (contact, QCcoding);
2993 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2994 tem = Qnil; /* No error message (too late!). */
2996 /* Setup coding systems for communicating with the network stream. */
2997 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2999 if (!NILP (tem))
3001 val = XCAR (XCDR (tem));
3002 if (CONSP (val))
3003 val = XCAR (val);
3005 else if (!NILP (Vcoding_system_for_read))
3006 val = Vcoding_system_for_read;
3007 else if ((!NILP (p->buffer)
3008 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3009 || (NILP (p->buffer)
3010 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3011 /* We dare not decode end-of-line format by setting VAL to
3012 Qraw_text, because the existing Emacs Lisp libraries
3013 assume that they receive bare code including a sequence of
3014 CR LF. */
3015 val = Qnil;
3016 else
3018 if (NILP (host) || NILP (service))
3019 coding_systems = Qnil;
3020 else
3021 coding_systems = CALLN (Ffind_operation_coding_system,
3022 Qopen_network_stream, name, p->buffer,
3023 host, service);
3024 if (CONSP (coding_systems))
3025 val = XCAR (coding_systems);
3026 else if (CONSP (Vdefault_process_coding_system))
3027 val = XCAR (Vdefault_process_coding_system);
3028 else
3029 val = Qnil;
3031 pset_decode_coding_system (p, val);
3033 if (!NILP (tem))
3035 val = XCAR (XCDR (tem));
3036 if (CONSP (val))
3037 val = XCDR (val);
3039 else if (!NILP (Vcoding_system_for_write))
3040 val = Vcoding_system_for_write;
3041 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3042 val = Qnil;
3043 else
3045 if (EQ (coding_systems, Qt))
3047 if (NILP (host) || NILP (service))
3048 coding_systems = Qnil;
3049 else
3050 coding_systems = CALLN (Ffind_operation_coding_system,
3051 Qopen_network_stream, name, p->buffer,
3052 host, service);
3054 if (CONSP (coding_systems))
3055 val = XCDR (coding_systems);
3056 else if (CONSP (Vdefault_process_coding_system))
3057 val = XCDR (Vdefault_process_coding_system);
3058 else
3059 val = Qnil;
3061 pset_encode_coding_system (p, val);
3063 pset_decoding_buf (p, empty_unibyte_string);
3064 p->decoding_carryover = 0;
3065 pset_encoding_buf (p, empty_unibyte_string);
3067 p->inherit_coding_system_flag
3068 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3071 #ifdef HAVE_GNUTLS
3072 static void
3073 finish_after_tls_connection (Lisp_Object proc)
3075 struct Lisp_Process *p = XPROCESS (proc);
3076 Lisp_Object contact = p->childp;
3077 Lisp_Object result = Qt;
3079 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3080 result = call3 (Qnsm_verify_connection,
3081 proc,
3082 Fplist_get (contact, QChost),
3083 Fplist_get (contact, QCservice));
3085 if (NILP (result))
3087 pset_status (p, list2 (Qfailed,
3088 build_string ("The Network Security Manager stopped the connections")));
3089 deactivate_process (proc);
3091 else
3093 /* If we cleared the connection wait mask before we did
3094 the TLS setup, then we have to say that the process
3095 is finally "open" here. */
3096 if (! FD_ISSET (p->outfd, &connect_wait_mask))
3098 pset_status (p, Qrun);
3099 /* Execute the sentinel here. If we had relied on
3100 status_notify to do it later, it will read input
3101 from the process before calling the sentinel. */
3102 exec_sentinel (proc, build_string ("open\n"));
3106 #endif
3108 static void
3109 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3110 Lisp_Object use_external_socket_p)
3112 ptrdiff_t count = SPECPDL_INDEX ();
3113 int s = -1, outch, inch;
3114 int xerrno = 0;
3115 int family;
3116 struct sockaddr *sa = NULL;
3117 int ret;
3118 ptrdiff_t addrlen;
3119 struct Lisp_Process *p = XPROCESS (proc);
3120 Lisp_Object contact = p->childp;
3121 int optbits = 0;
3122 int socket_to_use = -1;
3124 if (!NILP (use_external_socket_p))
3126 socket_to_use = external_sock_fd;
3128 /* Ensure we don't consume the external socket twice. */
3129 external_sock_fd = -1;
3132 /* Do this in case we never enter the while-loop below. */
3133 s = -1;
3135 while (!NILP (addrinfos))
3137 Lisp_Object addrinfo = XCAR (addrinfos);
3138 addrinfos = XCDR (addrinfos);
3139 int protocol = XINT (XCAR (addrinfo));
3140 Lisp_Object ip_address = XCDR (addrinfo);
3142 #ifdef WINDOWSNT
3143 retry_connect:
3144 #endif
3146 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3147 if (sa)
3148 free (sa);
3149 sa = xmalloc (addrlen);
3150 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3152 s = socket_to_use;
3153 if (s < 0)
3155 int socktype = p->socktype | SOCK_CLOEXEC;
3156 if (p->is_non_blocking_client)
3157 socktype |= SOCK_NONBLOCK;
3158 s = socket (family, socktype, protocol);
3159 if (s < 0)
3161 xerrno = errno;
3162 continue;
3166 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3168 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3169 if (ret < 0)
3171 xerrno = errno;
3172 emacs_close (s);
3173 s = -1;
3174 if (0 <= socket_to_use)
3175 break;
3176 continue;
3180 #ifdef DATAGRAM_SOCKETS
3181 if (!p->is_server && p->socktype == SOCK_DGRAM)
3182 break;
3183 #endif /* DATAGRAM_SOCKETS */
3185 /* Make us close S if quit. */
3186 record_unwind_protect_int (close_file_unwind, s);
3188 /* Parse network options in the arg list. We simply ignore anything
3189 which isn't a known option (including other keywords). An error
3190 is signaled if setting a known option fails. */
3192 Lisp_Object params = contact, key, val;
3194 while (!NILP (params))
3196 key = XCAR (params);
3197 params = XCDR (params);
3198 val = XCAR (params);
3199 params = XCDR (params);
3200 optbits |= set_socket_option (s, key, val);
3204 if (p->is_server)
3206 /* Configure as a server socket. */
3208 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3209 explicit :reuseaddr key to override this. */
3210 #ifdef HAVE_LOCAL_SOCKETS
3211 if (family != AF_LOCAL)
3212 #endif
3213 if (!(optbits & (1 << OPIX_REUSEADDR)))
3215 int optval = 1;
3216 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3217 report_file_error ("Cannot set reuse option on server socket", Qnil);
3220 /* If passed a socket descriptor, it should be already bound. */
3221 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3222 report_file_error ("Cannot bind server socket", Qnil);
3224 #ifdef HAVE_GETSOCKNAME
3225 if (p->port == 0)
3227 struct sockaddr_in sa1;
3228 socklen_t len1 = sizeof (sa1);
3229 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3231 Lisp_Object service;
3232 service = make_number (ntohs (sa1.sin_port));
3233 contact = Fplist_put (contact, QCservice, service);
3234 /* Save the port number so that we can stash it in
3235 the process object later. */
3236 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3239 #endif
3241 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3242 report_file_error ("Cannot listen on server socket", Qnil);
3244 break;
3247 immediate_quit = 1;
3248 QUIT;
3250 ret = connect (s, sa, addrlen);
3251 xerrno = errno;
3253 if (ret == 0 || xerrno == EISCONN)
3255 /* The unwind-protect will be discarded afterwards.
3256 Likewise for immediate_quit. */
3257 break;
3260 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3261 break;
3263 #ifndef WINDOWSNT
3264 if (xerrno == EINTR)
3266 /* Unlike most other syscalls connect() cannot be called
3267 again. (That would return EALREADY.) The proper way to
3268 wait for completion is pselect(). */
3269 int sc;
3270 socklen_t len;
3271 fd_set fdset;
3272 retry_select:
3273 FD_ZERO (&fdset);
3274 FD_SET (s, &fdset);
3275 QUIT;
3276 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3277 if (sc == -1)
3279 if (errno == EINTR)
3280 goto retry_select;
3281 else
3282 report_file_error ("Failed select", Qnil);
3284 eassert (sc > 0);
3286 len = sizeof xerrno;
3287 eassert (FD_ISSET (s, &fdset));
3288 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3289 report_file_error ("Failed getsockopt", Qnil);
3290 if (xerrno == 0)
3291 break;
3292 if (NILP (addrinfos))
3293 report_file_errno ("Failed connect", Qnil, xerrno);
3295 #endif /* !WINDOWSNT */
3297 immediate_quit = 0;
3299 /* Discard the unwind protect closing S. */
3300 specpdl_ptr = specpdl + count;
3301 emacs_close (s);
3302 s = -1;
3303 if (0 <= socket_to_use)
3304 break;
3306 #ifdef WINDOWSNT
3307 if (xerrno == EINTR)
3308 goto retry_connect;
3309 #endif
3312 if (s >= 0)
3314 #ifdef DATAGRAM_SOCKETS
3315 if (p->socktype == SOCK_DGRAM)
3317 if (datagram_address[s].sa)
3318 emacs_abort ();
3320 datagram_address[s].sa = xmalloc (addrlen);
3321 datagram_address[s].len = addrlen;
3322 if (p->is_server)
3324 Lisp_Object remote;
3325 memset (datagram_address[s].sa, 0, addrlen);
3326 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3328 int rfamily;
3329 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3330 if (rlen != 0 && rfamily == family
3331 && rlen == addrlen)
3332 conv_lisp_to_sockaddr (rfamily, remote,
3333 datagram_address[s].sa, rlen);
3336 else
3337 memcpy (datagram_address[s].sa, sa, addrlen);
3339 #endif
3341 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3342 conv_sockaddr_to_lisp (sa, addrlen));
3343 #ifdef HAVE_GETSOCKNAME
3344 if (!p->is_server)
3346 struct sockaddr_in sa1;
3347 socklen_t len1 = sizeof (sa1);
3348 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3349 contact = Fplist_put (contact, QClocal,
3350 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3352 #endif
3355 immediate_quit = 0;
3357 if (s < 0)
3359 /* If non-blocking got this far - and failed - assume non-blocking is
3360 not supported after all. This is probably a wrong assumption, but
3361 the normal blocking calls to open-network-stream handles this error
3362 better. */
3363 if (p->is_non_blocking_client)
3364 return;
3366 report_file_errno ((p->is_server
3367 ? "make server process failed"
3368 : "make client process failed"),
3369 contact, xerrno);
3372 inch = s;
3373 outch = s;
3375 chan_process[inch] = proc;
3377 fcntl (inch, F_SETFL, O_NONBLOCK);
3379 p = XPROCESS (proc);
3380 p->open_fd[SUBPROCESS_STDIN] = inch;
3381 p->infd = inch;
3382 p->outfd = outch;
3384 /* Discard the unwind protect for closing S, if any. */
3385 specpdl_ptr = specpdl + count;
3387 if (p->is_server && p->socktype != SOCK_DGRAM)
3388 pset_status (p, Qlisten);
3390 /* Make the process marker point into the process buffer (if any). */
3391 if (BUFFERP (p->buffer))
3392 set_marker_both (p->mark, p->buffer,
3393 BUF_ZV (XBUFFER (p->buffer)),
3394 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3396 if (p->is_non_blocking_client)
3398 /* We may get here if connect did succeed immediately. However,
3399 in that case, we still need to signal this like a non-blocking
3400 connection. */
3401 if (! (connecting_status (p->status)
3402 && EQ (XCDR (p->status), addrinfos)))
3403 pset_status (p, Fcons (Qconnect, addrinfos));
3404 if (!FD_ISSET (inch, &connect_wait_mask))
3406 FD_SET (inch, &connect_wait_mask);
3407 FD_SET (inch, &write_mask);
3408 num_pending_connects++;
3411 else
3412 /* A server may have a client filter setting of Qt, but it must
3413 still listen for incoming connects unless it is stopped. */
3414 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3415 || (EQ (p->status, Qlisten) && NILP (p->command)))
3417 FD_SET (inch, &input_wait_mask);
3418 FD_SET (inch, &non_keyboard_wait_mask);
3421 if (inch > max_process_desc)
3422 max_process_desc = inch;
3424 /* Set up the masks based on the process filter. */
3425 set_process_filter_masks (p);
3427 setup_process_coding_systems (proc);
3429 #ifdef HAVE_GNUTLS
3430 /* Continue the asynchronous connection. */
3431 if (!NILP (p->gnutls_boot_parameters))
3433 Lisp_Object boot, params = p->gnutls_boot_parameters;
3435 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3436 p->gnutls_boot_parameters = Qnil;
3438 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3439 /* Run sentinels, etc. */
3440 finish_after_tls_connection (proc);
3441 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3443 deactivate_process (proc);
3444 if (NILP (boot))
3445 pset_status (p, list2 (Qfailed,
3446 build_string ("TLS negotiation failed")));
3447 else
3448 pset_status (p, list2 (Qfailed, boot));
3451 #endif
3455 /* Create a network stream/datagram client/server process. Treated
3456 exactly like a normal process when reading and writing. Primary
3457 differences are in status display and process deletion. A network
3458 connection has no PID; you cannot signal it. All you can do is
3459 stop/continue it and deactivate/close it via delete-process. */
3461 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3462 0, MANY, 0,
3463 doc: /* Create and return a network server or client process.
3465 In Emacs, network connections are represented by process objects, so
3466 input and output work as for subprocesses and `delete-process' closes
3467 a network connection. However, a network process has no process id,
3468 it cannot be signaled, and the status codes are different from normal
3469 processes.
3471 Arguments are specified as keyword/argument pairs. The following
3472 arguments are defined:
3474 :name NAME -- NAME is name for process. It is modified if necessary
3475 to make it unique.
3477 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3478 with the process. Process output goes at end of that buffer, unless
3479 you specify an output stream or filter function to handle the output.
3480 BUFFER may be also nil, meaning that this process is not associated
3481 with any buffer.
3483 :host HOST -- HOST is name of the host to connect to, or its IP
3484 address. The symbol `local' specifies the local host. If specified
3485 for a server process, it must be a valid name or address for the local
3486 host, and only clients connecting to that address will be accepted.
3488 :service SERVICE -- SERVICE is name of the service desired, or an
3489 integer specifying a port number to connect to. If SERVICE is t,
3490 a random port number is selected for the server. A port number can
3491 be specified as an integer string, e.g., "80", as well as an integer.
3493 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3494 stream type connection, `datagram' creates a datagram type connection,
3495 `seqpacket' creates a reliable datagram connection.
3497 :family FAMILY -- FAMILY is the address (and protocol) family for the
3498 service specified by HOST and SERVICE. The default (nil) is to use
3499 whatever address family (IPv4 or IPv6) that is defined for the host
3500 and port number specified by HOST and SERVICE. Other address families
3501 supported are:
3502 local -- for a local (i.e. UNIX) address specified by SERVICE.
3503 ipv4 -- use IPv4 address family only.
3504 ipv6 -- use IPv6 address family only.
3506 :local ADDRESS -- ADDRESS is the local address used for the connection.
3507 This parameter is ignored when opening a client process. When specified
3508 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3510 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3511 connection. This parameter is ignored when opening a stream server
3512 process. For a datagram server process, it specifies the initial
3513 setting of the remote datagram address. When specified for a client
3514 process, the FAMILY, HOST, and SERVICE args are ignored.
3516 The format of ADDRESS depends on the address family:
3517 - An IPv4 address is represented as an vector of integers [A B C D P]
3518 corresponding to numeric IP address A.B.C.D and port number P.
3519 - A local address is represented as a string with the address in the
3520 local address space.
3521 - An "unsupported family" address is represented by a cons (F . AV)
3522 where F is the family number and AV is a vector containing the socket
3523 address data with one element per address data byte. Do not rely on
3524 this format in portable code, as it may depend on implementation
3525 defined constants, data sizes, and data structure alignment.
3527 :coding CODING -- If CODING is a symbol, it specifies the coding
3528 system used for both reading and writing for this process. If CODING
3529 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3530 ENCODING is used for writing.
3532 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3533 process, return without waiting for the connection to complete;
3534 instead, the sentinel function will be called with second arg matching
3535 "open" (if successful) or "failed" when the connect completes.
3536 Default is to use a blocking connect (i.e. wait) for stream type
3537 connections.
3539 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3540 running when Emacs is exited.
3542 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3543 In the stopped state, a server process does not accept new
3544 connections, and a client process does not handle incoming traffic.
3545 The stopped state is cleared by `continue-process' and set by
3546 `stop-process'.
3548 :filter FILTER -- Install FILTER as the process filter.
3550 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3551 process filter are multibyte, otherwise they are unibyte.
3552 If this keyword is not specified, the strings are multibyte if
3553 the default value of `enable-multibyte-characters' is non-nil.
3555 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3557 :log LOG -- Install LOG as the server process log function. This
3558 function is called when the server accepts a network connection from a
3559 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3560 is the server process, CLIENT is the new process for the connection,
3561 and MESSAGE is a string.
3563 :plist PLIST -- Install PLIST as the new process's initial plist.
3565 :tls-parameters LIST -- is a list that should be supplied if you're
3566 opening a TLS connection. The first element is the TLS type (either
3567 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3568 be a keyword list accepted by gnutls-boot (as returned by
3569 `gnutls-boot-parameters').
3571 :server QLEN -- if QLEN is non-nil, create a server process for the
3572 specified FAMILY, SERVICE, and connection type (stream or datagram).
3573 If QLEN is an integer, it is used as the max. length of the server's
3574 pending connection queue (also known as the backlog); the default
3575 queue length is 5. Default is to create a client process.
3577 The following network options can be specified for this connection:
3579 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3580 :dontroute BOOL -- Only send to directly connected hosts.
3581 :keepalive BOOL -- Send keep-alive messages on network stream.
3582 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3583 :oobinline BOOL -- Place out-of-band data in receive data stream.
3584 :priority INT -- Set protocol defined priority for sent packets.
3585 :reuseaddr BOOL -- Allow reusing a recently used local address
3586 (this is allowed by default for a server process).
3587 :bindtodevice NAME -- bind to interface NAME. Using this may require
3588 special privileges on some systems.
3589 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3590 been passed to Emacs. If Emacs wasn't
3591 passed a socket, this option is silently
3592 ignored.
3595 Consult the relevant system programmer's manual pages for more
3596 information on using these options.
3599 A server process will listen for and accept connections from clients.
3600 When a client connection is accepted, a new network process is created
3601 for the connection with the following parameters:
3603 - The client's process name is constructed by concatenating the server
3604 process's NAME and a client identification string.
3605 - If the FILTER argument is non-nil, the client process will not get a
3606 separate process buffer; otherwise, the client's process buffer is a newly
3607 created buffer named after the server process's BUFFER name or process
3608 NAME concatenated with the client identification string.
3609 - The connection type and the process filter and sentinel parameters are
3610 inherited from the server process's TYPE, FILTER and SENTINEL.
3611 - The client process's contact info is set according to the client's
3612 addressing information (typically an IP address and a port number).
3613 - The client process's plist is initialized from the server's plist.
3615 Notice that the FILTER and SENTINEL args are never used directly by
3616 the server process. Also, the BUFFER argument is not used directly by
3617 the server process, but via the optional :log function, accepted (and
3618 failed) connections may be logged in the server process's buffer.
3620 The original argument list, modified with the actual connection
3621 information, is available via the `process-contact' function.
3623 usage: (make-network-process &rest ARGS) */)
3624 (ptrdiff_t nargs, Lisp_Object *args)
3626 Lisp_Object proc;
3627 Lisp_Object contact;
3628 struct Lisp_Process *p;
3629 const char *portstring;
3630 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3631 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3632 #ifdef HAVE_LOCAL_SOCKETS
3633 struct sockaddr_un address_un;
3634 #endif
3635 EMACS_INT port = 0;
3636 Lisp_Object tem;
3637 Lisp_Object name, buffer, host, service, address;
3638 Lisp_Object filter, sentinel, use_external_socket_p;
3639 Lisp_Object addrinfos = Qnil;
3640 int socktype;
3641 int family = -1;
3642 enum { any_protocol = 0 };
3643 #ifdef HAVE_GETADDRINFO_A
3644 struct gaicb *dns_request = NULL;
3645 #endif
3646 ptrdiff_t count = SPECPDL_INDEX ();
3648 if (nargs == 0)
3649 return Qnil;
3651 /* Save arguments for process-contact and clone-process. */
3652 contact = Flist (nargs, args);
3654 #ifdef WINDOWSNT
3655 /* Ensure socket support is loaded if available. */
3656 init_winsock (TRUE);
3657 #endif
3659 /* :type TYPE (nil: stream, datagram */
3660 tem = Fplist_get (contact, QCtype);
3661 if (NILP (tem))
3662 socktype = SOCK_STREAM;
3663 #ifdef DATAGRAM_SOCKETS
3664 else if (EQ (tem, Qdatagram))
3665 socktype = SOCK_DGRAM;
3666 #endif
3667 #ifdef HAVE_SEQPACKET
3668 else if (EQ (tem, Qseqpacket))
3669 socktype = SOCK_SEQPACKET;
3670 #endif
3671 else
3672 error ("Unsupported connection type");
3674 name = Fplist_get (contact, QCname);
3675 buffer = Fplist_get (contact, QCbuffer);
3676 filter = Fplist_get (contact, QCfilter);
3677 sentinel = Fplist_get (contact, QCsentinel);
3678 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3680 CHECK_STRING (name);
3682 /* :local ADDRESS or :remote ADDRESS */
3683 tem = Fplist_get (contact, QCserver);
3684 if (NILP (tem))
3685 address = Fplist_get (contact, QCremote);
3686 else
3687 address = Fplist_get (contact, QClocal);
3688 if (!NILP (address))
3690 host = service = Qnil;
3692 if (!get_lisp_to_sockaddr_size (address, &family))
3693 error ("Malformed :address");
3695 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3696 goto open_socket;
3699 /* :family FAMILY -- nil (for Inet), local, or integer. */
3700 tem = Fplist_get (contact, QCfamily);
3701 if (NILP (tem))
3703 #ifdef AF_INET6
3704 family = AF_UNSPEC;
3705 #else
3706 family = AF_INET;
3707 #endif
3709 #ifdef HAVE_LOCAL_SOCKETS
3710 else if (EQ (tem, Qlocal))
3711 family = AF_LOCAL;
3712 #endif
3713 #ifdef AF_INET6
3714 else if (EQ (tem, Qipv6))
3715 family = AF_INET6;
3716 #endif
3717 else if (EQ (tem, Qipv4))
3718 family = AF_INET;
3719 else if (TYPE_RANGED_INTEGERP (int, tem))
3720 family = XINT (tem);
3721 else
3722 error ("Unknown address family");
3724 /* :service SERVICE -- string, integer (port number), or t (random port). */
3725 service = Fplist_get (contact, QCservice);
3727 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3728 host = Fplist_get (contact, QChost);
3729 if (NILP (host))
3731 /* The "connection" function gets it bind info from the address we're
3732 given, so use this dummy address if nothing is specified. */
3733 #ifdef HAVE_LOCAL_SOCKETS
3734 if (family != AF_LOCAL)
3735 #endif
3736 host = build_string ("127.0.0.1");
3738 else
3740 if (EQ (host, Qlocal))
3741 /* Depending on setup, "localhost" may map to different IPv4 and/or
3742 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3743 host = build_string ("127.0.0.1");
3744 CHECK_STRING (host);
3747 #ifdef HAVE_LOCAL_SOCKETS
3748 if (family == AF_LOCAL)
3750 if (!NILP (host))
3752 message (":family local ignores the :host property");
3753 contact = Fplist_put (contact, QChost, Qnil);
3754 host = Qnil;
3756 CHECK_STRING (service);
3757 if (sizeof address_un.sun_path <= SBYTES (service))
3758 error ("Service name too long");
3759 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3760 goto open_socket;
3762 #endif
3764 /* Slow down polling to every ten seconds.
3765 Some kernels have a bug which causes retrying connect to fail
3766 after a connect. Polling can interfere with gethostbyname too. */
3767 #ifdef POLL_FOR_INPUT
3768 if (socktype != SOCK_DGRAM)
3770 record_unwind_protect_void (run_all_atimers);
3771 bind_polling_period (10);
3773 #endif
3775 if (!NILP (host))
3777 /* SERVICE can either be a string or int.
3778 Convert to a C string for later use by getaddrinfo. */
3779 if (EQ (service, Qt))
3781 portstring = "0";
3782 portstringlen = 1;
3784 else if (INTEGERP (service))
3786 portstring = portbuf;
3787 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3789 else
3791 CHECK_STRING (service);
3792 portstring = SSDATA (service);
3793 portstringlen = SBYTES (service);
3797 #ifdef HAVE_GETADDRINFO_A
3798 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3800 ptrdiff_t hostlen = SBYTES (host);
3801 struct req
3803 struct gaicb gaicb;
3804 struct addrinfo hints;
3805 char str[FLEXIBLE_ARRAY_MEMBER];
3806 } *req = xmalloc (offsetof (struct req, str)
3807 + hostlen + 1 + portstringlen + 1);
3808 dns_request = &req->gaicb;
3809 dns_request->ar_name = req->str;
3810 dns_request->ar_service = req->str + hostlen + 1;
3811 dns_request->ar_request = &req->hints;
3812 dns_request->ar_result = NULL;
3813 memset (&req->hints, 0, sizeof req->hints);
3814 req->hints.ai_family = family;
3815 req->hints.ai_socktype = socktype;
3816 strcpy (req->str, SSDATA (host));
3817 strcpy (req->str + hostlen + 1, portstring);
3819 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3820 if (ret)
3821 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3823 goto open_socket;
3825 #endif /* HAVE_GETADDRINFO_A */
3827 /* If we have a host, use getaddrinfo to resolve both host and service.
3828 Otherwise, use getservbyname to lookup the service. */
3830 if (!NILP (host))
3832 struct addrinfo *res, *lres;
3833 int ret;
3835 immediate_quit = 1;
3836 QUIT;
3838 struct addrinfo hints;
3839 memset (&hints, 0, sizeof hints);
3840 hints.ai_family = family;
3841 hints.ai_socktype = socktype;
3843 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3844 if (ret)
3845 #ifdef HAVE_GAI_STRERROR
3847 synchronize_system_messages_locale ();
3848 char const *str = gai_strerror (ret);
3849 if (! NILP (Vlocale_coding_system))
3850 str = SSDATA (code_convert_string_norecord
3851 (build_string (str), Vlocale_coding_system, 0));
3852 error ("%s/%s %s", SSDATA (host), portstring, str);
3854 #else
3855 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3856 #endif
3857 immediate_quit = 0;
3859 for (lres = res; lres; lres = lres->ai_next)
3860 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
3862 addrinfos = Fnreverse (addrinfos);
3864 freeaddrinfo (res);
3866 goto open_socket;
3869 /* No hostname has been specified (e.g., a local server process). */
3871 if (EQ (service, Qt))
3872 port = 0;
3873 else if (INTEGERP (service))
3874 port = XINT (service);
3875 else
3877 CHECK_STRING (service);
3879 port = -1;
3880 if (SBYTES (service) != 0)
3882 /* Allow the service to be a string containing the port number,
3883 because that's allowed if you have getaddrbyname. */
3884 char *service_end;
3885 long int lport = strtol (SSDATA (service), &service_end, 10);
3886 if (service_end == SSDATA (service) + SBYTES (service))
3887 port = lport;
3888 else
3890 struct servent *svc_info
3891 = getservbyname (SSDATA (service),
3892 socktype == SOCK_DGRAM ? "udp" : "tcp");
3893 if (svc_info)
3894 port = ntohs (svc_info->s_port);
3899 if (! (0 <= port && port < 1 << 16))
3901 AUTO_STRING (unknown_service, "Unknown service: %s");
3902 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
3905 open_socket:
3907 if (!NILP (buffer))
3908 buffer = Fget_buffer_create (buffer);
3910 /* Unwind bind_polling_period. */
3911 unbind_to (count, Qnil);
3913 proc = make_process (name);
3914 record_unwind_protect (remove_process, proc);
3915 p = XPROCESS (proc);
3916 pset_childp (p, contact);
3917 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3918 pset_type (p, Qnetwork);
3920 pset_buffer (p, buffer);
3921 pset_sentinel (p, sentinel);
3922 pset_filter (p, filter);
3923 pset_log (p, Fplist_get (contact, QClog));
3924 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3925 p->kill_without_query = 1;
3926 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3927 pset_command (p, Qt);
3928 eassert (p->pid == 0);
3929 p->backlog = 5;
3930 eassert (! p->is_non_blocking_client);
3931 eassert (! p->is_server);
3932 p->port = port;
3933 p->socktype = socktype;
3934 #ifdef HAVE_GETADDRINFO_A
3935 eassert (! p->dns_request);
3936 #endif
3937 #ifdef HAVE_GNUTLS
3938 tem = Fplist_get (contact, QCtls_parameters);
3939 CHECK_LIST (tem);
3940 p->gnutls_boot_parameters = tem;
3941 #endif
3943 set_network_socket_coding_system (proc, host, service, name);
3945 /* :server BOOL */
3946 tem = Fplist_get (contact, QCserver);
3947 if (!NILP (tem))
3949 /* Don't support network sockets when non-blocking mode is
3950 not available, since a blocked Emacs is not useful. */
3951 p->is_server = true;
3952 if (TYPE_RANGED_INTEGERP (int, tem))
3953 p->backlog = XINT (tem);
3956 /* :nowait BOOL */
3957 if (!p->is_server && socktype != SOCK_DGRAM
3958 && !NILP (Fplist_get (contact, QCnowait)))
3959 p->is_non_blocking_client = true;
3961 bool postpone_connection = false;
3962 #ifdef HAVE_GETADDRINFO_A
3963 /* With async address resolution, the list of addresses is empty, so
3964 postpone connecting to the server. */
3965 if (!p->is_server && NILP (addrinfos))
3967 p->dns_request = dns_request;
3968 p->status = list1 (Qconnect);
3969 postpone_connection = true;
3971 #endif
3972 if (! postpone_connection)
3973 connect_network_socket (proc, addrinfos, use_external_socket_p);
3975 specpdl_ptr = specpdl + count;
3976 return proc;
3980 #ifdef HAVE_NET_IF_H
3982 #ifdef SIOCGIFCONF
3983 static Lisp_Object
3984 network_interface_list (void)
3986 struct ifconf ifconf;
3987 struct ifreq *ifreq;
3988 void *buf = NULL;
3989 ptrdiff_t buf_size = 512;
3990 int s;
3991 Lisp_Object res;
3992 ptrdiff_t count;
3994 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3995 if (s < 0)
3996 return Qnil;
3997 count = SPECPDL_INDEX ();
3998 record_unwind_protect_int (close_file_unwind, s);
4002 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4003 ifconf.ifc_buf = buf;
4004 ifconf.ifc_len = buf_size;
4005 if (ioctl (s, SIOCGIFCONF, &ifconf))
4007 emacs_close (s);
4008 xfree (buf);
4009 return Qnil;
4012 while (ifconf.ifc_len == buf_size);
4014 res = unbind_to (count, Qnil);
4015 ifreq = ifconf.ifc_req;
4016 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4018 struct ifreq *ifq = ifreq;
4019 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4020 #define SIZEOF_IFREQ(sif) \
4021 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4022 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4024 int len = SIZEOF_IFREQ (ifq);
4025 #else
4026 int len = sizeof (*ifreq);
4027 #endif
4028 char namebuf[sizeof (ifq->ifr_name) + 1];
4029 ifreq = (struct ifreq *) ((char *) ifreq + len);
4031 if (ifq->ifr_addr.sa_family != AF_INET)
4032 continue;
4034 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4035 namebuf[sizeof (ifq->ifr_name)] = 0;
4036 res = Fcons (Fcons (build_string (namebuf),
4037 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4038 sizeof (struct sockaddr))),
4039 res);
4042 xfree (buf);
4043 return res;
4045 #endif /* SIOCGIFCONF */
4047 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4049 struct ifflag_def {
4050 int flag_bit;
4051 const char *flag_sym;
4054 static const struct ifflag_def ifflag_table[] = {
4055 #ifdef IFF_UP
4056 { IFF_UP, "up" },
4057 #endif
4058 #ifdef IFF_BROADCAST
4059 { IFF_BROADCAST, "broadcast" },
4060 #endif
4061 #ifdef IFF_DEBUG
4062 { IFF_DEBUG, "debug" },
4063 #endif
4064 #ifdef IFF_LOOPBACK
4065 { IFF_LOOPBACK, "loopback" },
4066 #endif
4067 #ifdef IFF_POINTOPOINT
4068 { IFF_POINTOPOINT, "pointopoint" },
4069 #endif
4070 #ifdef IFF_RUNNING
4071 { IFF_RUNNING, "running" },
4072 #endif
4073 #ifdef IFF_NOARP
4074 { IFF_NOARP, "noarp" },
4075 #endif
4076 #ifdef IFF_PROMISC
4077 { IFF_PROMISC, "promisc" },
4078 #endif
4079 #ifdef IFF_NOTRAILERS
4080 #ifdef NS_IMPL_COCOA
4081 /* Really means smart, notrailers is obsolete. */
4082 { IFF_NOTRAILERS, "smart" },
4083 #else
4084 { IFF_NOTRAILERS, "notrailers" },
4085 #endif
4086 #endif
4087 #ifdef IFF_ALLMULTI
4088 { IFF_ALLMULTI, "allmulti" },
4089 #endif
4090 #ifdef IFF_MASTER
4091 { IFF_MASTER, "master" },
4092 #endif
4093 #ifdef IFF_SLAVE
4094 { IFF_SLAVE, "slave" },
4095 #endif
4096 #ifdef IFF_MULTICAST
4097 { IFF_MULTICAST, "multicast" },
4098 #endif
4099 #ifdef IFF_PORTSEL
4100 { IFF_PORTSEL, "portsel" },
4101 #endif
4102 #ifdef IFF_AUTOMEDIA
4103 { IFF_AUTOMEDIA, "automedia" },
4104 #endif
4105 #ifdef IFF_DYNAMIC
4106 { IFF_DYNAMIC, "dynamic" },
4107 #endif
4108 #ifdef IFF_OACTIVE
4109 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4110 #endif
4111 #ifdef IFF_SIMPLEX
4112 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4113 #endif
4114 #ifdef IFF_LINK0
4115 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4116 #endif
4117 #ifdef IFF_LINK1
4118 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4119 #endif
4120 #ifdef IFF_LINK2
4121 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4122 #endif
4123 { 0, 0 }
4126 static Lisp_Object
4127 network_interface_info (Lisp_Object ifname)
4129 struct ifreq rq;
4130 Lisp_Object res = Qnil;
4131 Lisp_Object elt;
4132 int s;
4133 bool any = 0;
4134 ptrdiff_t count;
4135 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4136 && defined HAVE_GETIFADDRS && defined LLADDR)
4137 struct ifaddrs *ifap;
4138 #endif
4140 CHECK_STRING (ifname);
4142 if (sizeof rq.ifr_name <= SBYTES (ifname))
4143 error ("interface name too long");
4144 lispstpcpy (rq.ifr_name, ifname);
4146 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4147 if (s < 0)
4148 return Qnil;
4149 count = SPECPDL_INDEX ();
4150 record_unwind_protect_int (close_file_unwind, s);
4152 elt = Qnil;
4153 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4154 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4156 int flags = rq.ifr_flags;
4157 const struct ifflag_def *fp;
4158 int fnum;
4160 /* If flags is smaller than int (i.e. short) it may have the high bit set
4161 due to IFF_MULTICAST. In that case, sign extending it into
4162 an int is wrong. */
4163 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4164 flags = (unsigned short) rq.ifr_flags;
4166 any = 1;
4167 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4169 if (flags & fp->flag_bit)
4171 elt = Fcons (intern (fp->flag_sym), elt);
4172 flags -= fp->flag_bit;
4175 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4177 if (flags & 1)
4179 elt = Fcons (make_number (fnum), elt);
4183 #endif
4184 res = Fcons (elt, res);
4186 elt = Qnil;
4187 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4188 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4190 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4191 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4192 int n;
4194 any = 1;
4195 for (n = 0; n < 6; n++)
4196 p->contents[n] = make_number (((unsigned char *)
4197 &rq.ifr_hwaddr.sa_data[0])
4198 [n]);
4199 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4201 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4202 if (getifaddrs (&ifap) != -1)
4204 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4205 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4206 struct ifaddrs *it;
4208 for (it = ifap; it != NULL; it = it->ifa_next)
4210 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4211 unsigned char linkaddr[6];
4212 int n;
4214 if (it->ifa_addr->sa_family != AF_LINK
4215 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4216 || sdl->sdl_alen != 6)
4217 continue;
4219 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4220 for (n = 0; n < 6; n++)
4221 p->contents[n] = make_number (linkaddr[n]);
4223 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4224 break;
4227 #ifdef HAVE_FREEIFADDRS
4228 freeifaddrs (ifap);
4229 #endif
4231 #endif /* HAVE_GETIFADDRS && LLADDR */
4233 res = Fcons (elt, res);
4235 elt = Qnil;
4236 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4237 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4239 any = 1;
4240 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4241 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4242 #else
4243 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4244 #endif
4246 #endif
4247 res = Fcons (elt, res);
4249 elt = Qnil;
4250 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4251 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4253 any = 1;
4254 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4256 #endif
4257 res = Fcons (elt, res);
4259 elt = Qnil;
4260 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4261 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4263 any = 1;
4264 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4266 #endif
4267 res = Fcons (elt, res);
4269 return unbind_to (count, any ? res : Qnil);
4271 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4272 #endif /* defined (HAVE_NET_IF_H) */
4274 DEFUN ("network-interface-list", Fnetwork_interface_list,
4275 Snetwork_interface_list, 0, 0, 0,
4276 doc: /* Return an alist of all network interfaces and their network address.
4277 Each element is a cons, the car of which is a string containing the
4278 interface name, and the cdr is the network address in internal
4279 format; see the description of ADDRESS in `make-network-process'.
4281 If the information is not available, return nil. */)
4282 (void)
4284 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4285 return network_interface_list ();
4286 #else
4287 return Qnil;
4288 #endif
4291 DEFUN ("network-interface-info", Fnetwork_interface_info,
4292 Snetwork_interface_info, 1, 1, 0,
4293 doc: /* Return information about network interface named IFNAME.
4294 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4295 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4296 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4297 FLAGS is the current flags of the interface.
4299 Data that is unavailable is returned as nil. */)
4300 (Lisp_Object ifname)
4302 #if ((defined HAVE_NET_IF_H \
4303 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4304 || defined SIOCGIFFLAGS)) \
4305 || defined WINDOWSNT)
4306 return network_interface_info (ifname);
4307 #else
4308 return Qnil;
4309 #endif
4312 /* Turn off input and output for process PROC. */
4314 static void
4315 deactivate_process (Lisp_Object proc)
4317 int inchannel;
4318 struct Lisp_Process *p = XPROCESS (proc);
4319 int i;
4321 #ifdef HAVE_GNUTLS
4322 /* Delete GnuTLS structures in PROC, if any. */
4323 emacs_gnutls_deinit (proc);
4324 #endif /* HAVE_GNUTLS */
4326 if (p->read_output_delay > 0)
4328 if (--process_output_delay_count < 0)
4329 process_output_delay_count = 0;
4330 p->read_output_delay = 0;
4331 p->read_output_skip = 0;
4334 /* Beware SIGCHLD hereabouts. */
4336 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4337 close_process_fd (&p->open_fd[i]);
4339 inchannel = p->infd;
4340 if (inchannel >= 0)
4342 p->infd = -1;
4343 p->outfd = -1;
4344 #ifdef DATAGRAM_SOCKETS
4345 if (DATAGRAM_CHAN_P (inchannel))
4347 xfree (datagram_address[inchannel].sa);
4348 datagram_address[inchannel].sa = 0;
4349 datagram_address[inchannel].len = 0;
4351 #endif
4352 chan_process[inchannel] = Qnil;
4353 FD_CLR (inchannel, &input_wait_mask);
4354 FD_CLR (inchannel, &non_keyboard_wait_mask);
4355 if (FD_ISSET (inchannel, &connect_wait_mask))
4357 FD_CLR (inchannel, &connect_wait_mask);
4358 FD_CLR (inchannel, &write_mask);
4359 if (--num_pending_connects < 0)
4360 emacs_abort ();
4362 if (inchannel == max_process_desc)
4364 /* We just closed the highest-numbered process input descriptor,
4365 so recompute the highest-numbered one now. */
4366 int i = inchannel;
4368 i--;
4369 while (0 <= i && NILP (chan_process[i]));
4371 max_process_desc = i;
4377 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4378 0, 4, 0,
4379 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4380 It is given to their filter functions.
4381 Optional argument PROCESS means do not return until output has been
4382 received from PROCESS.
4384 Optional second argument SECONDS and third argument MILLISEC
4385 specify a timeout; return after that much time even if there is
4386 no subprocess output. If SECONDS is a floating point number,
4387 it specifies a fractional number of seconds to wait.
4388 The MILLISEC argument is obsolete and should be avoided.
4390 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4391 from PROCESS only, suspending reading output from other processes.
4392 If JUST-THIS-ONE is an integer, don't run any timers either.
4393 Return non-nil if we received any output from PROCESS (or, if PROCESS
4394 is nil, from any process) before the timeout expired. */)
4395 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4397 intmax_t secs;
4398 int nsecs;
4400 if (! NILP (process))
4401 CHECK_PROCESS (process);
4402 else
4403 just_this_one = Qnil;
4405 if (!NILP (millisec))
4406 { /* Obsolete calling convention using integers rather than floats. */
4407 CHECK_NUMBER (millisec);
4408 if (NILP (seconds))
4409 seconds = make_float (XINT (millisec) / 1000.0);
4410 else
4412 CHECK_NUMBER (seconds);
4413 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4417 secs = 0;
4418 nsecs = -1;
4420 if (!NILP (seconds))
4422 if (INTEGERP (seconds))
4424 if (XINT (seconds) > 0)
4426 secs = XINT (seconds);
4427 nsecs = 0;
4430 else if (FLOATP (seconds))
4432 if (XFLOAT_DATA (seconds) > 0)
4434 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4435 secs = min (t.tv_sec, WAIT_READING_MAX);
4436 nsecs = t.tv_nsec;
4439 else
4440 wrong_type_argument (Qnumberp, seconds);
4442 else if (! NILP (process))
4443 nsecs = 0;
4445 return
4446 ((wait_reading_process_output (secs, nsecs, 0, 0,
4447 Qnil,
4448 !NILP (process) ? XPROCESS (process) : NULL,
4449 (NILP (just_this_one) ? 0
4450 : !INTEGERP (just_this_one) ? 1 : -1))
4451 <= 0)
4452 ? Qnil : Qt);
4455 /* Accept a connection for server process SERVER on CHANNEL. */
4457 static EMACS_INT connect_counter = 0;
4459 static void
4460 server_accept_connection (Lisp_Object server, int channel)
4462 Lisp_Object proc, caller, name, buffer;
4463 Lisp_Object contact, host, service;
4464 struct Lisp_Process *ps = XPROCESS (server);
4465 struct Lisp_Process *p;
4466 int s;
4467 union u_sockaddr {
4468 struct sockaddr sa;
4469 struct sockaddr_in in;
4470 #ifdef AF_INET6
4471 struct sockaddr_in6 in6;
4472 #endif
4473 #ifdef HAVE_LOCAL_SOCKETS
4474 struct sockaddr_un un;
4475 #endif
4476 } saddr;
4477 socklen_t len = sizeof saddr;
4478 ptrdiff_t count;
4480 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4482 if (s < 0)
4484 int code = errno;
4485 if (!would_block (code) && !NILP (ps->log))
4486 call3 (ps->log, server, Qnil,
4487 concat3 (build_string ("accept failed with code"),
4488 Fnumber_to_string (make_number (code)),
4489 build_string ("\n")));
4490 return;
4493 count = SPECPDL_INDEX ();
4494 record_unwind_protect_int (close_file_unwind, s);
4496 connect_counter++;
4498 /* Setup a new process to handle the connection. */
4500 /* Generate a unique identification of the caller, and build contact
4501 information for this process. */
4502 host = Qt;
4503 service = Qnil;
4504 switch (saddr.sa.sa_family)
4506 case AF_INET:
4508 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4510 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4511 host = CALLN (Fformat, ipv4_format,
4512 make_number (ip[0]), make_number (ip[1]),
4513 make_number (ip[2]), make_number (ip[3]));
4514 service = make_number (ntohs (saddr.in.sin_port));
4515 AUTO_STRING (caller_format, " <%s:%d>");
4516 caller = CALLN (Fformat, caller_format, host, service);
4518 break;
4520 #ifdef AF_INET6
4521 case AF_INET6:
4523 Lisp_Object args[9];
4524 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4525 int i;
4527 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4528 args[0] = ipv6_format;
4529 for (i = 0; i < 8; i++)
4530 args[i + 1] = make_number (ntohs (ip6[i]));
4531 host = CALLMANY (Fformat, args);
4532 service = make_number (ntohs (saddr.in.sin_port));
4533 AUTO_STRING (caller_format, " <[%s]:%d>");
4534 caller = CALLN (Fformat, caller_format, host, service);
4536 break;
4537 #endif
4539 #ifdef HAVE_LOCAL_SOCKETS
4540 case AF_LOCAL:
4541 #endif
4542 default:
4543 caller = Fnumber_to_string (make_number (connect_counter));
4544 AUTO_STRING (space_less_than, " <");
4545 AUTO_STRING (greater_than, ">");
4546 caller = concat3 (space_less_than, caller, greater_than);
4547 break;
4550 /* Create a new buffer name for this process if it doesn't have a
4551 filter. The new buffer name is based on the buffer name or
4552 process name of the server process concatenated with the caller
4553 identification. */
4555 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4556 || EQ (ps->filter, Qt)))
4557 buffer = Qnil;
4558 else
4560 buffer = ps->buffer;
4561 if (!NILP (buffer))
4562 buffer = Fbuffer_name (buffer);
4563 else
4564 buffer = ps->name;
4565 if (!NILP (buffer))
4567 buffer = concat2 (buffer, caller);
4568 buffer = Fget_buffer_create (buffer);
4572 /* Generate a unique name for the new server process. Combine the
4573 server process name with the caller identification. */
4575 name = concat2 (ps->name, caller);
4576 proc = make_process (name);
4578 chan_process[s] = proc;
4580 fcntl (s, F_SETFL, O_NONBLOCK);
4582 p = XPROCESS (proc);
4584 /* Build new contact information for this setup. */
4585 contact = Fcopy_sequence (ps->childp);
4586 contact = Fplist_put (contact, QCserver, Qnil);
4587 contact = Fplist_put (contact, QChost, host);
4588 if (!NILP (service))
4589 contact = Fplist_put (contact, QCservice, service);
4590 contact = Fplist_put (contact, QCremote,
4591 conv_sockaddr_to_lisp (&saddr.sa, len));
4592 #ifdef HAVE_GETSOCKNAME
4593 len = sizeof saddr;
4594 if (getsockname (s, &saddr.sa, &len) == 0)
4595 contact = Fplist_put (contact, QClocal,
4596 conv_sockaddr_to_lisp (&saddr.sa, len));
4597 #endif
4599 pset_childp (p, contact);
4600 pset_plist (p, Fcopy_sequence (ps->plist));
4601 pset_type (p, Qnetwork);
4603 pset_buffer (p, buffer);
4604 pset_sentinel (p, ps->sentinel);
4605 pset_filter (p, ps->filter);
4606 eassert (NILP (p->command));
4607 eassert (p->pid == 0);
4609 /* Discard the unwind protect for closing S. */
4610 specpdl_ptr = specpdl + count;
4612 p->open_fd[SUBPROCESS_STDIN] = s;
4613 p->infd = s;
4614 p->outfd = s;
4615 pset_status (p, Qrun);
4617 /* Client processes for accepted connections are not stopped initially. */
4618 if (!EQ (p->filter, Qt))
4620 FD_SET (s, &input_wait_mask);
4621 FD_SET (s, &non_keyboard_wait_mask);
4624 if (s > max_process_desc)
4625 max_process_desc = s;
4627 /* Setup coding system for new process based on server process.
4628 This seems to be the proper thing to do, as the coding system
4629 of the new process should reflect the settings at the time the
4630 server socket was opened; not the current settings. */
4632 pset_decode_coding_system (p, ps->decode_coding_system);
4633 pset_encode_coding_system (p, ps->encode_coding_system);
4634 setup_process_coding_systems (proc);
4636 pset_decoding_buf (p, empty_unibyte_string);
4637 eassert (p->decoding_carryover == 0);
4638 pset_encoding_buf (p, empty_unibyte_string);
4640 p->inherit_coding_system_flag
4641 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4643 AUTO_STRING (dash, "-");
4644 AUTO_STRING (nl, "\n");
4645 Lisp_Object host_string = STRINGP (host) ? host : dash;
4647 if (!NILP (ps->log))
4649 AUTO_STRING (accept_from, "accept from ");
4650 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4653 AUTO_STRING (open_from, "open from ");
4654 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4657 #ifdef HAVE_GETADDRINFO_A
4658 static Lisp_Object
4659 check_for_dns (Lisp_Object proc)
4661 struct Lisp_Process *p = XPROCESS (proc);
4662 Lisp_Object addrinfos = Qnil;
4664 /* Sanity check. */
4665 if (! p->dns_request)
4666 return Qnil;
4668 int ret = gai_error (p->dns_request);
4669 if (ret == EAI_INPROGRESS)
4670 return Qt;
4672 /* We got a response. */
4673 if (ret == 0)
4675 struct addrinfo *res;
4677 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4678 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4680 addrinfos = Fnreverse (addrinfos);
4682 /* The DNS lookup failed. */
4683 else if (connecting_status (p->status))
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 (! connecting_status (p->status))
4697 return Qnil;
4699 return addrinfos;
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 && connecting_status (XPROCESS (process)->status))
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 (connecting_status (XPROCESS (process)->status))
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 addrinfos = check_for_dns (aproc);
4883 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
4884 connect_network_socket (aproc, addrinfos, Qnil);
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 (num_pending_connects > 0 ? &Ctemp : NULL),
5003 NULL, &timeout, NULL)
5004 <= 0))
5006 /* It's okay for us to do this and then continue with
5007 the loop, since timeout has already been zeroed out. */
5008 clear_waiting_for_input ();
5009 got_some_output = status_notify (NULL, wait_proc);
5010 if (do_display) redisplay_preserve_echo_area (13);
5014 /* Don't wait for output from a non-running process. Just
5015 read whatever data has already been received. */
5016 if (wait_proc && wait_proc->raw_status_new)
5017 update_status (wait_proc);
5018 if (wait_proc
5019 && ! EQ (wait_proc->status, Qrun)
5020 && ! connecting_status (wait_proc->status))
5022 bool read_some_bytes = false;
5024 clear_waiting_for_input ();
5026 /* If data can be read from the process, do so until exhausted. */
5027 if (wait_proc->infd >= 0)
5029 XSETPROCESS (proc, wait_proc);
5031 while (true)
5033 int nread = read_process_output (proc, wait_proc->infd);
5034 if (nread < 0)
5036 if (errno == EIO || would_block (errno))
5037 break;
5039 else
5041 if (got_some_output < nread)
5042 got_some_output = nread;
5043 if (nread == 0)
5044 break;
5045 read_some_bytes = true;
5050 if (read_some_bytes && do_display)
5051 redisplay_preserve_echo_area (10);
5053 break;
5056 /* Wait till there is something to do. */
5058 if (wait_proc && just_wait_proc)
5060 if (wait_proc->infd < 0) /* Terminated. */
5061 break;
5062 FD_SET (wait_proc->infd, &Available);
5063 check_delay = 0;
5064 check_write = 0;
5066 else if (!NILP (wait_for_cell))
5068 Available = non_process_wait_mask;
5069 check_delay = 0;
5070 check_write = 0;
5072 else
5074 if (! read_kbd)
5075 Available = non_keyboard_wait_mask;
5076 else
5077 Available = input_wait_mask;
5078 Writeok = write_mask;
5079 check_delay = wait_proc ? 0 : process_output_delay_count;
5080 check_write = true;
5083 /* If frame size has changed or the window is newly mapped,
5084 redisplay now, before we start to wait. There is a race
5085 condition here; if a SIGIO arrives between now and the select
5086 and indicates that a frame is trashed, the select may block
5087 displaying a trashed screen. */
5088 if (frame_garbaged && do_display)
5090 clear_waiting_for_input ();
5091 redisplay_preserve_echo_area (11);
5092 if (read_kbd < 0)
5093 set_waiting_for_input (&timeout);
5096 /* Skip the `select' call if input is available and we're
5097 waiting for keyboard input or a cell change (which can be
5098 triggered by processing X events). In the latter case, set
5099 nfds to 1 to avoid breaking the loop. */
5100 no_avail = 0;
5101 if ((read_kbd || !NILP (wait_for_cell))
5102 && detect_input_pending ())
5104 nfds = read_kbd ? 0 : 1;
5105 no_avail = 1;
5106 FD_ZERO (&Available);
5108 else
5110 /* Set the timeout for adaptive read buffering if any
5111 process has non-zero read_output_skip and non-zero
5112 read_output_delay, and we are not reading output for a
5113 specific process. It is not executed if
5114 Vprocess_adaptive_read_buffering is nil. */
5115 if (process_output_skip && check_delay > 0)
5117 int adaptive_nsecs = timeout.tv_nsec;
5118 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5119 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5120 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
5122 proc = chan_process[channel];
5123 if (NILP (proc))
5124 continue;
5125 /* Find minimum non-zero read_output_delay among the
5126 processes with non-zero read_output_skip. */
5127 if (XPROCESS (proc)->read_output_delay > 0)
5129 check_delay--;
5130 if (!XPROCESS (proc)->read_output_skip)
5131 continue;
5132 FD_CLR (channel, &Available);
5133 process_skipped = true;
5134 XPROCESS (proc)->read_output_skip = 0;
5135 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5136 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5139 timeout = make_timespec (0, adaptive_nsecs);
5140 process_output_skip = 0;
5143 /* If we've got some output and haven't limited our timeout
5144 with adaptive read buffering, limit it. */
5145 if (got_some_output > 0 && !process_skipped
5146 && (timeout.tv_sec
5147 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5148 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5151 if (NILP (wait_for_cell) && just_wait_proc >= 0
5152 && timespec_valid_p (timer_delay)
5153 && timespec_cmp (timer_delay, timeout) < 0)
5155 if (!timespec_valid_p (now))
5156 now = current_timespec ();
5157 struct timespec timeout_abs = timespec_add (now, timeout);
5158 if (!timespec_valid_p (got_output_end_time)
5159 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5160 got_output_end_time = timeout_abs;
5161 timeout = timer_delay;
5163 else
5164 got_output_end_time = invalid_timespec ();
5166 /* NOW can become inaccurate if time can pass during pselect. */
5167 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5168 now = invalid_timespec ();
5170 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5171 if (retry_for_async
5172 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5174 timeout.tv_sec = 0;
5175 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5177 #endif
5179 #if defined (HAVE_NS)
5180 nfds = ns_select
5181 #elif defined (HAVE_GLIB)
5182 nfds = xg_select
5183 #else
5184 nfds = pselect
5185 #endif
5186 (max (max_process_desc, max_input_desc) + 1,
5187 &Available,
5188 (check_write ? &Writeok : 0),
5189 NULL, &timeout, NULL);
5191 #ifdef HAVE_GNUTLS
5192 /* GnuTLS buffers data internally. In lowat mode it leaves
5193 some data in the TCP buffers so that select works, but
5194 with custom pull/push functions we need to check if some
5195 data is available in the buffers manually. */
5196 if (nfds == 0)
5198 fd_set tls_available;
5199 int set = 0;
5201 FD_ZERO (&tls_available);
5202 if (! wait_proc)
5204 /* We're not waiting on a specific process, so loop
5205 through all the channels and check for data.
5206 This is a workaround needed for some versions of
5207 the gnutls library -- 2.12.14 has been confirmed
5208 to need it. See
5209 http://comments.gmane.org/gmane.emacs.devel/145074 */
5210 for (channel = 0; channel < FD_SETSIZE; ++channel)
5211 if (! NILP (chan_process[channel]))
5213 struct Lisp_Process *p =
5214 XPROCESS (chan_process[channel]);
5215 if (p && p->gnutls_p && p->gnutls_state
5216 && ((emacs_gnutls_record_check_pending
5217 (p->gnutls_state))
5218 > 0))
5220 nfds++;
5221 eassert (p->infd == channel);
5222 FD_SET (p->infd, &tls_available);
5223 set++;
5227 else
5229 /* Check this specific channel. */
5230 if (wait_proc->gnutls_p /* Check for valid process. */
5231 && wait_proc->gnutls_state
5232 /* Do we have pending data? */
5233 && ((emacs_gnutls_record_check_pending
5234 (wait_proc->gnutls_state))
5235 > 0))
5237 nfds = 1;
5238 eassert (0 <= wait_proc->infd);
5239 /* Set to Available. */
5240 FD_SET (wait_proc->infd, &tls_available);
5241 set++;
5244 if (set)
5245 Available = tls_available;
5247 #endif
5250 xerrno = errno;
5252 /* Make C-g and alarm signals set flags again. */
5253 clear_waiting_for_input ();
5255 /* If we woke up due to SIGWINCH, actually change size now. */
5256 do_pending_window_change (0);
5258 if (nfds == 0)
5260 /* Exit the main loop if we've passed the requested timeout,
5261 or aren't skipping processes and got some output and
5262 haven't lowered our timeout due to timers or SIGIO and
5263 have waited a long amount of time due to repeated
5264 timers. */
5265 struct timespec huge_timespec
5266 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5267 struct timespec cmp_time = huge_timespec;
5268 if (wait < TIMEOUT)
5269 break;
5270 if (wait == TIMEOUT)
5271 cmp_time = end_time;
5272 if (!process_skipped && got_some_output > 0
5273 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5275 if (!timespec_valid_p (got_output_end_time))
5276 break;
5277 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5278 cmp_time = got_output_end_time;
5280 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5282 now = current_timespec ();
5283 if (timespec_cmp (cmp_time, now) <= 0)
5284 break;
5288 if (nfds < 0)
5290 if (xerrno == EINTR)
5291 no_avail = 1;
5292 else if (xerrno == EBADF)
5293 emacs_abort ();
5294 else
5295 report_file_errno ("Failed select", Qnil, xerrno);
5298 /* Check for keyboard input. */
5299 /* If there is any, return immediately
5300 to give it higher priority than subprocesses. */
5302 if (read_kbd != 0)
5304 unsigned old_timers_run = timers_run;
5305 struct buffer *old_buffer = current_buffer;
5306 Lisp_Object old_window = selected_window;
5307 bool leave = false;
5309 if (detect_input_pending_run_timers (do_display))
5311 swallow_events (do_display);
5312 if (detect_input_pending_run_timers (do_display))
5313 leave = true;
5316 /* If a timer has run, this might have changed buffers
5317 an alike. Make read_key_sequence aware of that. */
5318 if (timers_run != old_timers_run
5319 && waiting_for_user_input_p == -1
5320 && (old_buffer != current_buffer
5321 || !EQ (old_window, selected_window)))
5322 record_asynch_buffer_change ();
5324 if (leave)
5325 break;
5328 /* If there is unread keyboard input, also return. */
5329 if (read_kbd != 0
5330 && requeued_events_pending_p ())
5331 break;
5333 /* If we are not checking for keyboard input now,
5334 do process events (but don't run any timers).
5335 This is so that X events will be processed.
5336 Otherwise they may have to wait until polling takes place.
5337 That would causes delays in pasting selections, for example.
5339 (We used to do this only if wait_for_cell.) */
5340 if (read_kbd == 0 && detect_input_pending ())
5342 swallow_events (do_display);
5343 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5344 if (detect_input_pending ())
5345 break;
5346 #endif
5349 /* Exit now if the cell we're waiting for became non-nil. */
5350 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5351 break;
5353 #ifdef USABLE_SIGIO
5354 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5355 go read it. This can happen with X on BSD after logging out.
5356 In that case, there really is no input and no SIGIO,
5357 but select says there is input. */
5359 if (read_kbd && interrupt_input
5360 && keyboard_bit_set (&Available) && ! noninteractive)
5361 handle_input_available_signal (SIGIO);
5362 #endif
5364 /* If checking input just got us a size-change event from X,
5365 obey it now if we should. */
5366 if (read_kbd || ! NILP (wait_for_cell))
5367 do_pending_window_change (0);
5369 /* Check for data from a process. */
5370 if (no_avail || nfds == 0)
5371 continue;
5373 for (channel = 0; channel <= max_input_desc; ++channel)
5375 struct fd_callback_data *d = &fd_callback_info[channel];
5376 if (d->func
5377 && ((d->condition & FOR_READ
5378 && FD_ISSET (channel, &Available))
5379 || (d->condition & FOR_WRITE
5380 && FD_ISSET (channel, &write_mask))))
5381 d->func (channel, d->data);
5384 for (channel = 0; channel <= max_process_desc; channel++)
5386 if (FD_ISSET (channel, &Available)
5387 && FD_ISSET (channel, &non_keyboard_wait_mask)
5388 && !FD_ISSET (channel, &non_process_wait_mask))
5390 int nread;
5392 /* If waiting for this channel, arrange to return as
5393 soon as no more input to be processed. No more
5394 waiting. */
5395 proc = chan_process[channel];
5396 if (NILP (proc))
5397 continue;
5399 /* If this is a server stream socket, accept connection. */
5400 if (EQ (XPROCESS (proc)->status, Qlisten))
5402 server_accept_connection (proc, channel);
5403 continue;
5406 /* Read data from the process, starting with our
5407 buffered-ahead character if we have one. */
5409 nread = read_process_output (proc, channel);
5410 if ((!wait_proc || wait_proc == XPROCESS (proc))
5411 && got_some_output < nread)
5412 got_some_output = nread;
5413 if (nread > 0)
5415 /* Vacuum up any leftovers without waiting. */
5416 if (wait_proc == XPROCESS (proc))
5417 wait = MINIMUM;
5418 /* Since read_process_output can run a filter,
5419 which can call accept-process-output,
5420 don't try to read from any other processes
5421 before doing the select again. */
5422 FD_ZERO (&Available);
5424 if (do_display)
5425 redisplay_preserve_echo_area (12);
5427 else if (nread == -1 && would_block (errno))
5429 #ifdef WINDOWSNT
5430 /* FIXME: Is this special case still needed? */
5431 /* Note that we cannot distinguish between no input
5432 available now and a closed pipe.
5433 With luck, a closed pipe will be accompanied by
5434 subprocess termination and SIGCHLD. */
5435 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5436 && !PIPECONN_P (proc))
5438 #endif
5439 #ifdef HAVE_PTYS
5440 /* On some OSs with ptys, when the process on one end of
5441 a pty exits, the other end gets an error reading with
5442 errno = EIO instead of getting an EOF (0 bytes read).
5443 Therefore, if we get an error reading and errno =
5444 EIO, just continue, because the child process has
5445 exited and should clean itself up soon (e.g. when we
5446 get a SIGCHLD). */
5447 else if (nread == -1 && errno == EIO)
5449 struct Lisp_Process *p = XPROCESS (proc);
5451 /* Clear the descriptor now, so we only raise the
5452 signal once. */
5453 FD_CLR (channel, &input_wait_mask);
5454 FD_CLR (channel, &non_keyboard_wait_mask);
5456 if (p->pid == -2)
5458 /* If the EIO occurs on a pty, the SIGCHLD handler's
5459 waitpid call will not find the process object to
5460 delete. Do it here. */
5461 p->tick = ++process_tick;
5462 pset_status (p, Qfailed);
5465 #endif /* HAVE_PTYS */
5466 /* If we can detect process termination, don't consider the
5467 process gone just because its pipe is closed. */
5468 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5469 && !PIPECONN_P (proc))
5471 else if (nread == 0 && PIPECONN_P (proc))
5473 /* Preserve status of processes already terminated. */
5474 XPROCESS (proc)->tick = ++process_tick;
5475 deactivate_process (proc);
5476 if (EQ (XPROCESS (proc)->status, Qrun))
5477 pset_status (XPROCESS (proc),
5478 list2 (Qexit, make_number (0)));
5480 else
5482 /* Preserve status of processes already terminated. */
5483 XPROCESS (proc)->tick = ++process_tick;
5484 deactivate_process (proc);
5485 if (XPROCESS (proc)->raw_status_new)
5486 update_status (XPROCESS (proc));
5487 if (EQ (XPROCESS (proc)->status, Qrun))
5488 pset_status (XPROCESS (proc),
5489 list2 (Qexit, make_number (256)));
5492 if (FD_ISSET (channel, &Writeok)
5493 && FD_ISSET (channel, &connect_wait_mask))
5495 struct Lisp_Process *p;
5497 FD_CLR (channel, &connect_wait_mask);
5498 FD_CLR (channel, &write_mask);
5499 if (--num_pending_connects < 0)
5500 emacs_abort ();
5502 proc = chan_process[channel];
5503 if (NILP (proc))
5504 continue;
5506 p = XPROCESS (proc);
5508 #ifndef WINDOWSNT
5510 socklen_t xlen = sizeof (xerrno);
5511 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5512 xerrno = errno;
5514 #else
5515 /* On MS-Windows, getsockopt clears the error for the
5516 entire process, which may not be the right thing; see
5517 w32.c. Use getpeername instead. */
5519 struct sockaddr pname;
5520 socklen_t pnamelen = sizeof (pname);
5522 /* If connection failed, getpeername will fail. */
5523 xerrno = 0;
5524 if (getpeername (channel, &pname, &pnamelen) < 0)
5526 /* Obtain connect failure code through error slippage. */
5527 char dummy;
5528 xerrno = errno;
5529 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5530 xerrno = errno;
5533 #endif
5534 if (xerrno)
5536 Lisp_Object addrinfos
5537 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5538 if (!NILP (addrinfos))
5539 XSETCDR (p->status, XCDR (addrinfos));
5540 else
5542 p->tick = ++process_tick;
5543 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5545 deactivate_process (proc);
5546 if (!NILP (addrinfos))
5547 connect_network_socket (proc, addrinfos, Qnil);
5549 else
5551 #ifdef HAVE_GNUTLS
5552 /* If we have an incompletely set up TLS connection,
5553 then defer the sentinel signaling until
5554 later. */
5555 if (NILP (p->gnutls_boot_parameters)
5556 && !p->gnutls_p)
5557 #endif
5559 pset_status (p, Qrun);
5560 /* Execute the sentinel here. If we had relied on
5561 status_notify to do it later, it will read input
5562 from the process before calling the sentinel. */
5563 exec_sentinel (proc, build_string ("open\n"));
5566 if (0 <= p->infd && !EQ (p->filter, Qt)
5567 && !EQ (p->command, Qt))
5569 FD_SET (p->infd, &input_wait_mask);
5570 FD_SET (p->infd, &non_keyboard_wait_mask);
5574 } /* End for each file descriptor. */
5575 } /* End while exit conditions not met. */
5577 unbind_to (count, Qnil);
5579 /* If calling from keyboard input, do not quit
5580 since we want to return C-g as an input character.
5581 Otherwise, do pending quit if requested. */
5582 if (read_kbd >= 0)
5584 /* Prevent input_pending from remaining set if we quit. */
5585 clear_input_pending ();
5586 QUIT;
5589 return got_some_output;
5592 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5594 static Lisp_Object
5595 read_process_output_call (Lisp_Object fun_and_args)
5597 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5600 static Lisp_Object
5601 read_process_output_error_handler (Lisp_Object error_val)
5603 cmd_error_internal (error_val, "error in process filter: ");
5604 Vinhibit_quit = Qt;
5605 update_echo_area ();
5606 Fsleep_for (make_number (2), Qnil);
5607 return Qt;
5610 static void
5611 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5612 ssize_t nbytes,
5613 struct coding_system *coding);
5615 /* Read pending output from the process channel,
5616 starting with our buffered-ahead character if we have one.
5617 Yield number of decoded characters read.
5619 This function reads at most 4096 characters.
5620 If you want to read all available subprocess output,
5621 you must call it repeatedly until it returns zero.
5623 The characters read are decoded according to PROC's coding-system
5624 for decoding. */
5626 static int
5627 read_process_output (Lisp_Object proc, int channel)
5629 ssize_t nbytes;
5630 struct Lisp_Process *p = XPROCESS (proc);
5631 struct coding_system *coding = proc_decode_coding_system[channel];
5632 int carryover = p->decoding_carryover;
5633 enum { readmax = 4096 };
5634 ptrdiff_t count = SPECPDL_INDEX ();
5635 Lisp_Object odeactivate;
5636 char chars[sizeof coding->carryover + readmax];
5638 if (carryover)
5639 /* See the comment above. */
5640 memcpy (chars, SDATA (p->decoding_buf), carryover);
5642 #ifdef DATAGRAM_SOCKETS
5643 /* We have a working select, so proc_buffered_char is always -1. */
5644 if (DATAGRAM_CHAN_P (channel))
5646 socklen_t len = datagram_address[channel].len;
5647 nbytes = recvfrom (channel, chars + carryover, readmax,
5648 0, datagram_address[channel].sa, &len);
5650 else
5651 #endif
5653 bool buffered = proc_buffered_char[channel] >= 0;
5654 if (buffered)
5656 chars[carryover] = proc_buffered_char[channel];
5657 proc_buffered_char[channel] = -1;
5659 #ifdef HAVE_GNUTLS
5660 if (p->gnutls_p && p->gnutls_state)
5661 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5662 readmax - buffered);
5663 else
5664 #endif
5665 nbytes = emacs_read (channel, chars + carryover + buffered,
5666 readmax - buffered);
5667 if (nbytes > 0 && p->adaptive_read_buffering)
5669 int delay = p->read_output_delay;
5670 if (nbytes < 256)
5672 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5674 if (delay == 0)
5675 process_output_delay_count++;
5676 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5679 else if (delay > 0 && nbytes == readmax - buffered)
5681 delay -= READ_OUTPUT_DELAY_INCREMENT;
5682 if (delay == 0)
5683 process_output_delay_count--;
5685 p->read_output_delay = delay;
5686 if (delay)
5688 p->read_output_skip = 1;
5689 process_output_skip = 1;
5692 nbytes += buffered;
5693 nbytes += buffered && nbytes <= 0;
5696 p->decoding_carryover = 0;
5698 /* At this point, NBYTES holds number of bytes just received
5699 (including the one in proc_buffered_char[channel]). */
5700 if (nbytes <= 0)
5702 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5703 return nbytes;
5704 coding->mode |= CODING_MODE_LAST_BLOCK;
5707 /* Now set NBYTES how many bytes we must decode. */
5708 nbytes += carryover;
5710 odeactivate = Vdeactivate_mark;
5711 /* There's no good reason to let process filters change the current
5712 buffer, and many callers of accept-process-output, sit-for, and
5713 friends don't expect current-buffer to be changed from under them. */
5714 record_unwind_current_buffer ();
5716 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5718 /* Handling the process output should not deactivate the mark. */
5719 Vdeactivate_mark = odeactivate;
5721 unbind_to (count, Qnil);
5722 return nbytes;
5725 static void
5726 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5727 ssize_t nbytes,
5728 struct coding_system *coding)
5730 Lisp_Object outstream = p->filter;
5731 Lisp_Object text;
5732 bool outer_running_asynch_code = running_asynch_code;
5733 int waiting = waiting_for_user_input_p;
5735 #if 0
5736 Lisp_Object obuffer, okeymap;
5737 XSETBUFFER (obuffer, current_buffer);
5738 okeymap = BVAR (current_buffer, keymap);
5739 #endif
5741 /* We inhibit quit here instead of just catching it so that
5742 hitting ^G when a filter happens to be running won't screw
5743 it up. */
5744 specbind (Qinhibit_quit, Qt);
5745 specbind (Qlast_nonmenu_event, Qt);
5747 /* In case we get recursively called,
5748 and we already saved the match data nonrecursively,
5749 save the same match data in safely recursive fashion. */
5750 if (outer_running_asynch_code)
5752 Lisp_Object tem;
5753 /* Don't clobber the CURRENT match data, either! */
5754 tem = Fmatch_data (Qnil, Qnil, Qnil);
5755 restore_search_regs ();
5756 record_unwind_save_match_data ();
5757 Fset_match_data (tem, Qt);
5760 /* For speed, if a search happens within this code,
5761 save the match data in a special nonrecursive fashion. */
5762 running_asynch_code = 1;
5764 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5765 text = coding->dst_object;
5766 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5767 /* A new coding system might be found. */
5768 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5770 pset_decode_coding_system (p, Vlast_coding_system_used);
5772 /* Don't call setup_coding_system for
5773 proc_decode_coding_system[channel] here. It is done in
5774 detect_coding called via decode_coding above. */
5776 /* If a coding system for encoding is not yet decided, we set
5777 it as the same as coding-system for decoding.
5779 But, before doing that we must check if
5780 proc_encode_coding_system[p->outfd] surely points to a
5781 valid memory because p->outfd will be changed once EOF is
5782 sent to the process. */
5783 if (NILP (p->encode_coding_system) && p->outfd >= 0
5784 && proc_encode_coding_system[p->outfd])
5786 pset_encode_coding_system
5787 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5788 setup_coding_system (p->encode_coding_system,
5789 proc_encode_coding_system[p->outfd]);
5793 if (coding->carryover_bytes > 0)
5795 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5796 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5797 memcpy (SDATA (p->decoding_buf), coding->carryover,
5798 coding->carryover_bytes);
5799 p->decoding_carryover = coding->carryover_bytes;
5801 if (SBYTES (text) > 0)
5802 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5803 sometimes it's simply wrong to wrap (e.g. when called from
5804 accept-process-output). */
5805 internal_condition_case_1 (read_process_output_call,
5806 list3 (outstream, make_lisp_proc (p), text),
5807 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5808 read_process_output_error_handler);
5810 /* If we saved the match data nonrecursively, restore it now. */
5811 restore_search_regs ();
5812 running_asynch_code = outer_running_asynch_code;
5814 /* Restore waiting_for_user_input_p as it was
5815 when we were called, in case the filter clobbered it. */
5816 waiting_for_user_input_p = waiting;
5818 #if 0 /* Call record_asynch_buffer_change unconditionally,
5819 because we might have changed minor modes or other things
5820 that affect key bindings. */
5821 if (! EQ (Fcurrent_buffer (), obuffer)
5822 || ! EQ (current_buffer->keymap, okeymap))
5823 #endif
5824 /* But do it only if the caller is actually going to read events.
5825 Otherwise there's no need to make him wake up, and it could
5826 cause trouble (for example it would make sit_for return). */
5827 if (waiting_for_user_input_p == -1)
5828 record_asynch_buffer_change ();
5831 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5832 Sinternal_default_process_filter, 2, 2, 0,
5833 doc: /* Function used as default process filter.
5834 This inserts the process's output into its buffer, if there is one.
5835 Otherwise it discards the output. */)
5836 (Lisp_Object proc, Lisp_Object text)
5838 struct Lisp_Process *p;
5839 ptrdiff_t opoint;
5841 CHECK_PROCESS (proc);
5842 p = XPROCESS (proc);
5843 CHECK_STRING (text);
5845 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5847 Lisp_Object old_read_only;
5848 ptrdiff_t old_begv, old_zv;
5849 ptrdiff_t old_begv_byte, old_zv_byte;
5850 ptrdiff_t before, before_byte;
5851 ptrdiff_t opoint_byte;
5852 struct buffer *b;
5854 Fset_buffer (p->buffer);
5855 opoint = PT;
5856 opoint_byte = PT_BYTE;
5857 old_read_only = BVAR (current_buffer, read_only);
5858 old_begv = BEGV;
5859 old_zv = ZV;
5860 old_begv_byte = BEGV_BYTE;
5861 old_zv_byte = ZV_BYTE;
5863 bset_read_only (current_buffer, Qnil);
5865 /* Insert new output into buffer at the current end-of-output
5866 marker, thus preserving logical ordering of input and output. */
5867 if (XMARKER (p->mark)->buffer)
5868 set_point_from_marker (p->mark);
5869 else
5870 SET_PT_BOTH (ZV, ZV_BYTE);
5871 before = PT;
5872 before_byte = PT_BYTE;
5874 /* If the output marker is outside of the visible region, save
5875 the restriction and widen. */
5876 if (! (BEGV <= PT && PT <= ZV))
5877 Fwiden ();
5879 /* Adjust the multibyteness of TEXT to that of the buffer. */
5880 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5881 != ! STRING_MULTIBYTE (text))
5882 text = (STRING_MULTIBYTE (text)
5883 ? Fstring_as_unibyte (text)
5884 : Fstring_to_multibyte (text));
5885 /* Insert before markers in case we are inserting where
5886 the buffer's mark is, and the user's next command is Meta-y. */
5887 insert_from_string_before_markers (text, 0, 0,
5888 SCHARS (text), SBYTES (text), 0);
5890 /* Make sure the process marker's position is valid when the
5891 process buffer is changed in the signal_after_change above.
5892 W3 is known to do that. */
5893 if (BUFFERP (p->buffer)
5894 && (b = XBUFFER (p->buffer), b != current_buffer))
5895 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5896 else
5897 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5899 update_mode_lines = 23;
5901 /* Make sure opoint and the old restrictions
5902 float ahead of any new text just as point would. */
5903 if (opoint >= before)
5905 opoint += PT - before;
5906 opoint_byte += PT_BYTE - before_byte;
5908 if (old_begv > before)
5910 old_begv += PT - before;
5911 old_begv_byte += PT_BYTE - before_byte;
5913 if (old_zv >= before)
5915 old_zv += PT - before;
5916 old_zv_byte += PT_BYTE - before_byte;
5919 /* If the restriction isn't what it should be, set it. */
5920 if (old_begv != BEGV || old_zv != ZV)
5921 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5923 bset_read_only (current_buffer, old_read_only);
5924 SET_PT_BOTH (opoint, opoint_byte);
5926 return Qnil;
5929 /* Sending data to subprocess. */
5931 /* In send_process, when a write fails temporarily,
5932 wait_reading_process_output is called. It may execute user code,
5933 e.g. timers, that attempts to write new data to the same process.
5934 We must ensure that data is sent in the right order, and not
5935 interspersed half-completed with other writes (Bug#10815). This is
5936 handled by the write_queue element of struct process. It is a list
5937 with each entry having the form
5939 (string . (offset . length))
5941 where STRING is a lisp string, OFFSET is the offset into the
5942 string's byte sequence from which we should begin to send, and
5943 LENGTH is the number of bytes left to send. */
5945 /* Create a new entry in write_queue.
5946 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5947 BUF is a pointer to the string sequence of the input_obj or a C
5948 string in case of Qt or Qnil. */
5950 static void
5951 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5952 const char *buf, ptrdiff_t len, bool front)
5954 ptrdiff_t offset;
5955 Lisp_Object entry, obj;
5957 if (STRINGP (input_obj))
5959 offset = buf - SSDATA (input_obj);
5960 obj = input_obj;
5962 else
5964 offset = 0;
5965 obj = make_unibyte_string (buf, len);
5968 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5970 if (front)
5971 pset_write_queue (p, Fcons (entry, p->write_queue));
5972 else
5973 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5976 /* Remove the first element in the write_queue of process P, put its
5977 contents in OBJ, BUF and LEN, and return true. If the
5978 write_queue is empty, return false. */
5980 static bool
5981 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5982 const char **buf, ptrdiff_t *len)
5984 Lisp_Object entry, offset_length;
5985 ptrdiff_t offset;
5987 if (NILP (p->write_queue))
5988 return 0;
5990 entry = XCAR (p->write_queue);
5991 pset_write_queue (p, XCDR (p->write_queue));
5993 *obj = XCAR (entry);
5994 offset_length = XCDR (entry);
5996 *len = XINT (XCDR (offset_length));
5997 offset = XINT (XCAR (offset_length));
5998 *buf = SSDATA (*obj) + offset;
6000 return 1;
6003 /* Send some data to process PROC.
6004 BUF is the beginning of the data; LEN is the number of characters.
6005 OBJECT is the Lisp object that the data comes from. If OBJECT is
6006 nil or t, it means that the data comes from C string.
6008 If OBJECT is not nil, the data is encoded by PROC's coding-system
6009 for encoding before it is sent.
6011 This function can evaluate Lisp code and can garbage collect. */
6013 static void
6014 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6015 Lisp_Object object)
6017 struct Lisp_Process *p = XPROCESS (proc);
6018 ssize_t rv;
6019 struct coding_system *coding;
6021 if (NETCONN_P (proc))
6023 wait_while_connecting (proc);
6024 wait_for_tls_negotiation (proc);
6027 if (p->raw_status_new)
6028 update_status (p);
6029 if (! EQ (p->status, Qrun))
6030 error ("Process %s not running", SDATA (p->name));
6031 if (p->outfd < 0)
6032 error ("Output file descriptor of %s is closed", SDATA (p->name));
6034 coding = proc_encode_coding_system[p->outfd];
6035 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6037 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6038 || (BUFFERP (object)
6039 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6040 || EQ (object, Qt))
6042 pset_encode_coding_system
6043 (p, complement_process_encoding_system (p->encode_coding_system));
6044 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6046 /* The coding system for encoding was changed to raw-text
6047 because we sent a unibyte text previously. Now we are
6048 sending a multibyte text, thus we must encode it by the
6049 original coding system specified for the current process.
6051 Another reason we come here is that the coding system
6052 was just complemented and a new one was returned by
6053 complement_process_encoding_system. */
6054 setup_coding_system (p->encode_coding_system, coding);
6055 Vlast_coding_system_used = p->encode_coding_system;
6057 coding->src_multibyte = 1;
6059 else
6061 coding->src_multibyte = 0;
6062 /* For sending a unibyte text, character code conversion should
6063 not take place but EOL conversion should. So, setup raw-text
6064 or one of the subsidiary if we have not yet done it. */
6065 if (CODING_REQUIRE_ENCODING (coding))
6067 if (CODING_REQUIRE_FLUSHING (coding))
6069 /* But, before changing the coding, we must flush out data. */
6070 coding->mode |= CODING_MODE_LAST_BLOCK;
6071 send_process (proc, "", 0, Qt);
6072 coding->mode &= CODING_MODE_LAST_BLOCK;
6074 setup_coding_system (raw_text_coding_system
6075 (Vlast_coding_system_used),
6076 coding);
6077 coding->src_multibyte = 0;
6080 coding->dst_multibyte = 0;
6082 if (CODING_REQUIRE_ENCODING (coding))
6084 coding->dst_object = Qt;
6085 if (BUFFERP (object))
6087 ptrdiff_t from_byte, from, to;
6088 ptrdiff_t save_pt, save_pt_byte;
6089 struct buffer *cur = current_buffer;
6091 set_buffer_internal (XBUFFER (object));
6092 save_pt = PT, save_pt_byte = PT_BYTE;
6094 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6095 from = BYTE_TO_CHAR (from_byte);
6096 to = BYTE_TO_CHAR (from_byte + len);
6097 TEMP_SET_PT_BOTH (from, from_byte);
6098 encode_coding_object (coding, object, from, from_byte,
6099 to, from_byte + len, Qt);
6100 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6101 set_buffer_internal (cur);
6103 else if (STRINGP (object))
6105 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6106 SBYTES (object), Qt);
6108 else
6110 coding->dst_object = make_unibyte_string (buf, len);
6111 coding->produced = len;
6114 len = coding->produced;
6115 object = coding->dst_object;
6116 buf = SSDATA (object);
6119 /* If there is already data in the write_queue, put the new data
6120 in the back of queue. Otherwise, ignore it. */
6121 if (!NILP (p->write_queue))
6122 write_queue_push (p, object, buf, len, 0);
6124 do /* while !NILP (p->write_queue) */
6126 ptrdiff_t cur_len = -1;
6127 const char *cur_buf;
6128 Lisp_Object cur_object;
6130 /* If write_queue is empty, ignore it. */
6131 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6133 cur_len = len;
6134 cur_buf = buf;
6135 cur_object = object;
6138 while (cur_len > 0)
6140 /* Send this batch, using one or more write calls. */
6141 ptrdiff_t written = 0;
6142 int outfd = p->outfd;
6143 #ifdef DATAGRAM_SOCKETS
6144 if (DATAGRAM_CHAN_P (outfd))
6146 rv = sendto (outfd, cur_buf, cur_len,
6147 0, datagram_address[outfd].sa,
6148 datagram_address[outfd].len);
6149 if (rv >= 0)
6150 written = rv;
6151 else if (errno == EMSGSIZE)
6152 report_file_error ("Sending datagram", proc);
6154 else
6155 #endif
6157 #ifdef HAVE_GNUTLS
6158 if (p->gnutls_p && p->gnutls_state)
6159 written = emacs_gnutls_write (p, cur_buf, cur_len);
6160 else
6161 #endif
6162 written = emacs_write_sig (outfd, cur_buf, cur_len);
6163 rv = (written ? 0 : -1);
6164 if (p->read_output_delay > 0
6165 && p->adaptive_read_buffering == 1)
6167 p->read_output_delay = 0;
6168 process_output_delay_count--;
6169 p->read_output_skip = 0;
6173 if (rv < 0)
6175 if (would_block (errno))
6176 /* Buffer is full. Wait, accepting input;
6177 that may allow the program
6178 to finish doing output and read more. */
6180 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6181 /* A gross hack to work around a bug in FreeBSD.
6182 In the following sequence, read(2) returns
6183 bogus data:
6185 write(2) 1022 bytes
6186 write(2) 954 bytes, get EAGAIN
6187 read(2) 1024 bytes in process_read_output
6188 read(2) 11 bytes in process_read_output
6190 That is, read(2) returns more bytes than have
6191 ever been written successfully. The 1033 bytes
6192 read are the 1022 bytes written successfully
6193 after processing (for example with CRs added if
6194 the terminal is set up that way which it is
6195 here). The same bytes will be seen again in a
6196 later read(2), without the CRs. */
6198 if (errno == EAGAIN)
6200 int flags = FWRITE;
6201 ioctl (p->outfd, TIOCFLUSH, &flags);
6203 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6205 /* Put what we should have written in wait_queue. */
6206 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6207 wait_reading_process_output (0, 20 * 1000 * 1000,
6208 0, 0, Qnil, NULL, 0);
6209 /* Reread queue, to see what is left. */
6210 break;
6212 else if (errno == EPIPE)
6214 p->raw_status_new = 0;
6215 pset_status (p, list2 (Qexit, make_number (256)));
6216 p->tick = ++process_tick;
6217 deactivate_process (proc);
6218 error ("process %s no longer connected to pipe; closed it",
6219 SDATA (p->name));
6221 else
6222 /* This is a real error. */
6223 report_file_error ("Writing to process", proc);
6225 cur_buf += written;
6226 cur_len -= written;
6229 while (!NILP (p->write_queue));
6232 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6233 3, 3, 0,
6234 doc: /* Send current contents of region as input to PROCESS.
6235 PROCESS may be a process, a buffer, the name of a process or buffer, or
6236 nil, indicating the current buffer's process.
6237 Called from program, takes three arguments, PROCESS, START and END.
6238 If the region is more than 500 characters long,
6239 it is sent in several bunches. This may happen even for shorter regions.
6240 Output from processes can arrive in between bunches.
6242 If PROCESS is a non-blocking network process that hasn't been fully
6243 set up yet, this function will block until socket setup has completed. */)
6244 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6246 Lisp_Object proc = get_process (process);
6247 ptrdiff_t start_byte, end_byte;
6249 validate_region (&start, &end);
6251 start_byte = CHAR_TO_BYTE (XINT (start));
6252 end_byte = CHAR_TO_BYTE (XINT (end));
6254 if (XINT (start) < GPT && XINT (end) > GPT)
6255 move_gap_both (XINT (start), start_byte);
6257 if (NETCONN_P (proc))
6258 wait_while_connecting (proc);
6260 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6261 end_byte - start_byte, Fcurrent_buffer ());
6263 return Qnil;
6266 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6267 2, 2, 0,
6268 doc: /* Send PROCESS the contents of STRING as input.
6269 PROCESS may be a process, a buffer, the name of a process or buffer, or
6270 nil, indicating the current buffer's process.
6271 If STRING is more than 500 characters long,
6272 it is sent in several bunches. This may happen even for shorter strings.
6273 Output from processes can arrive in between bunches.
6275 If PROCESS is a non-blocking network process that hasn't been fully
6276 set up yet, this function will block until socket setup has completed. */)
6277 (Lisp_Object process, Lisp_Object string)
6279 CHECK_STRING (string);
6280 Lisp_Object proc = get_process (process);
6281 send_process (proc, SSDATA (string),
6282 SBYTES (string), string);
6283 return Qnil;
6286 /* Return the foreground process group for the tty/pty that
6287 the process P uses. */
6288 static pid_t
6289 emacs_get_tty_pgrp (struct Lisp_Process *p)
6291 pid_t gid = -1;
6293 #ifdef TIOCGPGRP
6294 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6296 int fd;
6297 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6298 master side. Try the slave side. */
6299 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6301 if (fd != -1)
6303 ioctl (fd, TIOCGPGRP, &gid);
6304 emacs_close (fd);
6307 #endif /* defined (TIOCGPGRP ) */
6309 return gid;
6312 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6313 Sprocess_running_child_p, 0, 1, 0,
6314 doc: /* Return non-nil if PROCESS has given the terminal to a
6315 child. If the operating system does not make it possible to find out,
6316 return t. If we can find out, return the numeric ID of the foreground
6317 process group. */)
6318 (Lisp_Object process)
6320 /* Initialize in case ioctl doesn't exist or gives an error,
6321 in a way that will cause returning t. */
6322 Lisp_Object proc = get_process (process);
6323 struct Lisp_Process *p = XPROCESS (proc);
6325 if (!EQ (p->type, Qreal))
6326 error ("Process %s is not a subprocess",
6327 SDATA (p->name));
6328 if (p->infd < 0)
6329 error ("Process %s is not active",
6330 SDATA (p->name));
6332 pid_t gid = emacs_get_tty_pgrp (p);
6334 if (gid == p->pid)
6335 return Qnil;
6336 if (gid != -1)
6337 return make_number (gid);
6338 return Qt;
6341 /* Send a signal number SIGNO to PROCESS.
6342 If CURRENT_GROUP is t, that means send to the process group
6343 that currently owns the terminal being used to communicate with PROCESS.
6344 This is used for various commands in shell mode.
6345 If CURRENT_GROUP is lambda, that means send to the process group
6346 that currently owns the terminal, but only if it is NOT the shell itself.
6348 If NOMSG is false, insert signal-announcements into process's buffers
6349 right away.
6351 If we can, we try to signal PROCESS by sending control characters
6352 down the pty. This allows us to signal inferiors who have changed
6353 their uid, for which kill would return an EPERM error. */
6355 static void
6356 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6357 bool nomsg)
6359 Lisp_Object proc;
6360 struct Lisp_Process *p;
6361 pid_t gid;
6362 bool no_pgrp = 0;
6364 proc = get_process (process);
6365 p = XPROCESS (proc);
6367 if (!EQ (p->type, Qreal))
6368 error ("Process %s is not a subprocess",
6369 SDATA (p->name));
6370 if (p->infd < 0)
6371 error ("Process %s is not active",
6372 SDATA (p->name));
6374 if (!p->pty_flag)
6375 current_group = Qnil;
6377 /* If we are using pgrps, get a pgrp number and make it negative. */
6378 if (NILP (current_group))
6379 /* Send the signal to the shell's process group. */
6380 gid = p->pid;
6381 else
6383 #ifdef SIGNALS_VIA_CHARACTERS
6384 /* If possible, send signals to the entire pgrp
6385 by sending an input character to it. */
6387 struct termios t;
6388 cc_t *sig_char = NULL;
6390 tcgetattr (p->infd, &t);
6392 switch (signo)
6394 case SIGINT:
6395 sig_char = &t.c_cc[VINTR];
6396 break;
6398 case SIGQUIT:
6399 sig_char = &t.c_cc[VQUIT];
6400 break;
6402 case SIGTSTP:
6403 #ifdef VSWTCH
6404 sig_char = &t.c_cc[VSWTCH];
6405 #else
6406 sig_char = &t.c_cc[VSUSP];
6407 #endif
6408 break;
6411 if (sig_char && *sig_char != CDISABLE)
6413 send_process (proc, (char *) sig_char, 1, Qnil);
6414 return;
6416 /* If we can't send the signal with a character,
6417 fall through and send it another way. */
6419 /* The code above may fall through if it can't
6420 handle the signal. */
6421 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6423 #ifdef TIOCGPGRP
6424 /* Get the current pgrp using the tty itself, if we have that.
6425 Otherwise, use the pty to get the pgrp.
6426 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6427 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6428 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6429 His patch indicates that if TIOCGPGRP returns an error, then
6430 we should just assume that p->pid is also the process group id. */
6432 gid = emacs_get_tty_pgrp (p);
6434 if (gid == -1)
6435 /* If we can't get the information, assume
6436 the shell owns the tty. */
6437 gid = p->pid;
6439 /* It is not clear whether anything really can set GID to -1.
6440 Perhaps on some system one of those ioctls can or could do so.
6441 Or perhaps this is vestigial. */
6442 if (gid == -1)
6443 no_pgrp = 1;
6444 #else /* ! defined (TIOCGPGRP) */
6445 /* Can't select pgrps on this system, so we know that
6446 the child itself heads the pgrp. */
6447 gid = p->pid;
6448 #endif /* ! defined (TIOCGPGRP) */
6450 /* If current_group is lambda, and the shell owns the terminal,
6451 don't send any signal. */
6452 if (EQ (current_group, Qlambda) && gid == p->pid)
6453 return;
6456 #ifdef SIGCONT
6457 if (signo == SIGCONT)
6459 p->raw_status_new = 0;
6460 pset_status (p, Qrun);
6461 p->tick = ++process_tick;
6462 if (!nomsg)
6464 status_notify (NULL, NULL);
6465 redisplay_preserve_echo_area (13);
6468 #endif
6470 #ifdef TIOCSIGSEND
6471 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6472 We don't know whether the bug is fixed in later HP-UX versions. */
6473 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6474 return;
6475 #endif
6477 /* If we don't have process groups, send the signal to the immediate
6478 subprocess. That isn't really right, but it's better than any
6479 obvious alternative. */
6480 pid_t pid = no_pgrp ? gid : - gid;
6482 /* Do not kill an already-reaped process, as that could kill an
6483 innocent bystander that happens to have the same process ID. */
6484 sigset_t oldset;
6485 block_child_signal (&oldset);
6486 if (p->alive)
6487 kill (pid, signo);
6488 unblock_child_signal (&oldset);
6491 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6492 doc: /* Interrupt process PROCESS.
6493 PROCESS may be a process, a buffer, or the name of a process or buffer.
6494 No arg or nil means current buffer's process.
6495 Second arg CURRENT-GROUP non-nil means send signal to
6496 the current process-group of the process's controlling terminal
6497 rather than to the process's own process group.
6498 If the process is a shell, this means interrupt current subjob
6499 rather than the shell.
6501 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6502 don't send the signal. */)
6503 (Lisp_Object process, Lisp_Object current_group)
6505 process_send_signal (process, SIGINT, current_group, 0);
6506 return process;
6509 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6510 doc: /* Kill process PROCESS. May be process or name of one.
6511 See function `interrupt-process' for more details on usage. */)
6512 (Lisp_Object process, Lisp_Object current_group)
6514 process_send_signal (process, SIGKILL, current_group, 0);
6515 return process;
6518 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6519 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6520 See function `interrupt-process' for more details on usage. */)
6521 (Lisp_Object process, Lisp_Object current_group)
6523 process_send_signal (process, SIGQUIT, current_group, 0);
6524 return process;
6527 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6528 doc: /* Stop process PROCESS. May be process or name of one.
6529 See function `interrupt-process' for more details on usage.
6530 If PROCESS is a network or serial process, inhibit handling of incoming
6531 traffic. */)
6532 (Lisp_Object process, Lisp_Object current_group)
6534 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6535 || PIPECONN_P (process)))
6537 struct Lisp_Process *p;
6539 p = XPROCESS (process);
6540 if (NILP (p->command)
6541 && p->infd >= 0)
6543 FD_CLR (p->infd, &input_wait_mask);
6544 FD_CLR (p->infd, &non_keyboard_wait_mask);
6546 pset_command (p, Qt);
6547 return process;
6549 #ifndef SIGTSTP
6550 error ("No SIGTSTP support");
6551 #else
6552 process_send_signal (process, SIGTSTP, current_group, 0);
6553 #endif
6554 return process;
6557 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6558 doc: /* Continue process PROCESS. May be process or name of one.
6559 See function `interrupt-process' for more details on usage.
6560 If PROCESS is a network or serial process, resume handling of incoming
6561 traffic. */)
6562 (Lisp_Object process, Lisp_Object current_group)
6564 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6565 || PIPECONN_P (process)))
6567 struct Lisp_Process *p;
6569 p = XPROCESS (process);
6570 if (EQ (p->command, Qt)
6571 && p->infd >= 0
6572 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6574 FD_SET (p->infd, &input_wait_mask);
6575 FD_SET (p->infd, &non_keyboard_wait_mask);
6576 #ifdef WINDOWSNT
6577 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6578 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6579 #else /* not WINDOWSNT */
6580 tcflush (p->infd, TCIFLUSH);
6581 #endif /* not WINDOWSNT */
6583 pset_command (p, Qnil);
6584 return process;
6586 #ifdef SIGCONT
6587 process_send_signal (process, SIGCONT, current_group, 0);
6588 #else
6589 error ("No SIGCONT support");
6590 #endif
6591 return process;
6594 /* Return the integer value of the signal whose abbreviation is ABBR,
6595 or a negative number if there is no such signal. */
6596 static int
6597 abbr_to_signal (char const *name)
6599 int i, signo;
6600 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6602 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6603 name += 3;
6605 for (i = 0; i < sizeof sigbuf; i++)
6607 sigbuf[i] = c_toupper (name[i]);
6608 if (! sigbuf[i])
6609 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6612 return -1;
6615 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6616 2, 2, "sProcess (name or number): \nnSignal code: ",
6617 doc: /* Send PROCESS the signal with code SIGCODE.
6618 PROCESS may also be a number specifying the process id of the
6619 process to signal; in this case, the process need not be a child of
6620 this Emacs.
6621 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6622 (Lisp_Object process, Lisp_Object sigcode)
6624 pid_t pid;
6625 int signo;
6627 if (STRINGP (process))
6629 Lisp_Object tem = Fget_process (process);
6630 if (NILP (tem))
6632 Lisp_Object process_number
6633 = string_to_number (SSDATA (process), 10, 1);
6634 if (NUMBERP (process_number))
6635 tem = process_number;
6637 process = tem;
6639 else if (!NUMBERP (process))
6640 process = get_process (process);
6642 if (NILP (process))
6643 return process;
6645 if (NUMBERP (process))
6646 CONS_TO_INTEGER (process, pid_t, pid);
6647 else
6649 CHECK_PROCESS (process);
6650 pid = XPROCESS (process)->pid;
6651 if (pid <= 0)
6652 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6655 if (INTEGERP (sigcode))
6657 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6658 signo = XINT (sigcode);
6660 else
6662 char *name;
6664 CHECK_SYMBOL (sigcode);
6665 name = SSDATA (SYMBOL_NAME (sigcode));
6667 signo = abbr_to_signal (name);
6668 if (signo < 0)
6669 error ("Undefined signal name %s", name);
6672 return make_number (kill (pid, signo));
6675 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6676 doc: /* Make PROCESS see end-of-file in its input.
6677 EOF comes after any text already sent to it.
6678 PROCESS may be a process, a buffer, the name of a process or buffer, or
6679 nil, indicating the current buffer's process.
6680 If PROCESS is a network connection, or is a process communicating
6681 through a pipe (as opposed to a pty), then you cannot send any more
6682 text to PROCESS after you call this function.
6683 If PROCESS is a serial process, wait until all output written to the
6684 process has been transmitted to the serial port. */)
6685 (Lisp_Object process)
6687 Lisp_Object proc;
6688 struct coding_system *coding = NULL;
6689 int outfd;
6691 proc = get_process (process);
6693 if (NETCONN_P (proc))
6694 wait_while_connecting (proc);
6696 if (DATAGRAM_CONN_P (proc))
6697 return process;
6700 outfd = XPROCESS (proc)->outfd;
6701 if (outfd >= 0)
6702 coding = proc_encode_coding_system[outfd];
6704 /* Make sure the process is really alive. */
6705 if (XPROCESS (proc)->raw_status_new)
6706 update_status (XPROCESS (proc));
6707 if (! EQ (XPROCESS (proc)->status, Qrun))
6708 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6710 if (coding && CODING_REQUIRE_FLUSHING (coding))
6712 coding->mode |= CODING_MODE_LAST_BLOCK;
6713 send_process (proc, "", 0, Qnil);
6716 if (XPROCESS (proc)->pty_flag)
6717 send_process (proc, "\004", 1, Qnil);
6718 else if (EQ (XPROCESS (proc)->type, Qserial))
6720 #ifndef WINDOWSNT
6721 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6722 report_file_error ("Failed tcdrain", Qnil);
6723 #endif /* not WINDOWSNT */
6724 /* Do nothing on Windows because writes are blocking. */
6726 else
6728 struct Lisp_Process *p = XPROCESS (proc);
6729 int old_outfd = p->outfd;
6730 int new_outfd;
6732 #ifdef HAVE_SHUTDOWN
6733 /* If this is a network connection, or socketpair is used
6734 for communication with the subprocess, call shutdown to cause EOF.
6735 (In some old system, shutdown to socketpair doesn't work.
6736 Then we just can't win.) */
6737 if (0 <= old_outfd
6738 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6739 shutdown (old_outfd, 1);
6740 #endif
6741 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6742 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6743 if (new_outfd < 0)
6744 report_file_error ("Opening null device", Qnil);
6745 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6746 p->outfd = new_outfd;
6748 if (!proc_encode_coding_system[new_outfd])
6749 proc_encode_coding_system[new_outfd]
6750 = xmalloc (sizeof (struct coding_system));
6751 if (old_outfd >= 0)
6753 *proc_encode_coding_system[new_outfd]
6754 = *proc_encode_coding_system[old_outfd];
6755 memset (proc_encode_coding_system[old_outfd], 0,
6756 sizeof (struct coding_system));
6758 else
6759 setup_coding_system (p->encode_coding_system,
6760 proc_encode_coding_system[new_outfd]);
6762 return process;
6765 /* The main Emacs thread records child processes in three places:
6767 - Vprocess_alist, for asynchronous subprocesses, which are child
6768 processes visible to Lisp.
6770 - deleted_pid_list, for child processes invisible to Lisp,
6771 typically because of delete-process. These are recorded so that
6772 the processes can be reaped when they exit, so that the operating
6773 system's process table is not cluttered by zombies.
6775 - the local variable PID in Fcall_process, call_process_cleanup and
6776 call_process_kill, for synchronous subprocesses.
6777 record_unwind_protect is used to make sure this process is not
6778 forgotten: if the user interrupts call-process and the child
6779 process refuses to exit immediately even with two C-g's,
6780 call_process_kill adds PID's contents to deleted_pid_list before
6781 returning.
6783 The main Emacs thread invokes waitpid only on child processes that
6784 it creates and that have not been reaped. This avoid races on
6785 platforms such as GTK, where other threads create their own
6786 subprocesses which the main thread should not reap. For example,
6787 if the main thread attempted to reap an already-reaped child, it
6788 might inadvertently reap a GTK-created process that happened to
6789 have the same process ID. */
6791 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6792 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6793 keep track of its own children. GNUstep is similar. */
6795 static void dummy_handler (int sig) {}
6796 static signal_handler_t volatile lib_child_handler;
6798 /* Handle a SIGCHLD signal by looking for known child processes of
6799 Emacs whose status have changed. For each one found, record its
6800 new status.
6802 All we do is change the status; we do not run sentinels or print
6803 notifications. That is saved for the next time keyboard input is
6804 done, in order to avoid timing errors.
6806 ** WARNING: this can be called during garbage collection.
6807 Therefore, it must not be fooled by the presence of mark bits in
6808 Lisp objects.
6810 ** USG WARNING: Although it is not obvious from the documentation
6811 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6812 signal() before executing at least one wait(), otherwise the
6813 handler will be called again, resulting in an infinite loop. The
6814 relevant portion of the documentation reads "SIGCLD signals will be
6815 queued and the signal-catching function will be continually
6816 reentered until the queue is empty". Invoking signal() causes the
6817 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6818 Inc.
6820 ** Malloc WARNING: This should never call malloc either directly or
6821 indirectly; if it does, that is a bug. */
6823 static void
6824 handle_child_signal (int sig)
6826 Lisp_Object tail, proc;
6828 /* Find the process that signaled us, and record its status. */
6830 /* The process can have been deleted by Fdelete_process, or have
6831 been started asynchronously by Fcall_process. */
6832 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6834 bool all_pids_are_fixnums
6835 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6836 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6837 Lisp_Object head = XCAR (tail);
6838 Lisp_Object xpid;
6839 if (! CONSP (head))
6840 continue;
6841 xpid = XCAR (head);
6842 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6844 pid_t deleted_pid;
6845 if (INTEGERP (xpid))
6846 deleted_pid = XINT (xpid);
6847 else
6848 deleted_pid = XFLOAT_DATA (xpid);
6849 if (child_status_changed (deleted_pid, 0, 0))
6851 if (STRINGP (XCDR (head)))
6852 unlink (SSDATA (XCDR (head)));
6853 XSETCAR (tail, Qnil);
6858 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6859 FOR_EACH_PROCESS (tail, proc)
6861 struct Lisp_Process *p = XPROCESS (proc);
6862 int status;
6864 if (p->alive
6865 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6867 /* Change the status of the process that was found. */
6868 p->tick = ++process_tick;
6869 p->raw_status = status;
6870 p->raw_status_new = 1;
6872 /* If process has terminated, stop waiting for its output. */
6873 if (WIFSIGNALED (status) || WIFEXITED (status))
6875 bool clear_desc_flag = 0;
6876 p->alive = 0;
6877 if (p->infd >= 0)
6878 clear_desc_flag = 1;
6880 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6881 if (clear_desc_flag)
6883 FD_CLR (p->infd, &input_wait_mask);
6884 FD_CLR (p->infd, &non_keyboard_wait_mask);
6890 lib_child_handler (sig);
6891 #ifdef NS_IMPL_GNUSTEP
6892 /* NSTask in GNUstep sets its child handler each time it is called.
6893 So we must re-set ours. */
6894 catch_child_signal ();
6895 #endif
6898 static void
6899 deliver_child_signal (int sig)
6901 deliver_process_signal (sig, handle_child_signal);
6905 static Lisp_Object
6906 exec_sentinel_error_handler (Lisp_Object error_val)
6908 cmd_error_internal (error_val, "error in process sentinel: ");
6909 Vinhibit_quit = Qt;
6910 update_echo_area ();
6911 Fsleep_for (make_number (2), Qnil);
6912 return Qt;
6915 static void
6916 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6918 Lisp_Object sentinel, odeactivate;
6919 struct Lisp_Process *p = XPROCESS (proc);
6920 ptrdiff_t count = SPECPDL_INDEX ();
6921 bool outer_running_asynch_code = running_asynch_code;
6922 int waiting = waiting_for_user_input_p;
6924 if (inhibit_sentinels)
6925 return;
6927 odeactivate = Vdeactivate_mark;
6928 #if 0
6929 Lisp_Object obuffer, okeymap;
6930 XSETBUFFER (obuffer, current_buffer);
6931 okeymap = BVAR (current_buffer, keymap);
6932 #endif
6934 /* There's no good reason to let sentinels change the current
6935 buffer, and many callers of accept-process-output, sit-for, and
6936 friends don't expect current-buffer to be changed from under them. */
6937 record_unwind_current_buffer ();
6939 sentinel = p->sentinel;
6941 /* Inhibit quit so that random quits don't screw up a running filter. */
6942 specbind (Qinhibit_quit, Qt);
6943 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6945 /* In case we get recursively called,
6946 and we already saved the match data nonrecursively,
6947 save the same match data in safely recursive fashion. */
6948 if (outer_running_asynch_code)
6950 Lisp_Object tem;
6951 tem = Fmatch_data (Qnil, Qnil, Qnil);
6952 restore_search_regs ();
6953 record_unwind_save_match_data ();
6954 Fset_match_data (tem, Qt);
6957 /* For speed, if a search happens within this code,
6958 save the match data in a special nonrecursive fashion. */
6959 running_asynch_code = 1;
6961 internal_condition_case_1 (read_process_output_call,
6962 list3 (sentinel, proc, reason),
6963 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6964 exec_sentinel_error_handler);
6966 /* If we saved the match data nonrecursively, restore it now. */
6967 restore_search_regs ();
6968 running_asynch_code = outer_running_asynch_code;
6970 Vdeactivate_mark = odeactivate;
6972 /* Restore waiting_for_user_input_p as it was
6973 when we were called, in case the filter clobbered it. */
6974 waiting_for_user_input_p = waiting;
6976 #if 0
6977 if (! EQ (Fcurrent_buffer (), obuffer)
6978 || ! EQ (current_buffer->keymap, okeymap))
6979 #endif
6980 /* But do it only if the caller is actually going to read events.
6981 Otherwise there's no need to make him wake up, and it could
6982 cause trouble (for example it would make sit_for return). */
6983 if (waiting_for_user_input_p == -1)
6984 record_asynch_buffer_change ();
6986 unbind_to (count, Qnil);
6989 /* Report all recent events of a change in process status
6990 (either run the sentinel or output a message).
6991 This is usually done while Emacs is waiting for keyboard input
6992 but can be done at other times.
6994 Return positive if any input was received from WAIT_PROC (or from
6995 any process if WAIT_PROC is null), zero if input was attempted but
6996 none received, and negative if we didn't even try. */
6998 static int
6999 status_notify (struct Lisp_Process *deleting_process,
7000 struct Lisp_Process *wait_proc)
7002 Lisp_Object proc;
7003 Lisp_Object tail, msg;
7004 int got_some_output = -1;
7006 tail = Qnil;
7007 msg = Qnil;
7009 /* Set this now, so that if new processes are created by sentinels
7010 that we run, we get called again to handle their status changes. */
7011 update_tick = process_tick;
7013 FOR_EACH_PROCESS (tail, proc)
7015 Lisp_Object symbol;
7016 register struct Lisp_Process *p = XPROCESS (proc);
7018 if (p->tick != p->update_tick)
7020 p->update_tick = p->tick;
7022 /* If process is still active, read any output that remains. */
7023 while (! EQ (p->filter, Qt)
7024 && ! connecting_status (p->status)
7025 && ! EQ (p->status, Qlisten)
7026 /* Network or serial process not stopped: */
7027 && ! EQ (p->command, Qt)
7028 && p->infd >= 0
7029 && p != deleting_process)
7031 int nread = read_process_output (proc, p->infd);
7032 if ((!wait_proc || wait_proc == XPROCESS (proc))
7033 && got_some_output < nread)
7034 got_some_output = nread;
7035 if (nread <= 0)
7036 break;
7039 /* Get the text to use for the message. */
7040 if (p->raw_status_new)
7041 update_status (p);
7042 msg = status_message (p);
7044 /* If process is terminated, deactivate it or delete it. */
7045 symbol = p->status;
7046 if (CONSP (p->status))
7047 symbol = XCAR (p->status);
7049 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7050 || EQ (symbol, Qclosed))
7052 if (delete_exited_processes)
7053 remove_process (proc);
7054 else
7055 deactivate_process (proc);
7058 /* The actions above may have further incremented p->tick.
7059 So set p->update_tick again so that an error in the sentinel will
7060 not cause this code to be run again. */
7061 p->update_tick = p->tick;
7062 /* Now output the message suitably. */
7063 exec_sentinel (proc, msg);
7064 if (BUFFERP (p->buffer))
7065 /* In case it uses %s in mode-line-format. */
7066 bset_update_mode_line (XBUFFER (p->buffer));
7068 } /* end for */
7070 return got_some_output;
7073 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7074 Sinternal_default_process_sentinel, 2, 2, 0,
7075 doc: /* Function used as default sentinel for processes.
7076 This inserts a status message into the process's buffer, if there is one. */)
7077 (Lisp_Object proc, Lisp_Object msg)
7079 Lisp_Object buffer, symbol;
7080 struct Lisp_Process *p;
7081 CHECK_PROCESS (proc);
7082 p = XPROCESS (proc);
7083 buffer = p->buffer;
7084 symbol = p->status;
7085 if (CONSP (symbol))
7086 symbol = XCAR (symbol);
7088 if (!EQ (symbol, Qrun) && !NILP (buffer))
7090 Lisp_Object tem;
7091 struct buffer *old = current_buffer;
7092 ptrdiff_t opoint, opoint_byte;
7093 ptrdiff_t before, before_byte;
7095 /* Avoid error if buffer is deleted
7096 (probably that's why the process is dead, too). */
7097 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7098 return Qnil;
7099 Fset_buffer (buffer);
7101 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7102 msg = (code_convert_string_norecord
7103 (msg, Vlocale_coding_system, 1));
7105 opoint = PT;
7106 opoint_byte = PT_BYTE;
7107 /* Insert new output into buffer
7108 at the current end-of-output marker,
7109 thus preserving logical ordering of input and output. */
7110 if (XMARKER (p->mark)->buffer)
7111 Fgoto_char (p->mark);
7112 else
7113 SET_PT_BOTH (ZV, ZV_BYTE);
7115 before = PT;
7116 before_byte = PT_BYTE;
7118 tem = BVAR (current_buffer, read_only);
7119 bset_read_only (current_buffer, Qnil);
7120 insert_string ("\nProcess ");
7121 { /* FIXME: temporary kludge. */
7122 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7123 insert_string (" ");
7124 Finsert (1, &msg);
7125 bset_read_only (current_buffer, tem);
7126 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7128 if (opoint >= before)
7129 SET_PT_BOTH (opoint + (PT - before),
7130 opoint_byte + (PT_BYTE - before_byte));
7131 else
7132 SET_PT_BOTH (opoint, opoint_byte);
7134 set_buffer_internal (old);
7136 return Qnil;
7140 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7141 Sset_process_coding_system, 1, 3, 0,
7142 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7143 DECODING will be used to decode subprocess output and ENCODING to
7144 encode subprocess input. */)
7145 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7147 CHECK_PROCESS (process);
7149 struct Lisp_Process *p = XPROCESS (process);
7151 Fcheck_coding_system (decoding);
7152 Fcheck_coding_system (encoding);
7153 encoding = coding_inherit_eol_type (encoding, Qnil);
7154 pset_decode_coding_system (p, decoding);
7155 pset_encode_coding_system (p, encoding);
7157 /* If the sockets haven't been set up yet, the final setup part of
7158 this will be called asynchronously. */
7159 if (p->infd < 0 || p->outfd < 0)
7160 return Qnil;
7162 setup_process_coding_systems (process);
7164 return Qnil;
7167 DEFUN ("process-coding-system",
7168 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7169 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7170 (register Lisp_Object process)
7172 CHECK_PROCESS (process);
7173 return Fcons (XPROCESS (process)->decode_coding_system,
7174 XPROCESS (process)->encode_coding_system);
7177 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7178 Sset_process_filter_multibyte, 2, 2, 0,
7179 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7180 If FLAG is non-nil, the filter is given multibyte strings.
7181 If FLAG is nil, the filter is given unibyte strings. In this case,
7182 all character code conversion except for end-of-line conversion is
7183 suppressed. */)
7184 (Lisp_Object process, Lisp_Object flag)
7186 CHECK_PROCESS (process);
7188 struct Lisp_Process *p = XPROCESS (process);
7189 if (NILP (flag))
7190 pset_decode_coding_system
7191 (p, raw_text_coding_system (p->decode_coding_system));
7193 /* If the sockets haven't been set up yet, the final setup part of
7194 this will be called asynchronously. */
7195 if (p->infd < 0 || p->outfd < 0)
7196 return Qnil;
7198 setup_process_coding_systems (process);
7200 return Qnil;
7203 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7204 Sprocess_filter_multibyte_p, 1, 1, 0,
7205 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7206 (Lisp_Object process)
7208 CHECK_PROCESS (process);
7209 struct Lisp_Process *p = XPROCESS (process);
7210 if (p->infd < 0)
7211 return Qnil;
7212 struct coding_system *coding = proc_decode_coding_system[p->infd];
7213 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7219 # ifdef HAVE_GPM
7221 void
7222 add_gpm_wait_descriptor (int desc)
7224 add_keyboard_wait_descriptor (desc);
7227 void
7228 delete_gpm_wait_descriptor (int desc)
7230 delete_keyboard_wait_descriptor (desc);
7233 # endif
7235 # ifdef USABLE_SIGIO
7237 /* Return true if *MASK has a bit set
7238 that corresponds to one of the keyboard input descriptors. */
7240 static bool
7241 keyboard_bit_set (fd_set *mask)
7243 int fd;
7245 for (fd = 0; fd <= max_input_desc; fd++)
7246 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7247 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7248 return 1;
7250 return 0;
7252 # endif
7254 #else /* not subprocesses */
7256 /* Defined in msdos.c. */
7257 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7258 struct timespec *, void *);
7260 /* Implementation of wait_reading_process_output, assuming that there
7261 are no subprocesses. Used only by the MS-DOS build.
7263 Wait for timeout to elapse and/or keyboard input to be available.
7265 TIME_LIMIT is:
7266 timeout in seconds
7267 If negative, gobble data immediately available but don't wait for any.
7269 NSECS is:
7270 an additional duration to wait, measured in nanoseconds
7271 If TIME_LIMIT is zero, then:
7272 If NSECS == 0, there is no limit.
7273 If NSECS > 0, the timeout consists of NSECS only.
7274 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7276 READ_KBD is:
7277 0 to ignore keyboard input, or
7278 1 to return when input is available, or
7279 -1 means caller will actually read the input, so don't throw to
7280 the quit handler.
7282 see full version for other parameters. We know that wait_proc will
7283 always be NULL, since `subprocesses' isn't defined.
7285 DO_DISPLAY means redisplay should be done to show subprocess
7286 output that arrives.
7288 Return -1 signifying we got no output and did not try. */
7291 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7292 bool do_display,
7293 Lisp_Object wait_for_cell,
7294 struct Lisp_Process *wait_proc, int just_wait_proc)
7296 register int nfds;
7297 struct timespec end_time, timeout;
7298 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7300 if (TYPE_MAXIMUM (time_t) < time_limit)
7301 time_limit = TYPE_MAXIMUM (time_t);
7303 if (time_limit < 0 || nsecs < 0)
7304 wait = MINIMUM;
7305 else if (time_limit > 0 || nsecs > 0)
7307 wait = TIMEOUT;
7308 end_time = timespec_add (current_timespec (),
7309 make_timespec (time_limit, nsecs));
7311 else
7312 wait = INFINITY;
7314 /* Turn off periodic alarms (in case they are in use)
7315 and then turn off any other atimers,
7316 because the select emulator uses alarms. */
7317 stop_polling ();
7318 turn_on_atimers (0);
7320 while (1)
7322 bool timeout_reduced_for_timers = false;
7323 fd_set waitchannels;
7324 int xerrno;
7326 /* If calling from keyboard input, do not quit
7327 since we want to return C-g as an input character.
7328 Otherwise, do pending quit if requested. */
7329 if (read_kbd >= 0)
7330 QUIT;
7332 /* Exit now if the cell we're waiting for became non-nil. */
7333 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7334 break;
7336 /* Compute time from now till when time limit is up. */
7337 /* Exit if already run out. */
7338 if (wait == TIMEOUT)
7340 struct timespec now = current_timespec ();
7341 if (timespec_cmp (end_time, now) <= 0)
7342 break;
7343 timeout = timespec_sub (end_time, now);
7345 else
7346 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7348 /* If our caller will not immediately handle keyboard events,
7349 run timer events directly.
7350 (Callers that will immediately read keyboard events
7351 call timer_delay on their own.) */
7352 if (NILP (wait_for_cell))
7354 struct timespec timer_delay;
7358 unsigned old_timers_run = timers_run;
7359 timer_delay = timer_check ();
7360 if (timers_run != old_timers_run && do_display)
7361 /* We must retry, since a timer may have requeued itself
7362 and that could alter the time delay. */
7363 redisplay_preserve_echo_area (14);
7364 else
7365 break;
7367 while (!detect_input_pending ());
7369 /* If there is unread keyboard input, also return. */
7370 if (read_kbd != 0
7371 && requeued_events_pending_p ())
7372 break;
7374 if (timespec_valid_p (timer_delay))
7376 if (timespec_cmp (timer_delay, timeout) < 0)
7378 timeout = timer_delay;
7379 timeout_reduced_for_timers = true;
7384 /* Cause C-g and alarm signals to take immediate action,
7385 and cause input available signals to zero out timeout. */
7386 if (read_kbd < 0)
7387 set_waiting_for_input (&timeout);
7389 /* If a frame has been newly mapped and needs updating,
7390 reprocess its display stuff. */
7391 if (frame_garbaged && do_display)
7393 clear_waiting_for_input ();
7394 redisplay_preserve_echo_area (15);
7395 if (read_kbd < 0)
7396 set_waiting_for_input (&timeout);
7399 /* Wait till there is something to do. */
7400 FD_ZERO (&waitchannels);
7401 if (read_kbd && detect_input_pending ())
7402 nfds = 0;
7403 else
7405 if (read_kbd || !NILP (wait_for_cell))
7406 FD_SET (0, &waitchannels);
7407 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7410 xerrno = errno;
7412 /* Make C-g and alarm signals set flags again. */
7413 clear_waiting_for_input ();
7415 /* If we woke up due to SIGWINCH, actually change size now. */
7416 do_pending_window_change (0);
7418 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7419 /* We waited the full specified time, so return now. */
7420 break;
7422 if (nfds == -1)
7424 /* If the system call was interrupted, then go around the
7425 loop again. */
7426 if (xerrno == EINTR)
7427 FD_ZERO (&waitchannels);
7428 else
7429 report_file_errno ("Failed select", Qnil, xerrno);
7432 /* Check for keyboard input. */
7434 if (read_kbd
7435 && detect_input_pending_run_timers (do_display))
7437 swallow_events (do_display);
7438 if (detect_input_pending_run_timers (do_display))
7439 break;
7442 /* If there is unread keyboard input, also return. */
7443 if (read_kbd
7444 && requeued_events_pending_p ())
7445 break;
7447 /* If wait_for_cell. check for keyboard input
7448 but don't run any timers.
7449 ??? (It seems wrong to me to check for keyboard
7450 input at all when wait_for_cell, but the code
7451 has been this way since July 1994.
7452 Try changing this after version 19.31.) */
7453 if (! NILP (wait_for_cell)
7454 && detect_input_pending ())
7456 swallow_events (do_display);
7457 if (detect_input_pending ())
7458 break;
7461 /* Exit now if the cell we're waiting for became non-nil. */
7462 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7463 break;
7466 start_polling ();
7468 return -1;
7471 #endif /* not subprocesses */
7473 /* The following functions are needed even if async subprocesses are
7474 not supported. Some of them are no-op stubs in that case. */
7476 #ifdef HAVE_TIMERFD
7478 /* Add FD, which is a descriptor returned by timerfd_create,
7479 to the set of non-keyboard input descriptors. */
7481 void
7482 add_timer_wait_descriptor (int fd)
7484 FD_SET (fd, &input_wait_mask);
7485 FD_SET (fd, &non_keyboard_wait_mask);
7486 FD_SET (fd, &non_process_wait_mask);
7487 fd_callback_info[fd].func = timerfd_callback;
7488 fd_callback_info[fd].data = NULL;
7489 fd_callback_info[fd].condition |= FOR_READ;
7490 if (fd > max_input_desc)
7491 max_input_desc = fd;
7494 #endif /* HAVE_TIMERFD */
7496 /* If program file NAME starts with /: for quoting a magic
7497 name, remove that, preserving the multibyteness of NAME. */
7499 Lisp_Object
7500 remove_slash_colon (Lisp_Object name)
7502 return
7503 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7504 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7505 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7506 : name);
7509 /* Add DESC to the set of keyboard input descriptors. */
7511 void
7512 add_keyboard_wait_descriptor (int desc)
7514 #ifdef subprocesses /* Actually means "not MSDOS". */
7515 FD_SET (desc, &input_wait_mask);
7516 FD_SET (desc, &non_process_wait_mask);
7517 if (desc > max_input_desc)
7518 max_input_desc = desc;
7519 #endif
7522 /* From now on, do not expect DESC to give keyboard input. */
7524 void
7525 delete_keyboard_wait_descriptor (int desc)
7527 #ifdef subprocesses
7528 FD_CLR (desc, &input_wait_mask);
7529 FD_CLR (desc, &non_process_wait_mask);
7530 delete_input_desc (desc);
7531 #endif
7534 /* Setup coding systems of PROCESS. */
7536 void
7537 setup_process_coding_systems (Lisp_Object process)
7539 #ifdef subprocesses
7540 struct Lisp_Process *p = XPROCESS (process);
7541 int inch = p->infd;
7542 int outch = p->outfd;
7543 Lisp_Object coding_system;
7545 if (inch < 0 || outch < 0)
7546 return;
7548 if (!proc_decode_coding_system[inch])
7549 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7550 coding_system = p->decode_coding_system;
7551 if (EQ (p->filter, Qinternal_default_process_filter)
7552 && BUFFERP (p->buffer))
7554 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7555 coding_system = raw_text_coding_system (coding_system);
7557 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7559 if (!proc_encode_coding_system[outch])
7560 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7561 setup_coding_system (p->encode_coding_system,
7562 proc_encode_coding_system[outch]);
7563 #endif
7566 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7567 doc: /* Return the (or a) live process associated with BUFFER.
7568 BUFFER may be a buffer or the name of one.
7569 Return nil if all processes associated with BUFFER have been
7570 deleted or killed. */)
7571 (register Lisp_Object buffer)
7573 #ifdef subprocesses
7574 register Lisp_Object buf, tail, proc;
7576 if (NILP (buffer)) return Qnil;
7577 buf = Fget_buffer (buffer);
7578 if (NILP (buf)) return Qnil;
7580 FOR_EACH_PROCESS (tail, proc)
7581 if (EQ (XPROCESS (proc)->buffer, buf))
7582 return proc;
7583 #endif /* subprocesses */
7584 return Qnil;
7587 DEFUN ("process-inherit-coding-system-flag",
7588 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7589 1, 1, 0,
7590 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7591 If this flag is t, `buffer-file-coding-system' of the buffer
7592 associated with PROCESS will inherit the coding system used to decode
7593 the process output. */)
7594 (register Lisp_Object process)
7596 #ifdef subprocesses
7597 CHECK_PROCESS (process);
7598 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7599 #else
7600 /* Ignore the argument and return the value of
7601 inherit-process-coding-system. */
7602 return inherit_process_coding_system ? Qt : Qnil;
7603 #endif
7606 /* Kill all processes associated with `buffer'.
7607 If `buffer' is nil, kill all processes. */
7609 void
7610 kill_buffer_processes (Lisp_Object buffer)
7612 #ifdef subprocesses
7613 Lisp_Object tail, proc;
7615 FOR_EACH_PROCESS (tail, proc)
7616 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7618 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7619 Fdelete_process (proc);
7620 else if (XPROCESS (proc)->infd >= 0)
7621 process_send_signal (proc, SIGHUP, Qnil, 1);
7623 #else /* subprocesses */
7624 /* Since we have no subprocesses, this does nothing. */
7625 #endif /* subprocesses */
7628 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7629 Swaiting_for_user_input_p, 0, 0, 0,
7630 doc: /* Return non-nil if Emacs is waiting for input from the user.
7631 This is intended for use by asynchronous process output filters and sentinels. */)
7632 (void)
7634 #ifdef subprocesses
7635 return (waiting_for_user_input_p ? Qt : Qnil);
7636 #else
7637 return Qnil;
7638 #endif
7641 /* Stop reading input from keyboard sources. */
7643 void
7644 hold_keyboard_input (void)
7646 kbd_is_on_hold = 1;
7649 /* Resume reading input from keyboard sources. */
7651 void
7652 unhold_keyboard_input (void)
7654 kbd_is_on_hold = 0;
7657 /* Return true if keyboard input is on hold, zero otherwise. */
7659 bool
7660 kbd_on_hold_p (void)
7662 return kbd_is_on_hold;
7666 /* Enumeration of and access to system processes a-la ps(1). */
7668 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7669 0, 0, 0,
7670 doc: /* Return a list of numerical process IDs of all running processes.
7671 If this functionality is unsupported, return nil.
7673 See `process-attributes' for getting attributes of a process given its ID. */)
7674 (void)
7676 return list_system_processes ();
7679 DEFUN ("process-attributes", Fprocess_attributes,
7680 Sprocess_attributes, 1, 1, 0,
7681 doc: /* Return attributes of the process given by its PID, a number.
7683 Value is an alist where each element is a cons cell of the form
7685 (KEY . VALUE)
7687 If this functionality is unsupported, the value is nil.
7689 See `list-system-processes' for getting a list of all process IDs.
7691 The KEYs of the attributes that this function may return are listed
7692 below, together with the type of the associated VALUE (in parentheses).
7693 Not all platforms support all of these attributes; unsupported
7694 attributes will not appear in the returned alist.
7695 Unless explicitly indicated otherwise, numbers can have either
7696 integer or floating point values.
7698 euid -- Effective user User ID of the process (number)
7699 user -- User name corresponding to euid (string)
7700 egid -- Effective user Group ID of the process (number)
7701 group -- Group name corresponding to egid (string)
7702 comm -- Command name (executable name only) (string)
7703 state -- Process state code, such as "S", "R", or "T" (string)
7704 ppid -- Parent process ID (number)
7705 pgrp -- Process group ID (number)
7706 sess -- Session ID, i.e. process ID of session leader (number)
7707 ttname -- Controlling tty name (string)
7708 tpgid -- ID of foreground process group on the process's tty (number)
7709 minflt -- number of minor page faults (number)
7710 majflt -- number of major page faults (number)
7711 cminflt -- cumulative number of minor page faults (number)
7712 cmajflt -- cumulative number of major page faults (number)
7713 utime -- user time used by the process, in (current-time) format,
7714 which is a list of integers (HIGH LOW USEC PSEC)
7715 stime -- system time used by the process (current-time)
7716 time -- sum of utime and stime (current-time)
7717 cutime -- user time used by the process and its children (current-time)
7718 cstime -- system time used by the process and its children (current-time)
7719 ctime -- sum of cutime and cstime (current-time)
7720 pri -- priority of the process (number)
7721 nice -- nice value of the process (number)
7722 thcount -- process thread count (number)
7723 start -- time the process started (current-time)
7724 vsize -- virtual memory size of the process in KB's (number)
7725 rss -- resident set size of the process in KB's (number)
7726 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7727 pcpu -- percents of CPU time used by the process (floating-point number)
7728 pmem -- percents of total physical memory used by process's resident set
7729 (floating-point number)
7730 args -- command line which invoked the process (string). */)
7731 ( Lisp_Object pid)
7733 return system_process_attributes (pid);
7736 #ifdef subprocesses
7737 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7738 Invoke this after init_process_emacs, and after glib and/or GNUstep
7739 futz with the SIGCHLD handler, but before Emacs forks any children.
7740 This function's caller should block SIGCHLD. */
7742 void
7743 catch_child_signal (void)
7745 struct sigaction action, old_action;
7746 sigset_t oldset;
7747 emacs_sigaction_init (&action, deliver_child_signal);
7748 block_child_signal (&oldset);
7749 sigaction (SIGCHLD, &action, &old_action);
7750 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7751 || ! (old_action.sa_flags & SA_SIGINFO));
7753 if (old_action.sa_handler != deliver_child_signal)
7754 lib_child_handler
7755 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7756 ? dummy_handler
7757 : old_action.sa_handler);
7758 unblock_child_signal (&oldset);
7760 #endif /* subprocesses */
7763 /* This is not called "init_process" because that is the name of a
7764 Mach system call, so it would cause problems on Darwin systems. */
7765 void
7766 init_process_emacs (int sockfd)
7768 #ifdef subprocesses
7769 int i;
7771 inhibit_sentinels = 0;
7773 #ifndef CANNOT_DUMP
7774 if (! noninteractive || initialized)
7775 #endif
7777 #if defined HAVE_GLIB && !defined WINDOWSNT
7778 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7779 this should always fail, but is enough to initialize glib's
7780 private SIGCHLD handler, allowing catch_child_signal to copy
7781 it into lib_child_handler. */
7782 g_source_unref (g_child_watch_source_new (getpid ()));
7783 #endif
7784 catch_child_signal ();
7787 FD_ZERO (&input_wait_mask);
7788 FD_ZERO (&non_keyboard_wait_mask);
7789 FD_ZERO (&non_process_wait_mask);
7790 FD_ZERO (&write_mask);
7791 max_process_desc = max_input_desc = -1;
7792 external_sock_fd = sockfd;
7793 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7795 FD_ZERO (&connect_wait_mask);
7796 num_pending_connects = 0;
7798 process_output_delay_count = 0;
7799 process_output_skip = 0;
7801 /* Don't do this, it caused infinite select loops. The display
7802 method should call add_keyboard_wait_descriptor on stdin if it
7803 needs that. */
7804 #if 0
7805 FD_SET (0, &input_wait_mask);
7806 #endif
7808 Vprocess_alist = Qnil;
7809 deleted_pid_list = Qnil;
7810 for (i = 0; i < FD_SETSIZE; i++)
7812 chan_process[i] = Qnil;
7813 proc_buffered_char[i] = -1;
7815 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7816 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7817 #ifdef DATAGRAM_SOCKETS
7818 memset (datagram_address, 0, sizeof datagram_address);
7819 #endif
7821 #if defined (DARWIN_OS)
7822 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7823 processes. As such, we only change the default value. */
7824 if (initialized)
7826 char const *release = (STRINGP (Voperating_system_release)
7827 ? SSDATA (Voperating_system_release)
7828 : 0);
7829 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7830 Vprocess_connection_type = Qnil;
7833 #endif
7834 #endif /* subprocesses */
7835 kbd_is_on_hold = 0;
7838 void
7839 syms_of_process (void)
7841 #ifdef subprocesses
7843 DEFSYM (Qprocessp, "processp");
7844 DEFSYM (Qrun, "run");
7845 DEFSYM (Qstop, "stop");
7846 DEFSYM (Qsignal, "signal");
7848 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7849 here again. */
7851 DEFSYM (Qopen, "open");
7852 DEFSYM (Qclosed, "closed");
7853 DEFSYM (Qconnect, "connect");
7854 DEFSYM (Qfailed, "failed");
7855 DEFSYM (Qlisten, "listen");
7856 DEFSYM (Qlocal, "local");
7857 DEFSYM (Qipv4, "ipv4");
7858 #ifdef AF_INET6
7859 DEFSYM (Qipv6, "ipv6");
7860 #endif
7861 DEFSYM (Qdatagram, "datagram");
7862 DEFSYM (Qseqpacket, "seqpacket");
7864 DEFSYM (QCport, ":port");
7865 DEFSYM (QCspeed, ":speed");
7866 DEFSYM (QCprocess, ":process");
7868 DEFSYM (QCbytesize, ":bytesize");
7869 DEFSYM (QCstopbits, ":stopbits");
7870 DEFSYM (QCparity, ":parity");
7871 DEFSYM (Qodd, "odd");
7872 DEFSYM (Qeven, "even");
7873 DEFSYM (QCflowcontrol, ":flowcontrol");
7874 DEFSYM (Qhw, "hw");
7875 DEFSYM (Qsw, "sw");
7876 DEFSYM (QCsummary, ":summary");
7878 DEFSYM (Qreal, "real");
7879 DEFSYM (Qnetwork, "network");
7880 DEFSYM (Qserial, "serial");
7881 DEFSYM (Qpipe, "pipe");
7882 DEFSYM (QCbuffer, ":buffer");
7883 DEFSYM (QChost, ":host");
7884 DEFSYM (QCservice, ":service");
7885 DEFSYM (QClocal, ":local");
7886 DEFSYM (QCremote, ":remote");
7887 DEFSYM (QCcoding, ":coding");
7888 DEFSYM (QCserver, ":server");
7889 DEFSYM (QCnowait, ":nowait");
7890 DEFSYM (QCsentinel, ":sentinel");
7891 DEFSYM (QCuse_external_socket, ":use-external-socket");
7892 DEFSYM (QCtls_parameters, ":tls-parameters");
7893 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
7894 DEFSYM (QClog, ":log");
7895 DEFSYM (QCnoquery, ":noquery");
7896 DEFSYM (QCstop, ":stop");
7897 DEFSYM (QCplist, ":plist");
7898 DEFSYM (QCcommand, ":command");
7899 DEFSYM (QCconnection_type, ":connection-type");
7900 DEFSYM (QCstderr, ":stderr");
7901 DEFSYM (Qpty, "pty");
7902 DEFSYM (Qpipe, "pipe");
7904 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7906 staticpro (&Vprocess_alist);
7907 staticpro (&deleted_pid_list);
7909 #endif /* subprocesses */
7911 DEFSYM (QCname, ":name");
7912 DEFSYM (QCtype, ":type");
7914 DEFSYM (Qeuid, "euid");
7915 DEFSYM (Qegid, "egid");
7916 DEFSYM (Quser, "user");
7917 DEFSYM (Qgroup, "group");
7918 DEFSYM (Qcomm, "comm");
7919 DEFSYM (Qstate, "state");
7920 DEFSYM (Qppid, "ppid");
7921 DEFSYM (Qpgrp, "pgrp");
7922 DEFSYM (Qsess, "sess");
7923 DEFSYM (Qttname, "ttname");
7924 DEFSYM (Qtpgid, "tpgid");
7925 DEFSYM (Qminflt, "minflt");
7926 DEFSYM (Qmajflt, "majflt");
7927 DEFSYM (Qcminflt, "cminflt");
7928 DEFSYM (Qcmajflt, "cmajflt");
7929 DEFSYM (Qutime, "utime");
7930 DEFSYM (Qstime, "stime");
7931 DEFSYM (Qtime, "time");
7932 DEFSYM (Qcutime, "cutime");
7933 DEFSYM (Qcstime, "cstime");
7934 DEFSYM (Qctime, "ctime");
7935 #ifdef subprocesses
7936 DEFSYM (Qinternal_default_process_sentinel,
7937 "internal-default-process-sentinel");
7938 DEFSYM (Qinternal_default_process_filter,
7939 "internal-default-process-filter");
7940 #endif
7941 DEFSYM (Qpri, "pri");
7942 DEFSYM (Qnice, "nice");
7943 DEFSYM (Qthcount, "thcount");
7944 DEFSYM (Qstart, "start");
7945 DEFSYM (Qvsize, "vsize");
7946 DEFSYM (Qrss, "rss");
7947 DEFSYM (Qetime, "etime");
7948 DEFSYM (Qpcpu, "pcpu");
7949 DEFSYM (Qpmem, "pmem");
7950 DEFSYM (Qargs, "args");
7952 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7953 doc: /* Non-nil means delete processes immediately when they exit.
7954 A value of nil means don't delete them until `list-processes' is run. */);
7956 delete_exited_processes = 1;
7958 #ifdef subprocesses
7959 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7960 doc: /* Control type of device used to communicate with subprocesses.
7961 Values are nil to use a pipe, or t or `pty' to use a pty.
7962 The value has no effect if the system has no ptys or if all ptys are busy:
7963 then a pipe is used in any case.
7964 The value takes effect when `start-process' is called. */);
7965 Vprocess_connection_type = Qt;
7967 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7968 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7969 On some systems, when Emacs reads the output from a subprocess, the output data
7970 is read in very small blocks, potentially resulting in very poor performance.
7971 This behavior can be remedied to some extent by setting this variable to a
7972 non-nil value, as it will automatically delay reading from such processes, to
7973 allow them to produce more output before Emacs tries to read it.
7974 If the value is t, the delay is reset after each write to the process; any other
7975 non-nil value means that the delay is not reset on write.
7976 The variable takes effect when `start-process' is called. */);
7977 Vprocess_adaptive_read_buffering = Qt;
7979 defsubr (&Sprocessp);
7980 defsubr (&Sget_process);
7981 defsubr (&Sdelete_process);
7982 defsubr (&Sprocess_status);
7983 defsubr (&Sprocess_exit_status);
7984 defsubr (&Sprocess_id);
7985 defsubr (&Sprocess_name);
7986 defsubr (&Sprocess_tty_name);
7987 defsubr (&Sprocess_command);
7988 defsubr (&Sset_process_buffer);
7989 defsubr (&Sprocess_buffer);
7990 defsubr (&Sprocess_mark);
7991 defsubr (&Sset_process_filter);
7992 defsubr (&Sprocess_filter);
7993 defsubr (&Sset_process_sentinel);
7994 defsubr (&Sprocess_sentinel);
7995 defsubr (&Sset_process_window_size);
7996 defsubr (&Sset_process_inherit_coding_system_flag);
7997 defsubr (&Sset_process_query_on_exit_flag);
7998 defsubr (&Sprocess_query_on_exit_flag);
7999 defsubr (&Sprocess_contact);
8000 defsubr (&Sprocess_plist);
8001 defsubr (&Sset_process_plist);
8002 defsubr (&Sprocess_list);
8003 defsubr (&Smake_process);
8004 defsubr (&Smake_pipe_process);
8005 defsubr (&Sserial_process_configure);
8006 defsubr (&Smake_serial_process);
8007 defsubr (&Sset_network_process_option);
8008 defsubr (&Smake_network_process);
8009 defsubr (&Sformat_network_address);
8010 defsubr (&Snetwork_interface_list);
8011 defsubr (&Snetwork_interface_info);
8012 #ifdef DATAGRAM_SOCKETS
8013 defsubr (&Sprocess_datagram_address);
8014 defsubr (&Sset_process_datagram_address);
8015 #endif
8016 defsubr (&Saccept_process_output);
8017 defsubr (&Sprocess_send_region);
8018 defsubr (&Sprocess_send_string);
8019 defsubr (&Sinterrupt_process);
8020 defsubr (&Skill_process);
8021 defsubr (&Squit_process);
8022 defsubr (&Sstop_process);
8023 defsubr (&Scontinue_process);
8024 defsubr (&Sprocess_running_child_p);
8025 defsubr (&Sprocess_send_eof);
8026 defsubr (&Ssignal_process);
8027 defsubr (&Swaiting_for_user_input_p);
8028 defsubr (&Sprocess_type);
8029 defsubr (&Sinternal_default_process_sentinel);
8030 defsubr (&Sinternal_default_process_filter);
8031 defsubr (&Sset_process_coding_system);
8032 defsubr (&Sprocess_coding_system);
8033 defsubr (&Sset_process_filter_multibyte);
8034 defsubr (&Sprocess_filter_multibyte_p);
8037 Lisp_Object subfeatures = Qnil;
8038 const struct socket_options *sopt;
8040 #define ADD_SUBFEATURE(key, val) \
8041 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8043 ADD_SUBFEATURE (QCnowait, Qt);
8044 #ifdef DATAGRAM_SOCKETS
8045 ADD_SUBFEATURE (QCtype, Qdatagram);
8046 #endif
8047 #ifdef HAVE_SEQPACKET
8048 ADD_SUBFEATURE (QCtype, Qseqpacket);
8049 #endif
8050 #ifdef HAVE_LOCAL_SOCKETS
8051 ADD_SUBFEATURE (QCfamily, Qlocal);
8052 #endif
8053 ADD_SUBFEATURE (QCfamily, Qipv4);
8054 #ifdef AF_INET6
8055 ADD_SUBFEATURE (QCfamily, Qipv6);
8056 #endif
8057 #ifdef HAVE_GETSOCKNAME
8058 ADD_SUBFEATURE (QCservice, Qt);
8059 #endif
8060 ADD_SUBFEATURE (QCserver, Qt);
8062 for (sopt = socket_options; sopt->name; sopt++)
8063 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8065 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8068 #endif /* subprocesses */
8070 defsubr (&Sget_buffer_process);
8071 defsubr (&Sprocess_inherit_coding_system_flag);
8072 defsubr (&Slist_system_processes);
8073 defsubr (&Sprocess_attributes);