; * lisp/ldefs-boot.el: Update.
[emacs.git] / src / process.c
blob2df51cfd9965c30bbdaad908069ff5b76985c90f
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2019 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <fcntl.h>
33 #include "lisp.h"
35 /* Only MS-DOS does not define `subprocesses'. */
36 #ifdef subprocesses
38 #include <sys/socket.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
43 #endif /* subprocesses */
45 #ifdef HAVE_SETRLIMIT
46 # include <sys/resource.h>
48 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
49 NOFILE_LIMIT is the initial limit on the number of open files,
50 which should be restored in child processes. */
51 static struct rlimit nofile_limit;
52 #endif
54 #ifdef subprocesses
56 /* Are local (unix) sockets supported? */
57 #if defined (HAVE_SYS_UN_H)
58 #if !defined (AF_LOCAL) && defined (AF_UNIX)
59 #define AF_LOCAL AF_UNIX
60 #endif
61 #ifdef AF_LOCAL
62 #define HAVE_LOCAL_SOCKETS
63 #include <sys/un.h>
64 #endif
65 #endif
67 #include <sys/ioctl.h>
68 #if defined (HAVE_NET_IF_H)
69 #include <net/if.h>
70 #endif /* HAVE_NET_IF_H */
72 #if defined (HAVE_IFADDRS_H)
73 /* Must be after net/if.h */
74 #include <ifaddrs.h>
76 /* We only use structs from this header when we use getifaddrs. */
77 #if defined (HAVE_NET_IF_DL_H)
78 #include <net/if_dl.h>
79 #endif
81 #endif
83 #ifdef NEED_BSDTTY
84 #include <bsdtty.h>
85 #endif
87 #ifdef USG5_4
88 # include <sys/stream.h>
89 # include <sys/stropts.h>
90 #endif
92 #ifdef HAVE_UTIL_H
93 #include <util.h>
94 #endif
96 #ifdef HAVE_PTY_H
97 #include <pty.h>
98 #endif
100 #include <c-ctype.h>
101 #include <flexmember.h>
102 #include <sig2str.h>
103 #include <verify.h>
105 #endif /* subprocesses */
107 #include "systime.h"
108 #include "systty.h"
110 #include "window.h"
111 #include "character.h"
112 #include "buffer.h"
113 #include "coding.h"
114 #include "process.h"
115 #include "frame.h"
116 #include "termopts.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "atimer.h"
120 #include "sysselect.h"
121 #include "syssignal.h"
122 #include "syswait.h"
123 #ifdef HAVE_GNUTLS
124 #include "gnutls.h"
125 #endif
127 #ifdef HAVE_WINDOW_SYSTEM
128 #include TERM_HEADER
129 #endif /* HAVE_WINDOW_SYSTEM */
131 #ifdef HAVE_GLIB
132 #include "xgselect.h"
133 #ifndef WINDOWSNT
134 #include <glib.h>
135 #endif
136 #endif
138 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
139 /* This is 0.1s in nanoseconds. */
140 #define ASYNC_RETRY_NSEC 100000000
141 #endif
143 #ifdef WINDOWSNT
144 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
145 const struct timespec *, const sigset_t *);
146 #endif
148 /* Work around GCC 4.3.0 bug with strict overflow checking; see
149 <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
150 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
151 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
152 # pragma GCC diagnostic ignored "-Wstrict-overflow"
153 #endif
155 /* True if keyboard input is on hold, zero otherwise. */
157 static bool kbd_is_on_hold;
159 /* Nonzero means don't run process sentinels. This is used
160 when exiting. */
161 bool inhibit_sentinels;
163 #ifdef subprocesses
165 #ifndef SOCK_CLOEXEC
166 # define SOCK_CLOEXEC 0
167 #endif
168 #ifndef SOCK_NONBLOCK
169 # define SOCK_NONBLOCK 0
170 #endif
172 /* True if ERRNUM represents an error where the system call would
173 block if a blocking variant were used. */
174 static bool
175 would_block (int errnum)
177 #ifdef EWOULDBLOCK
178 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
179 return true;
180 #endif
181 return errnum == EAGAIN;
184 #ifndef HAVE_ACCEPT4
186 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
188 static int
189 close_on_exec (int fd)
191 if (0 <= fd)
192 fcntl (fd, F_SETFD, FD_CLOEXEC);
193 return fd;
196 # undef accept4
197 # define accept4(sockfd, addr, addrlen, flags) \
198 process_accept4 (sockfd, addr, addrlen, flags)
199 static int
200 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
202 return close_on_exec (accept (sockfd, addr, addrlen));
205 static int
206 process_socket (int domain, int type, int protocol)
208 return close_on_exec (socket (domain, type, protocol));
210 # undef socket
211 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
212 #endif
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
218 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
219 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
221 /* Number of events of change of status of a process. */
222 static EMACS_INT process_tick;
223 /* Number of events for which the user or sentinel has been notified. */
224 static EMACS_INT update_tick;
226 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
227 this system. We need to read full packets, so we need a
228 "non-destructive" select. So we require either native select,
229 or emulation of select using FIONREAD. */
231 #ifndef BROKEN_DATAGRAM_SOCKETS
232 # if defined HAVE_SELECT || defined USABLE_FIONREAD
233 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
234 # define DATAGRAM_SOCKETS
235 # endif
236 # endif
237 #endif
239 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
240 # define HAVE_SEQPACKET
241 #endif
243 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
244 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
245 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
247 /* Number of processes which have a non-zero read_output_delay,
248 and therefore might be delayed for adaptive read buffering. */
250 static int process_output_delay_count;
252 /* True if any process has non-nil read_output_skip. */
254 static bool process_output_skip;
256 static void start_process_unwind (Lisp_Object);
257 static void create_process (Lisp_Object, char **, Lisp_Object);
258 #ifdef USABLE_SIGIO
259 static bool keyboard_bit_set (fd_set *);
260 #endif
261 static void deactivate_process (Lisp_Object);
262 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
263 static int read_process_output (Lisp_Object, int);
264 static void create_pty (Lisp_Object);
265 static void exec_sentinel (Lisp_Object, Lisp_Object);
267 /* Number of bits set in connect_wait_mask. */
268 static int num_pending_connects;
270 /* The largest descriptor currently in use; -1 if none. */
271 static int max_desc;
273 /* Set the external socket descriptor for Emacs to use when
274 `make-network-process' is called with a non-nil
275 `:use-external-socket' option. The value should be either -1, or
276 the file descriptor of a socket that is already bound. */
277 static int external_sock_fd;
279 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
280 static Lisp_Object chan_process[FD_SETSIZE];
281 static void wait_for_socket_fds (Lisp_Object, char const *);
283 /* Alist of elements (NAME . PROCESS). */
284 static Lisp_Object Vprocess_alist;
286 /* Buffered-ahead input char from process, indexed by channel.
287 -1 means empty (no char is buffered).
288 Used on sys V where the only way to tell if there is any
289 output from the process is to read at least one char.
290 Always -1 on systems that support FIONREAD. */
292 static int proc_buffered_char[FD_SETSIZE];
294 /* Table of `struct coding-system' for each process. */
295 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
296 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
298 #ifdef DATAGRAM_SOCKETS
299 /* Table of `partner address' for datagram sockets. */
300 static struct sockaddr_and_len {
301 struct sockaddr *sa;
302 ptrdiff_t len;
303 } datagram_address[FD_SETSIZE];
304 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
305 #define DATAGRAM_CONN_P(proc) \
306 (PROCESSP (proc) && \
307 XPROCESS (proc)->infd >= 0 && \
308 datagram_address[XPROCESS (proc)->infd].sa != 0)
309 #else
310 #define DATAGRAM_CONN_P(proc) (0)
311 #endif
313 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
314 a `for' loop which iterates over processes from Vprocess_alist. */
316 #define FOR_EACH_PROCESS(list_var, proc_var) \
317 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
319 /* These setters are used only in this file, so they can be private. */
320 static void
321 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
323 p->buffer = val;
325 static void
326 pset_command (struct Lisp_Process *p, Lisp_Object val)
328 p->command = val;
330 static void
331 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
333 p->decode_coding_system = val;
335 static void
336 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
338 p->decoding_buf = val;
340 static void
341 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
343 p->encode_coding_system = val;
345 static void
346 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
348 p->encoding_buf = val;
350 static void
351 pset_filter (struct Lisp_Process *p, Lisp_Object val)
353 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
355 static void
356 pset_log (struct Lisp_Process *p, Lisp_Object val)
358 p->log = val;
360 static void
361 pset_mark (struct Lisp_Process *p, Lisp_Object val)
363 p->mark = val;
365 static void
366 pset_thread (struct Lisp_Process *p, Lisp_Object val)
368 p->thread = val;
370 static void
371 pset_name (struct Lisp_Process *p, Lisp_Object val)
373 p->name = val;
375 static void
376 pset_plist (struct Lisp_Process *p, Lisp_Object val)
378 p->plist = val;
380 static void
381 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
383 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
385 static void
386 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
388 p->tty_name = val;
390 static void
391 pset_type (struct Lisp_Process *p, Lisp_Object val)
393 p->type = val;
395 static void
396 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
398 p->write_queue = val;
400 static void
401 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
403 p->stderrproc = val;
407 static Lisp_Object
408 make_lisp_proc (struct Lisp_Process *p)
410 return make_lisp_ptr (p, Lisp_Vectorlike);
413 enum fd_bits
415 /* Read from file descriptor. */
416 FOR_READ = 1,
417 /* Write to file descriptor. */
418 FOR_WRITE = 2,
419 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
420 set. */
421 KEYBOARD_FD = 4,
422 /* This descriptor refers to a process. */
423 PROCESS_FD = 8,
424 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
425 NON_BLOCKING_CONNECT_FD = 16
428 static struct fd_callback_data
430 fd_callback func;
431 void *data;
432 /* Flags from enum fd_bits. */
433 int flags;
434 /* If this fd is locked to a certain thread, this points to it.
435 Otherwise, this is NULL. If an fd is locked to a thread, then
436 only that thread is permitted to wait on it. */
437 struct thread_state *thread;
438 /* If this fd is currently being selected on by a thread, this
439 points to the thread. Otherwise it is NULL. */
440 struct thread_state *waiting_thread;
441 } fd_callback_info[FD_SETSIZE];
444 /* Add a file descriptor FD to be monitored for when read is possible.
445 When read is possible, call FUNC with argument DATA. */
447 void
448 add_read_fd (int fd, fd_callback func, void *data)
450 add_keyboard_wait_descriptor (fd);
452 fd_callback_info[fd].func = func;
453 fd_callback_info[fd].data = data;
456 static void
457 add_non_keyboard_read_fd (int fd)
459 eassert (fd >= 0 && fd < FD_SETSIZE);
460 eassert (fd_callback_info[fd].func == NULL);
462 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
463 fd_callback_info[fd].flags |= FOR_READ;
464 if (fd > max_desc)
465 max_desc = fd;
468 static void
469 add_process_read_fd (int fd)
471 add_non_keyboard_read_fd (fd);
472 fd_callback_info[fd].flags |= PROCESS_FD;
475 /* Stop monitoring file descriptor FD for when read is possible. */
477 void
478 delete_read_fd (int fd)
480 delete_keyboard_wait_descriptor (fd);
482 if (fd_callback_info[fd].flags == 0)
484 fd_callback_info[fd].func = 0;
485 fd_callback_info[fd].data = 0;
489 /* Add a file descriptor FD to be monitored for when write is possible.
490 When write is possible, call FUNC with argument DATA. */
492 void
493 add_write_fd (int fd, fd_callback func, void *data)
495 eassert (fd >= 0 && fd < FD_SETSIZE);
497 fd_callback_info[fd].func = func;
498 fd_callback_info[fd].data = data;
499 fd_callback_info[fd].flags |= FOR_WRITE;
500 if (fd > max_desc)
501 max_desc = fd;
504 static void
505 add_non_blocking_write_fd (int fd)
507 eassert (fd >= 0 && fd < FD_SETSIZE);
508 eassert (fd_callback_info[fd].func == NULL);
510 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
511 if (fd > max_desc)
512 max_desc = fd;
513 ++num_pending_connects;
516 static void
517 recompute_max_desc (void)
519 int fd;
521 for (fd = max_desc; fd >= 0; --fd)
523 if (fd_callback_info[fd].flags != 0)
525 max_desc = fd;
526 break;
531 /* Stop monitoring file descriptor FD for when write is possible. */
533 void
534 delete_write_fd (int fd)
536 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
538 if (--num_pending_connects < 0)
539 emacs_abort ();
541 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
542 if (fd_callback_info[fd].flags == 0)
544 fd_callback_info[fd].func = 0;
545 fd_callback_info[fd].data = 0;
547 if (fd == max_desc)
548 recompute_max_desc ();
552 static void
553 compute_input_wait_mask (fd_set *mask)
555 int fd;
557 FD_ZERO (mask);
558 for (fd = 0; fd <= max_desc; ++fd)
560 if (fd_callback_info[fd].thread != NULL
561 && fd_callback_info[fd].thread != current_thread)
562 continue;
563 if (fd_callback_info[fd].waiting_thread != NULL
564 && fd_callback_info[fd].waiting_thread != current_thread)
565 continue;
566 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
568 FD_SET (fd, mask);
569 fd_callback_info[fd].waiting_thread = current_thread;
574 static void
575 compute_non_process_wait_mask (fd_set *mask)
577 int fd;
579 FD_ZERO (mask);
580 for (fd = 0; fd <= max_desc; ++fd)
582 if (fd_callback_info[fd].thread != NULL
583 && fd_callback_info[fd].thread != current_thread)
584 continue;
585 if (fd_callback_info[fd].waiting_thread != NULL
586 && fd_callback_info[fd].waiting_thread != current_thread)
587 continue;
588 if ((fd_callback_info[fd].flags & FOR_READ) != 0
589 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
591 FD_SET (fd, mask);
592 fd_callback_info[fd].waiting_thread = current_thread;
597 static void
598 compute_non_keyboard_wait_mask (fd_set *mask)
600 int fd;
602 FD_ZERO (mask);
603 for (fd = 0; fd <= max_desc; ++fd)
605 if (fd_callback_info[fd].thread != NULL
606 && fd_callback_info[fd].thread != current_thread)
607 continue;
608 if (fd_callback_info[fd].waiting_thread != NULL
609 && fd_callback_info[fd].waiting_thread != current_thread)
610 continue;
611 if ((fd_callback_info[fd].flags & FOR_READ) != 0
612 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
614 FD_SET (fd, mask);
615 fd_callback_info[fd].waiting_thread = current_thread;
620 static void
621 compute_write_mask (fd_set *mask)
623 int fd;
625 FD_ZERO (mask);
626 for (fd = 0; fd <= max_desc; ++fd)
628 if (fd_callback_info[fd].thread != NULL
629 && fd_callback_info[fd].thread != current_thread)
630 continue;
631 if (fd_callback_info[fd].waiting_thread != NULL
632 && fd_callback_info[fd].waiting_thread != current_thread)
633 continue;
634 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
636 FD_SET (fd, mask);
637 fd_callback_info[fd].waiting_thread = current_thread;
642 static void
643 clear_waiting_thread_info (void)
645 int fd;
647 for (fd = 0; fd <= max_desc; ++fd)
649 if (fd_callback_info[fd].waiting_thread == current_thread)
650 fd_callback_info[fd].waiting_thread = NULL;
655 /* Compute the Lisp form of the process status, p->status, from
656 the numeric status that was returned by `wait'. */
658 static Lisp_Object status_convert (int);
660 static void
661 update_status (struct Lisp_Process *p)
663 eassert (p->raw_status_new);
664 pset_status (p, status_convert (p->raw_status));
665 p->raw_status_new = 0;
668 /* Convert a process status word in Unix format to
669 the list that we use internally. */
671 static Lisp_Object
672 status_convert (int w)
674 if (WIFSTOPPED (w))
675 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
676 else if (WIFEXITED (w))
677 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
678 WCOREDUMP (w) ? Qt : Qnil));
679 else if (WIFSIGNALED (w))
680 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
681 WCOREDUMP (w) ? Qt : Qnil));
682 else
683 return Qrun;
686 /* True if STATUS is that of a process attempting connection. */
688 static bool
689 connecting_status (Lisp_Object status)
691 return CONSP (status) && EQ (XCAR (status), Qconnect);
694 /* Given a status-list, extract the three pieces of information
695 and store them individually through the three pointers. */
697 static void
698 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
699 bool *coredump)
701 Lisp_Object tem;
703 if (connecting_status (l))
704 l = XCAR (l);
706 if (SYMBOLP (l))
708 *symbol = l;
709 *code = make_number (0);
710 *coredump = 0;
712 else
714 *symbol = XCAR (l);
715 tem = XCDR (l);
716 *code = XCAR (tem);
717 tem = XCDR (tem);
718 *coredump = !NILP (tem);
722 /* Return a string describing a process status list. */
724 static Lisp_Object
725 status_message (struct Lisp_Process *p)
727 Lisp_Object status = p->status;
728 Lisp_Object symbol, code;
729 bool coredump;
730 Lisp_Object string;
732 decode_status (status, &symbol, &code, &coredump);
734 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
736 char const *signame;
737 synchronize_system_messages_locale ();
738 signame = strsignal (XFASTINT (code));
739 if (signame == 0)
740 string = build_string ("unknown");
741 else
743 int c1, c2;
745 string = build_unibyte_string (signame);
746 if (! NILP (Vlocale_coding_system))
747 string = (code_convert_string_norecord
748 (string, Vlocale_coding_system, 0));
749 c1 = STRING_CHAR (SDATA (string));
750 c2 = downcase (c1);
751 if (c1 != c2)
752 Faset (string, make_number (0), make_number (c2));
754 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
755 return concat2 (string, suffix);
757 else if (EQ (symbol, Qexit))
759 if (NETCONN1_P (p))
760 return build_string (XFASTINT (code) == 0
761 ? "deleted\n"
762 : "connection broken by remote peer\n");
763 if (XFASTINT (code) == 0)
764 return build_string ("finished\n");
765 AUTO_STRING (prefix, "exited abnormally with code ");
766 string = Fnumber_to_string (code);
767 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
768 return concat3 (prefix, string, suffix);
770 else if (EQ (symbol, Qfailed))
772 AUTO_STRING (format, "failed with code %s\n");
773 return CALLN (Fformat, format, code);
775 else
776 return Fcopy_sequence (Fsymbol_name (symbol));
779 enum { PTY_NAME_SIZE = 24 };
781 /* Open an available pty, returning a file descriptor.
782 Store into PTY_NAME the file name of the terminal corresponding to the pty.
783 Return -1 on failure. */
785 static int
786 allocate_pty (char pty_name[PTY_NAME_SIZE])
788 #ifdef HAVE_PTYS
789 int fd;
791 #ifdef PTY_ITERATION
792 PTY_ITERATION
793 #else
794 register int c, i;
795 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
796 for (i = 0; i < 16; i++)
797 #endif
799 #ifdef PTY_NAME_SPRINTF
800 PTY_NAME_SPRINTF
801 #else
802 sprintf (pty_name, "/dev/pty%c%x", c, i);
803 #endif /* no PTY_NAME_SPRINTF */
805 #ifdef PTY_OPEN
806 PTY_OPEN;
807 #else /* no PTY_OPEN */
808 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
809 #endif /* no PTY_OPEN */
811 if (fd >= 0)
813 #ifdef PTY_TTY_NAME_SPRINTF
814 PTY_TTY_NAME_SPRINTF
815 #else
816 sprintf (pty_name, "/dev/tty%c%x", c, i);
817 #endif /* no PTY_TTY_NAME_SPRINTF */
819 /* Set FD's close-on-exec flag. This is needed even if
820 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
821 doesn't require support for that combination.
822 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
823 doesn't work if the close-on-exec flag is set (Bug#20555).
824 Multithreaded platforms where posix_openpt ignores
825 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
826 have a race condition between the PTY_OPEN and here. */
827 fcntl (fd, F_SETFD, FD_CLOEXEC);
829 /* Check to make certain that both sides are available.
830 This avoids a nasty yet stupid bug in rlogins. */
831 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
833 emacs_close (fd);
834 continue;
836 setup_pty (fd);
837 return fd;
840 #endif /* HAVE_PTYS */
841 return -1;
844 /* Allocate basically initialized process. */
846 static struct Lisp_Process *
847 allocate_process (void)
849 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
852 static Lisp_Object
853 make_process (Lisp_Object name)
855 struct Lisp_Process *p = allocate_process ();
856 /* Initialize Lisp data. Note that allocate_process initializes all
857 Lisp data to nil, so do it only for slots which should not be nil. */
858 pset_status (p, Qrun);
859 pset_mark (p, Fmake_marker ());
860 pset_thread (p, Fcurrent_thread ());
862 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
863 non-Lisp data, so do it only for slots which should not be zero. */
864 p->infd = -1;
865 p->outfd = -1;
866 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
867 p->open_fd[i] = -1;
869 #ifdef HAVE_GNUTLS
870 verify (GNUTLS_STAGE_EMPTY == 0);
871 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
872 eassert (NILP (p->gnutls_boot_parameters));
873 #endif
875 /* If name is already in use, modify it until it is unused. */
877 Lisp_Object name1 = name;
878 for (printmax_t i = 1; ; i++)
880 Lisp_Object tem = Fget_process (name1);
881 if (NILP (tem))
882 break;
883 char const suffix_fmt[] = "<%"pMd">";
884 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
885 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
886 name1 = concat2 (name, lsuffix);
888 name = name1;
889 pset_name (p, name);
890 pset_sentinel (p, Qinternal_default_process_sentinel);
891 pset_filter (p, Qinternal_default_process_filter);
892 Lisp_Object val;
893 XSETPROCESS (val, p);
894 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
895 return val;
898 static void
899 remove_process (register Lisp_Object proc)
901 register Lisp_Object pair;
903 pair = Frassq (proc, Vprocess_alist);
904 Vprocess_alist = Fdelq (pair, Vprocess_alist);
906 deactivate_process (proc);
909 void
910 update_processes_for_thread_death (Lisp_Object dying_thread)
912 Lisp_Object pair;
914 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
916 Lisp_Object process = XCDR (XCAR (pair));
917 if (EQ (XPROCESS (process)->thread, dying_thread))
919 struct Lisp_Process *proc = XPROCESS (process);
921 pset_thread (proc, Qnil);
922 if (proc->infd >= 0)
923 fd_callback_info[proc->infd].thread = NULL;
924 if (proc->outfd >= 0)
925 fd_callback_info[proc->outfd].thread = NULL;
930 #ifdef HAVE_GETADDRINFO_A
931 static void
932 free_dns_request (Lisp_Object proc)
934 struct Lisp_Process *p = XPROCESS (proc);
936 if (p->dns_request->ar_result)
937 freeaddrinfo (p->dns_request->ar_result);
938 xfree (p->dns_request);
939 p->dns_request = NULL;
941 #endif
944 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
945 doc: /* Return t if OBJECT is a process. */)
946 (Lisp_Object object)
948 return PROCESSP (object) ? Qt : Qnil;
951 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
952 doc: /* Return the process named NAME, or nil if there is none. */)
953 (register Lisp_Object name)
955 if (PROCESSP (name))
956 return name;
957 CHECK_STRING (name);
958 return Fcdr (Fassoc (name, Vprocess_alist, Qnil));
961 /* This is how commands for the user decode process arguments. It
962 accepts a process, a process name, a buffer, a buffer name, or nil.
963 Buffers denote the first process in the buffer, and nil denotes the
964 current buffer. */
966 static Lisp_Object
967 get_process (register Lisp_Object name)
969 register Lisp_Object proc, obj;
970 if (STRINGP (name))
972 obj = Fget_process (name);
973 if (NILP (obj))
974 obj = Fget_buffer (name);
975 if (NILP (obj))
976 error ("Process %s does not exist", SDATA (name));
978 else if (NILP (name))
979 obj = Fcurrent_buffer ();
980 else
981 obj = name;
983 /* Now obj should be either a buffer object or a process object. */
984 if (BUFFERP (obj))
986 if (NILP (BVAR (XBUFFER (obj), name)))
987 error ("Attempt to get process for a dead buffer");
988 proc = Fget_buffer_process (obj);
989 if (NILP (proc))
990 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
992 else
994 CHECK_PROCESS (obj);
995 proc = obj;
997 return proc;
1001 /* Fdelete_process promises to immediately forget about the process, but in
1002 reality, Emacs needs to remember those processes until they have been
1003 treated by the SIGCHLD handler and waitpid has been invoked on them;
1004 otherwise they might fill up the kernel's process table.
1006 Some processes created by call-process are also put onto this list.
1008 Members of this list are (process-ID . filename) pairs. The
1009 process-ID is a number; the filename, if a string, is a file that
1010 needs to be removed after the process exits. */
1011 static Lisp_Object deleted_pid_list;
1013 void
1014 record_deleted_pid (pid_t pid, Lisp_Object filename)
1016 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1017 /* GC treated elements set to nil. */
1018 Fdelq (Qnil, deleted_pid_list));
1022 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1023 doc: /* Delete PROCESS: kill it and forget about it immediately.
1024 PROCESS may be a process, a buffer, the name of a process or buffer, or
1025 nil, indicating the current buffer's process. */)
1026 (register Lisp_Object process)
1028 register struct Lisp_Process *p;
1030 process = get_process (process);
1031 p = XPROCESS (process);
1033 #ifdef HAVE_GETADDRINFO_A
1034 if (p->dns_request)
1036 /* Cancel the request. Unless shutting down, wait until
1037 completion. Free the request if completely canceled. */
1039 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
1040 if (!canceled && !inhibit_sentinels)
1042 struct gaicb const *req = p->dns_request;
1043 while (gai_suspend (&req, 1, NULL) != 0)
1044 continue;
1045 canceled = true;
1047 if (canceled)
1048 free_dns_request (process);
1050 #endif
1052 p->raw_status_new = 0;
1053 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1055 pset_status (p, list2 (Qexit, make_number (0)));
1056 p->tick = ++process_tick;
1057 status_notify (p, NULL);
1058 redisplay_preserve_echo_area (13);
1060 else
1062 if (p->alive)
1063 record_kill_process (p, Qnil);
1065 if (p->infd >= 0)
1067 /* Update P's status, since record_kill_process will make the
1068 SIGCHLD handler update deleted_pid_list, not *P. */
1069 Lisp_Object symbol;
1070 if (p->raw_status_new)
1071 update_status (p);
1072 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1073 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1074 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1076 p->tick = ++process_tick;
1077 status_notify (p, NULL);
1078 redisplay_preserve_echo_area (13);
1081 remove_process (process);
1082 return Qnil;
1085 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1086 doc: /* Return the status of PROCESS.
1087 The returned value is one of the following symbols:
1088 run -- for a process that is running.
1089 stop -- for a process stopped but continuable.
1090 exit -- for a process that has exited.
1091 signal -- for a process that has got a fatal signal.
1092 open -- for a network stream connection that is open.
1093 listen -- for a network stream server that is listening.
1094 closed -- for a network stream connection that is closed.
1095 connect -- when waiting for a non-blocking connection to complete.
1096 failed -- when a non-blocking connection has failed.
1097 nil -- if arg is a process name and no such process exists.
1098 PROCESS may be a process, a buffer, the name of a process, or
1099 nil, indicating the current buffer's process. */)
1100 (register Lisp_Object process)
1102 register struct Lisp_Process *p;
1103 register Lisp_Object status;
1105 if (STRINGP (process))
1106 process = Fget_process (process);
1107 else
1108 process = get_process (process);
1110 if (NILP (process))
1111 return process;
1113 p = XPROCESS (process);
1114 if (p->raw_status_new)
1115 update_status (p);
1116 status = p->status;
1117 if (CONSP (status))
1118 status = XCAR (status);
1119 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1121 if (EQ (status, Qexit))
1122 status = Qclosed;
1123 else if (EQ (p->command, Qt))
1124 status = Qstop;
1125 else if (EQ (status, Qrun))
1126 status = Qopen;
1128 return status;
1131 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1132 1, 1, 0,
1133 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1134 If PROCESS has not yet exited or died, return 0. */)
1135 (register Lisp_Object process)
1137 CHECK_PROCESS (process);
1138 if (XPROCESS (process)->raw_status_new)
1139 update_status (XPROCESS (process));
1140 if (CONSP (XPROCESS (process)->status))
1141 return XCAR (XCDR (XPROCESS (process)->status));
1142 return make_number (0);
1145 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1146 doc: /* Return the process id of PROCESS.
1147 This is the pid of the external process which PROCESS uses or talks to.
1148 For a network, serial, and pipe connections, this value is nil. */)
1149 (register Lisp_Object process)
1151 pid_t pid;
1153 CHECK_PROCESS (process);
1154 pid = XPROCESS (process)->pid;
1155 return (pid ? make_fixnum_or_float (pid) : Qnil);
1158 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1159 doc: /* Return the name of PROCESS, as a string.
1160 This is the name of the program invoked in PROCESS,
1161 possibly modified to make it unique among process names. */)
1162 (register Lisp_Object process)
1164 CHECK_PROCESS (process);
1165 return XPROCESS (process)->name;
1168 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1169 doc: /* Return the command that was executed to start PROCESS.
1170 This is a list of strings, the first string being the program executed
1171 and the rest of the strings being the arguments given to it.
1172 For a network or serial or pipe connection, this is nil (process is running)
1173 or t (process is stopped). */)
1174 (register Lisp_Object process)
1176 CHECK_PROCESS (process);
1177 return XPROCESS (process)->command;
1180 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1181 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1182 This is the terminal that the process itself reads and writes on,
1183 not the name of the pty that Emacs uses to talk with that terminal. */)
1184 (register Lisp_Object process)
1186 CHECK_PROCESS (process);
1187 return XPROCESS (process)->tty_name;
1190 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1191 2, 2, 0,
1192 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1193 Return BUFFER. */)
1194 (register Lisp_Object process, Lisp_Object buffer)
1196 struct Lisp_Process *p;
1198 CHECK_PROCESS (process);
1199 if (!NILP (buffer))
1200 CHECK_BUFFER (buffer);
1201 p = XPROCESS (process);
1202 pset_buffer (p, buffer);
1203 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1204 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1205 setup_process_coding_systems (process);
1206 return buffer;
1209 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1210 1, 1, 0,
1211 doc: /* Return the buffer PROCESS is associated with.
1212 The default process filter inserts output from PROCESS into this buffer. */)
1213 (register Lisp_Object process)
1215 CHECK_PROCESS (process);
1216 return XPROCESS (process)->buffer;
1219 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1220 1, 1, 0,
1221 doc: /* Return the marker for the end of the last output from PROCESS. */)
1222 (register Lisp_Object process)
1224 CHECK_PROCESS (process);
1225 return XPROCESS (process)->mark;
1228 static void
1229 set_process_filter_masks (struct Lisp_Process *p)
1231 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1232 delete_read_fd (p->infd);
1233 else if (EQ (p->filter, Qt)
1234 /* Network or serial process not stopped: */
1235 && !EQ (p->command, Qt))
1236 add_process_read_fd (p->infd);
1239 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1240 2, 2, 0,
1241 doc: /* Give PROCESS the filter function FILTER; nil means default.
1242 A value of t means stop accepting output from the process.
1244 When a process has a non-default filter, its buffer is not used for output.
1245 Instead, each time it does output, the entire string of output is
1246 passed to the filter.
1248 The filter gets two arguments: the process and the string of output.
1249 The string argument is normally a multibyte string, except:
1250 - if the process's input coding system is no-conversion or raw-text,
1251 it is a unibyte string (the non-converted input), or else
1252 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1253 string (the result of converting the decoded input multibyte
1254 string to unibyte with `string-make-unibyte'). */)
1255 (Lisp_Object process, Lisp_Object filter)
1257 CHECK_PROCESS (process);
1258 struct Lisp_Process *p = XPROCESS (process);
1260 /* Don't signal an error if the process's input file descriptor
1261 is closed. This could make debugging Lisp more difficult,
1262 for example when doing something like
1264 (setq process (start-process ...))
1265 (debug)
1266 (set-process-filter process ...) */
1268 if (NILP (filter))
1269 filter = Qinternal_default_process_filter;
1271 pset_filter (p, filter);
1273 if (p->infd >= 0)
1274 set_process_filter_masks (p);
1276 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1277 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1278 setup_process_coding_systems (process);
1279 return filter;
1282 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1283 1, 1, 0,
1284 doc: /* Return the filter function of PROCESS.
1285 See `set-process-filter' for more info on filter functions. */)
1286 (register Lisp_Object process)
1288 CHECK_PROCESS (process);
1289 return XPROCESS (process)->filter;
1292 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1293 2, 2, 0,
1294 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1295 The sentinel is called as a function when the process changes state.
1296 It gets two arguments: the process, and a string describing the change. */)
1297 (register Lisp_Object process, Lisp_Object sentinel)
1299 struct Lisp_Process *p;
1301 CHECK_PROCESS (process);
1302 p = XPROCESS (process);
1304 if (NILP (sentinel))
1305 sentinel = Qinternal_default_process_sentinel;
1307 pset_sentinel (p, sentinel);
1308 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1309 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1310 return sentinel;
1313 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1314 1, 1, 0,
1315 doc: /* Return the sentinel of PROCESS.
1316 See `set-process-sentinel' for more info on sentinels. */)
1317 (register Lisp_Object process)
1319 CHECK_PROCESS (process);
1320 return XPROCESS (process)->sentinel;
1323 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1324 2, 2, 0,
1325 doc: /* Set the locking thread of PROCESS to be THREAD.
1326 If THREAD is nil, the process is unlocked. */)
1327 (Lisp_Object process, Lisp_Object thread)
1329 struct Lisp_Process *proc;
1330 struct thread_state *tstate;
1332 CHECK_PROCESS (process);
1333 if (NILP (thread))
1334 tstate = NULL;
1335 else
1337 CHECK_THREAD (thread);
1338 tstate = XTHREAD (thread);
1341 proc = XPROCESS (process);
1342 pset_thread (proc, thread);
1343 if (proc->infd >= 0)
1344 fd_callback_info[proc->infd].thread = tstate;
1345 if (proc->outfd >= 0)
1346 fd_callback_info[proc->outfd].thread = tstate;
1348 return thread;
1351 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1352 1, 1, 0,
1353 doc: /* Return the locking thread of PROCESS.
1354 If PROCESS is unlocked, this function returns nil. */)
1355 (Lisp_Object process)
1357 CHECK_PROCESS (process);
1358 return XPROCESS (process)->thread;
1361 DEFUN ("set-process-window-size", Fset_process_window_size,
1362 Sset_process_window_size, 3, 3, 0,
1363 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1364 Value is t if PROCESS was successfully told about the window size,
1365 nil otherwise. */)
1366 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1368 CHECK_PROCESS (process);
1370 /* All known platforms store window sizes as 'unsigned short'. */
1371 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1372 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1374 if (NETCONN_P (process)
1375 || XPROCESS (process)->infd < 0
1376 || (set_window_size (XPROCESS (process)->infd,
1377 XINT (height), XINT (width))
1378 < 0))
1379 return Qnil;
1380 else
1381 return Qt;
1384 DEFUN ("set-process-inherit-coding-system-flag",
1385 Fset_process_inherit_coding_system_flag,
1386 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1387 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1388 If the second argument FLAG is non-nil, then the variable
1389 `buffer-file-coding-system' of the buffer associated with PROCESS
1390 will be bound to the value of the coding system used to decode
1391 the process output.
1393 This is useful when the coding system specified for the process buffer
1394 leaves either the character code conversion or the end-of-line conversion
1395 unspecified, or if the coding system used to decode the process output
1396 is more appropriate for saving the process buffer.
1398 Binding the variable `inherit-process-coding-system' to non-nil before
1399 starting the process is an alternative way of setting the inherit flag
1400 for the process which will run.
1402 This function returns FLAG. */)
1403 (register Lisp_Object process, Lisp_Object flag)
1405 CHECK_PROCESS (process);
1406 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1407 return flag;
1410 DEFUN ("set-process-query-on-exit-flag",
1411 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1412 2, 2, 0,
1413 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1414 If the second argument FLAG is non-nil, Emacs will query the user before
1415 exiting or killing a buffer if PROCESS is running. This function
1416 returns FLAG. */)
1417 (register Lisp_Object process, Lisp_Object flag)
1419 CHECK_PROCESS (process);
1420 XPROCESS (process)->kill_without_query = NILP (flag);
1421 return flag;
1424 DEFUN ("process-query-on-exit-flag",
1425 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1426 1, 1, 0,
1427 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1428 (register Lisp_Object process)
1430 CHECK_PROCESS (process);
1431 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1434 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1435 1, 2, 0,
1436 doc: /* Return the contact info of PROCESS; t for a real child.
1437 For a network or serial or pipe connection, the value depends on the
1438 optional KEY arg. If KEY is nil, value is a cons cell of the form
1439 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1440 connection; it is t for a pipe connection. If KEY is t, the complete
1441 contact information for the connection is returned, else the specific
1442 value for the keyword KEY is returned. See `make-network-process',
1443 `make-serial-process', or `make-pipe-process' for the list of keywords.
1444 If PROCESS is a non-blocking network process that hasn't been fully
1445 set up yet, this function will block until socket setup has completed. */)
1446 (Lisp_Object process, Lisp_Object key)
1448 Lisp_Object contact;
1450 CHECK_PROCESS (process);
1451 contact = XPROCESS (process)->childp;
1453 #ifdef DATAGRAM_SOCKETS
1455 if (NETCONN_P (process))
1456 wait_for_socket_fds (process, "process-contact");
1458 if (DATAGRAM_CONN_P (process)
1459 && (EQ (key, Qt) || EQ (key, QCremote)))
1460 contact = Fplist_put (contact, QCremote,
1461 Fprocess_datagram_address (process));
1462 #endif
1464 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1465 || EQ (key, Qt))
1466 return contact;
1467 if (NILP (key) && NETCONN_P (process))
1468 return list2 (Fplist_get (contact, QChost),
1469 Fplist_get (contact, QCservice));
1470 if (NILP (key) && SERIALCONN_P (process))
1471 return list2 (Fplist_get (contact, QCport),
1472 Fplist_get (contact, QCspeed));
1473 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1474 if the pipe process is useful for purposes other than receiving
1475 stderr. */
1476 if (NILP (key) && PIPECONN_P (process))
1477 return Qt;
1478 return Fplist_get (contact, key);
1481 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1482 1, 1, 0,
1483 doc: /* Return the plist of PROCESS. */)
1484 (register Lisp_Object process)
1486 CHECK_PROCESS (process);
1487 return XPROCESS (process)->plist;
1490 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1491 2, 2, 0,
1492 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1493 (Lisp_Object process, Lisp_Object plist)
1495 CHECK_PROCESS (process);
1496 CHECK_LIST (plist);
1498 pset_plist (XPROCESS (process), plist);
1499 return plist;
1502 #if 0 /* Turned off because we don't currently record this info
1503 in the process. Perhaps add it. */
1504 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1505 doc: /* Return the connection type of PROCESS.
1506 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1507 a socket connection. */)
1508 (Lisp_Object process)
1510 return XPROCESS (process)->type;
1512 #endif
1514 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1515 doc: /* Return the connection type of PROCESS.
1516 The value is either the symbol `real', `network', `serial', or `pipe'.
1517 PROCESS may be a process, a buffer, the name of a process or buffer, or
1518 nil, indicating the current buffer's process. */)
1519 (Lisp_Object process)
1521 Lisp_Object proc;
1522 proc = get_process (process);
1523 return XPROCESS (proc)->type;
1526 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1527 1, 2, 0,
1528 doc: /* Convert network ADDRESS from internal format to a string.
1529 A 4 or 5 element vector represents an IPv4 address (with port number).
1530 An 8 or 9 element vector represents an IPv6 address (with port number).
1531 If optional second argument OMIT-PORT is non-nil, don't include a port
1532 number in the string, even when present in ADDRESS.
1533 Return nil if format of ADDRESS is invalid. */)
1534 (Lisp_Object address, Lisp_Object omit_port)
1536 if (NILP (address))
1537 return Qnil;
1539 if (STRINGP (address)) /* AF_LOCAL */
1540 return address;
1542 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1544 register struct Lisp_Vector *p = XVECTOR (address);
1545 ptrdiff_t size = p->header.size;
1546 Lisp_Object args[10];
1547 int nargs, i;
1548 char const *format;
1550 if (size == 4 || (size == 5 && !NILP (omit_port)))
1552 format = "%d.%d.%d.%d";
1553 nargs = 4;
1555 else if (size == 5)
1557 format = "%d.%d.%d.%d:%d";
1558 nargs = 5;
1560 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1562 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1563 nargs = 8;
1565 else if (size == 9)
1567 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1568 nargs = 9;
1570 else
1571 return Qnil;
1573 AUTO_STRING (format_obj, format);
1574 args[0] = format_obj;
1576 for (i = 0; i < nargs; i++)
1578 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1579 return Qnil;
1581 if (nargs <= 5 /* IPv4 */
1582 && i < 4 /* host, not port */
1583 && XINT (p->contents[i]) > 255)
1584 return Qnil;
1586 args[i + 1] = p->contents[i];
1589 return Fformat (nargs + 1, args);
1592 if (CONSP (address))
1594 AUTO_STRING (format, "<Family %d>");
1595 return CALLN (Fformat, format, Fcar (address));
1598 return Qnil;
1601 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1602 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1603 (void)
1605 return Fmapcar (Qcdr, Vprocess_alist);
1608 /* Starting asynchronous inferior processes. */
1610 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1611 doc: /* Start a program in a subprocess. Return the process object for it.
1613 This is similar to `start-process', but arguments are specified as
1614 keyword/argument pairs. The following arguments are defined:
1616 :name NAME -- NAME is name for process. It is modified if necessary
1617 to make it unique.
1619 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1620 with the process. Process output goes at end of that buffer, unless
1621 you specify a filter function to handle the output. BUFFER may be
1622 also nil, meaning that this process is not associated with any buffer.
1624 :command COMMAND -- COMMAND is a list starting with the program file
1625 name, followed by strings to give to the program as arguments.
1627 :coding CODING -- If CODING is a symbol, it specifies the coding
1628 system used for both reading and writing for this process. If CODING
1629 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1630 ENCODING is used for writing.
1632 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1633 the process is running. If BOOL is not given, query before exiting.
1635 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1636 In the stopped state, a process does not accept incoming data, but you
1637 can send outgoing data. The stopped state is cleared by
1638 `continue-process' and set by `stop-process'.
1640 :connection-type TYPE -- TYPE is control type of device used to
1641 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1642 to use a pty, or nil to use the default specified through
1643 `process-connection-type'.
1645 :filter FILTER -- Install FILTER as the process filter.
1647 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1649 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1650 to the standard error of subprocess. Specifying this implies
1651 `:connection-type' is set to `pipe'.
1653 usage: (make-process &rest ARGS) */)
1654 (ptrdiff_t nargs, Lisp_Object *args)
1656 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1657 Lisp_Object xstderr, stderrproc;
1658 ptrdiff_t count = SPECPDL_INDEX ();
1660 if (nargs == 0)
1661 return Qnil;
1663 /* Save arguments for process-contact and clone-process. */
1664 contact = Flist (nargs, args);
1666 buffer = Fplist_get (contact, QCbuffer);
1667 if (!NILP (buffer))
1668 buffer = Fget_buffer_create (buffer);
1670 /* Make sure that the child will be able to chdir to the current
1671 buffer's current directory, or its unhandled equivalent. We
1672 can't just have the child check for an error when it does the
1673 chdir, since it's in a vfork. */
1674 current_dir = encode_current_directory ();
1676 name = Fplist_get (contact, QCname);
1677 CHECK_STRING (name);
1679 command = Fplist_get (contact, QCcommand);
1680 if (CONSP (command))
1681 program = XCAR (command);
1682 else
1683 program = Qnil;
1685 if (!NILP (program))
1686 CHECK_STRING (program);
1688 bool query_on_exit = NILP (Fplist_get (contact, QCnoquery));
1690 stderrproc = Qnil;
1691 xstderr = Fplist_get (contact, QCstderr);
1692 if (PROCESSP (xstderr))
1694 if (!PIPECONN_P (xstderr))
1695 error ("Process is not a pipe process");
1696 stderrproc = xstderr;
1698 else if (!NILP (xstderr))
1700 CHECK_STRING (program);
1701 stderrproc = CALLN (Fmake_pipe_process,
1702 QCname,
1703 concat2 (name, build_string (" stderr")),
1704 QCbuffer,
1705 Fget_buffer_create (xstderr),
1706 QCnoquery,
1707 query_on_exit ? Qnil : Qt);
1710 proc = make_process (name);
1711 record_unwind_protect (start_process_unwind, proc);
1713 pset_childp (XPROCESS (proc), Qt);
1714 eassert (NILP (XPROCESS (proc)->plist));
1715 pset_type (XPROCESS (proc), Qreal);
1716 pset_buffer (XPROCESS (proc), buffer);
1717 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1718 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1719 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1721 if (!query_on_exit)
1722 XPROCESS (proc)->kill_without_query = 1;
1723 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1724 pset_command (XPROCESS (proc), Qt);
1726 tem = Fplist_get (contact, QCconnection_type);
1727 if (EQ (tem, Qpty))
1728 XPROCESS (proc)->pty_flag = true;
1729 else if (EQ (tem, Qpipe))
1730 XPROCESS (proc)->pty_flag = false;
1731 else if (NILP (tem))
1732 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1733 else
1734 report_file_error ("Unknown connection type", tem);
1736 if (!NILP (stderrproc))
1738 pset_stderrproc (XPROCESS (proc), stderrproc);
1740 XPROCESS (proc)->pty_flag = false;
1743 #ifdef HAVE_GNUTLS
1744 /* AKA GNUTLS_INITSTAGE(proc). */
1745 verify (GNUTLS_STAGE_EMPTY == 0);
1746 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1747 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1748 #endif
1750 XPROCESS (proc)->adaptive_read_buffering
1751 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1752 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1754 /* Make the process marker point into the process buffer (if any). */
1755 if (BUFFERP (buffer))
1756 set_marker_both (XPROCESS (proc)->mark, buffer,
1757 BUF_ZV (XBUFFER (buffer)),
1758 BUF_ZV_BYTE (XBUFFER (buffer)));
1760 USE_SAFE_ALLOCA;
1763 /* Decide coding systems for communicating with the process. Here
1764 we don't setup the structure coding_system nor pay attention to
1765 unibyte mode. They are done in create_process. */
1767 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1768 Lisp_Object coding_systems = Qt;
1769 Lisp_Object val, *args2;
1771 tem = Fplist_get (contact, QCcoding);
1772 if (!NILP (tem))
1774 val = tem;
1775 if (CONSP (val))
1776 val = XCAR (val);
1778 else
1779 val = Vcoding_system_for_read;
1780 if (NILP (val))
1782 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1783 Lisp_Object tem2;
1784 SAFE_ALLOCA_LISP (args2, nargs2);
1785 ptrdiff_t i = 0;
1786 args2[i++] = Qstart_process;
1787 args2[i++] = name;
1788 args2[i++] = buffer;
1789 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1790 args2[i++] = XCAR (tem2);
1791 if (!NILP (program))
1792 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1793 if (CONSP (coding_systems))
1794 val = XCAR (coding_systems);
1795 else if (CONSP (Vdefault_process_coding_system))
1796 val = XCAR (Vdefault_process_coding_system);
1798 pset_decode_coding_system (XPROCESS (proc), val);
1800 if (!NILP (tem))
1802 val = tem;
1803 if (CONSP (val))
1804 val = XCDR (val);
1806 else
1807 val = Vcoding_system_for_write;
1808 if (NILP (val))
1810 if (EQ (coding_systems, Qt))
1812 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1813 Lisp_Object tem2;
1814 SAFE_ALLOCA_LISP (args2, nargs2);
1815 ptrdiff_t i = 0;
1816 args2[i++] = Qstart_process;
1817 args2[i++] = name;
1818 args2[i++] = buffer;
1819 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1820 args2[i++] = XCAR (tem2);
1821 if (!NILP (program))
1822 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1824 if (CONSP (coding_systems))
1825 val = XCDR (coding_systems);
1826 else if (CONSP (Vdefault_process_coding_system))
1827 val = XCDR (Vdefault_process_coding_system);
1829 pset_encode_coding_system (XPROCESS (proc), val);
1830 /* Note: At this moment, the above coding system may leave
1831 text-conversion or eol-conversion unspecified. They will be
1832 decided after we read output from the process and decode it by
1833 some coding system, or just before we actually send a text to
1834 the process. */
1838 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1839 eassert (XPROCESS (proc)->decoding_carryover == 0);
1840 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1842 XPROCESS (proc)->inherit_coding_system_flag
1843 = !(NILP (buffer) || !inherit_process_coding_system);
1845 if (!NILP (program))
1847 Lisp_Object program_args = XCDR (command);
1849 /* If program file name is not absolute, search our path for it.
1850 Put the name we will really use in TEM. */
1851 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1852 && !(SCHARS (program) > 1
1853 && IS_DEVICE_SEP (SREF (program, 1))))
1855 tem = Qnil;
1856 openp (Vexec_path, program, Vexec_suffixes, &tem,
1857 make_number (X_OK), false);
1858 if (NILP (tem))
1859 report_file_error ("Searching for program", program);
1860 tem = Fexpand_file_name (tem, Qnil);
1862 else
1864 if (!NILP (Ffile_directory_p (program)))
1865 error ("Specified program for new process is a directory");
1866 tem = program;
1869 /* Remove "/:" from TEM. */
1870 tem = remove_slash_colon (tem);
1872 Lisp_Object arg_encoding = Qnil;
1874 /* Encode the file name and put it in NEW_ARGV.
1875 That's where the child will use it to execute the program. */
1876 tem = list1 (ENCODE_FILE (tem));
1877 ptrdiff_t new_argc = 1;
1879 /* Here we encode arguments by the coding system used for sending
1880 data to the process. We don't support using different coding
1881 systems for encoding arguments and for encoding data sent to the
1882 process. */
1884 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1886 Lisp_Object arg = XCAR (tem2);
1887 CHECK_STRING (arg);
1888 if (STRING_MULTIBYTE (arg))
1890 if (NILP (arg_encoding))
1891 arg_encoding = (complement_process_encoding_system
1892 (XPROCESS (proc)->encode_coding_system));
1893 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1895 tem = Fcons (arg, tem);
1896 new_argc++;
1899 /* Now that everything is encoded we can collect the strings into
1900 NEW_ARGV. */
1901 char **new_argv;
1902 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1903 new_argv[new_argc] = 0;
1905 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1907 new_argv[i] = SSDATA (XCAR (tem));
1908 tem = XCDR (tem);
1911 create_process (proc, new_argv, current_dir);
1913 else
1914 create_pty (proc);
1916 SAFE_FREE ();
1917 return unbind_to (count, proc);
1920 /* If PROC doesn't have its pid set, then an error was signaled and
1921 the process wasn't started successfully, so remove it. */
1922 static void
1923 start_process_unwind (Lisp_Object proc)
1925 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1926 remove_process (proc);
1929 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1931 static void
1932 close_process_fd (int *fd_addr)
1934 int fd = *fd_addr;
1935 if (0 <= fd)
1937 *fd_addr = -1;
1938 emacs_close (fd);
1942 /* Indexes of file descriptors in open_fds. */
1943 enum
1945 /* The pipe from Emacs to its subprocess. */
1946 SUBPROCESS_STDIN,
1947 WRITE_TO_SUBPROCESS,
1949 /* The main pipe from the subprocess to Emacs. */
1950 READ_FROM_SUBPROCESS,
1951 SUBPROCESS_STDOUT,
1953 /* The pipe from the subprocess to Emacs that is closed when the
1954 subprocess execs. */
1955 READ_FROM_EXEC_MONITOR,
1956 EXEC_MONITOR_OUTPUT
1959 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1961 static void
1962 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1964 struct Lisp_Process *p = XPROCESS (process);
1965 int inchannel, outchannel;
1966 pid_t pid;
1967 int vfork_errno;
1968 int forkin, forkout, forkerr = -1;
1969 bool pty_flag = 0;
1970 char pty_name[PTY_NAME_SIZE];
1971 Lisp_Object lisp_pty_name = Qnil;
1972 sigset_t oldset;
1974 inchannel = outchannel = -1;
1976 if (p->pty_flag)
1977 outchannel = inchannel = allocate_pty (pty_name);
1979 if (inchannel >= 0)
1981 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1982 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1983 /* On most USG systems it does not work to open the pty's tty here,
1984 then close it and reopen it in the child. */
1985 /* Don't let this terminal become our controlling terminal
1986 (in case we don't have one). */
1987 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1988 if (forkin < 0)
1989 report_file_error ("Opening pty", Qnil);
1990 p->open_fd[SUBPROCESS_STDIN] = forkin;
1991 #else
1992 forkin = forkout = -1;
1993 #endif /* not USG, or USG_SUBTTY_WORKS */
1994 pty_flag = 1;
1995 lisp_pty_name = build_string (pty_name);
1997 else
1999 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2000 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2001 report_file_error ("Creating pipe", Qnil);
2002 forkin = p->open_fd[SUBPROCESS_STDIN];
2003 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2004 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2005 forkout = p->open_fd[SUBPROCESS_STDOUT];
2007 if (!NILP (p->stderrproc))
2009 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2011 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
2013 /* Close unnecessary file descriptors. */
2014 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
2015 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
2019 #ifndef WINDOWSNT
2020 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
2021 report_file_error ("Creating pipe", Qnil);
2022 #endif
2024 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2025 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2027 /* Record this as an active process, with its channels. */
2028 chan_process[inchannel] = process;
2029 p->infd = inchannel;
2030 p->outfd = outchannel;
2032 /* Previously we recorded the tty descriptor used in the subprocess.
2033 It was only used for getting the foreground tty process, so now
2034 we just reopen the device (see emacs_get_tty_pgrp) as this is
2035 more portable (see USG_SUBTTY_WORKS above). */
2037 p->pty_flag = pty_flag;
2038 pset_status (p, Qrun);
2040 if (!EQ (p->command, Qt))
2041 add_process_read_fd (inchannel);
2043 /* This may signal an error. */
2044 setup_process_coding_systems (process);
2046 block_input ();
2047 block_child_signal (&oldset);
2049 #ifndef WINDOWSNT
2050 /* vfork, and prevent local vars from being clobbered by the vfork. */
2051 Lisp_Object volatile current_dir_volatile = current_dir;
2052 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
2053 char **volatile new_argv_volatile = new_argv;
2054 int volatile forkin_volatile = forkin;
2055 int volatile forkout_volatile = forkout;
2056 int volatile forkerr_volatile = forkerr;
2057 struct Lisp_Process *p_volatile = p;
2059 #ifdef DARWIN_OS
2060 /* Darwin doesn't let us run setsid after a vfork, so use fork when
2061 necessary. Also, reset SIGCHLD handling after a vfork, as
2062 apparently macOS can mistakenly deliver SIGCHLD to the child. */
2063 if (pty_flag)
2064 pid = fork ();
2065 else
2067 pid = vfork ();
2068 if (pid == 0)
2069 signal (SIGCHLD, SIG_DFL);
2071 #else
2072 pid = vfork ();
2073 #endif
2075 current_dir = current_dir_volatile;
2076 lisp_pty_name = lisp_pty_name_volatile;
2077 new_argv = new_argv_volatile;
2078 forkin = forkin_volatile;
2079 forkout = forkout_volatile;
2080 forkerr = forkerr_volatile;
2081 p = p_volatile;
2083 pty_flag = p->pty_flag;
2085 if (pid == 0)
2086 #endif /* not WINDOWSNT */
2088 /* Make the pty be the controlling terminal of the process. */
2089 #ifdef HAVE_PTYS
2090 /* First, disconnect its current controlling terminal.
2091 Do this even if !PTY_FLAG; see Bug#30762. */
2092 setsid ();
2093 /* Make the pty's terminal the controlling terminal. */
2094 if (pty_flag && forkin >= 0)
2096 #ifdef TIOCSCTTY
2097 /* We ignore the return value
2098 because faith@cs.unc.edu says that is necessary on Linux. */
2099 ioctl (forkin, TIOCSCTTY, 0);
2100 #endif
2102 #if defined (LDISC1)
2103 if (pty_flag && forkin >= 0)
2105 struct termios t;
2106 tcgetattr (forkin, &t);
2107 t.c_lflag = LDISC1;
2108 if (tcsetattr (forkin, TCSANOW, &t) < 0)
2109 emacs_perror ("create_process/tcsetattr LDISC1");
2111 #else
2112 #if defined (NTTYDISC) && defined (TIOCSETD)
2113 if (pty_flag && forkin >= 0)
2115 /* Use new line discipline. */
2116 int ldisc = NTTYDISC;
2117 ioctl (forkin, TIOCSETD, &ldisc);
2119 #endif
2120 #endif
2121 #ifdef TIOCNOTTY
2122 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2123 can do TIOCSPGRP only to the process's controlling tty. */
2124 if (pty_flag)
2126 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2127 I can't test it since I don't have 4.3. */
2128 int j = emacs_open (DEV_TTY, O_RDWR, 0);
2129 if (j >= 0)
2131 ioctl (j, TIOCNOTTY, 0);
2132 emacs_close (j);
2135 #endif /* TIOCNOTTY */
2137 #if !defined (DONT_REOPEN_PTY)
2138 /*** There is a suggestion that this ought to be a
2139 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2140 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2141 that system does seem to need this code, even though
2142 both TIOCSCTTY is defined. */
2143 /* Now close the pty (if we had it open) and reopen it.
2144 This makes the pty the controlling terminal of the subprocess. */
2145 if (pty_flag)
2148 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2149 would work? */
2150 if (forkin >= 0)
2151 emacs_close (forkin);
2152 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2154 if (forkin < 0)
2156 emacs_perror (SSDATA (lisp_pty_name));
2157 _exit (EXIT_CANCELED);
2161 #endif /* not DONT_REOPEN_PTY */
2163 #ifdef SETUP_SLAVE_PTY
2164 if (pty_flag)
2166 SETUP_SLAVE_PTY;
2168 #endif /* SETUP_SLAVE_PTY */
2169 #endif /* HAVE_PTYS */
2171 signal (SIGINT, SIG_DFL);
2172 signal (SIGQUIT, SIG_DFL);
2173 #ifdef SIGPROF
2174 signal (SIGPROF, SIG_DFL);
2175 #endif
2177 /* Emacs ignores SIGPIPE, but the child should not. */
2178 signal (SIGPIPE, SIG_DFL);
2180 /* Stop blocking SIGCHLD in the child. */
2181 unblock_child_signal (&oldset);
2183 if (pty_flag)
2184 child_setup_tty (forkout);
2186 if (forkerr < 0)
2187 forkerr = forkout;
2188 #ifdef WINDOWSNT
2189 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2190 #else /* not WINDOWSNT */
2191 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
2192 #endif /* not WINDOWSNT */
2195 /* Back in the parent process. */
2197 vfork_errno = errno;
2198 p->pid = pid;
2199 if (pid >= 0)
2200 p->alive = 1;
2202 /* Stop blocking in the parent. */
2203 unblock_child_signal (&oldset);
2204 unblock_input ();
2206 if (pid < 0)
2207 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2208 else
2210 /* vfork succeeded. */
2212 /* Close the pipe ends that the child uses, or the child's pty. */
2213 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2214 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2216 #ifdef WINDOWSNT
2217 register_child (pid, inchannel);
2218 #endif /* WINDOWSNT */
2220 pset_tty_name (p, lisp_pty_name);
2222 #ifndef WINDOWSNT
2223 /* Wait for child_setup to complete in case that vfork is
2224 actually defined as fork. The descriptor
2225 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2226 of a pipe is closed at the child side either by close-on-exec
2227 on successful execve or the _exit call in child_setup. */
2229 char dummy;
2231 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2232 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2233 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2235 #endif
2236 if (!NILP (p->stderrproc))
2238 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2239 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2244 static void
2245 create_pty (Lisp_Object process)
2247 struct Lisp_Process *p = XPROCESS (process);
2248 char pty_name[PTY_NAME_SIZE];
2249 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2251 if (pty_fd >= 0)
2253 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2254 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2255 /* On most USG systems it does not work to open the pty's tty here,
2256 then close it and reopen it in the child. */
2257 /* Don't let this terminal become our controlling terminal
2258 (in case we don't have one). */
2259 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2260 if (forkout < 0)
2261 report_file_error ("Opening pty", Qnil);
2262 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2263 #if defined (DONT_REOPEN_PTY)
2264 /* In the case that vfork is defined as fork, the parent process
2265 (Emacs) may send some data before the child process completes
2266 tty options setup. So we setup tty before forking. */
2267 child_setup_tty (forkout);
2268 #endif /* DONT_REOPEN_PTY */
2269 #endif /* not USG, or USG_SUBTTY_WORKS */
2271 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2273 /* Record this as an active process, with its channels.
2274 As a result, child_setup will close Emacs's side of the pipes. */
2275 chan_process[pty_fd] = process;
2276 p->infd = pty_fd;
2277 p->outfd = pty_fd;
2279 /* Previously we recorded the tty descriptor used in the subprocess.
2280 It was only used for getting the foreground tty process, so now
2281 we just reopen the device (see emacs_get_tty_pgrp) as this is
2282 more portable (see USG_SUBTTY_WORKS above). */
2284 p->pty_flag = 1;
2285 pset_status (p, Qrun);
2286 setup_process_coding_systems (process);
2288 add_process_read_fd (pty_fd);
2290 pset_tty_name (p, build_string (pty_name));
2293 p->pid = -2;
2296 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2297 0, MANY, 0,
2298 doc: /* Create and return a bidirectional pipe process.
2300 In Emacs, pipes are represented by process objects, so input and
2301 output work as for subprocesses, and `delete-process' closes a pipe.
2302 However, a pipe process has no process id, it cannot be signaled,
2303 and the status codes are different from normal processes.
2305 Arguments are specified as keyword/argument pairs. The following
2306 arguments are defined:
2308 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2310 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2311 with the process. Process output goes at the end of that buffer,
2312 unless you specify a filter function to handle the output. If BUFFER
2313 is not given, the value of NAME is used.
2315 :coding CODING -- If CODING is a symbol, it specifies the coding
2316 system used for both reading and writing for this process. If CODING
2317 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2318 ENCODING is used for writing.
2320 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2321 the process is running. If BOOL is not given, query before exiting.
2323 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2324 In the stopped state, a pipe process does not accept incoming data,
2325 but you can send outgoing data. The stopped state is cleared by
2326 `continue-process' and set by `stop-process'.
2328 :filter FILTER -- Install FILTER as the process filter.
2330 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2332 usage: (make-pipe-process &rest ARGS) */)
2333 (ptrdiff_t nargs, Lisp_Object *args)
2335 Lisp_Object proc, contact;
2336 struct Lisp_Process *p;
2337 Lisp_Object name, buffer;
2338 Lisp_Object tem;
2339 ptrdiff_t specpdl_count;
2340 int inchannel, outchannel;
2342 if (nargs == 0)
2343 return Qnil;
2345 contact = Flist (nargs, args);
2347 name = Fplist_get (contact, QCname);
2348 CHECK_STRING (name);
2349 proc = make_process (name);
2350 specpdl_count = SPECPDL_INDEX ();
2351 record_unwind_protect (remove_process, proc);
2352 p = XPROCESS (proc);
2354 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2355 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2356 report_file_error ("Creating pipe", Qnil);
2357 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2358 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2360 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2361 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2363 #ifdef WINDOWSNT
2364 register_aux_fd (inchannel);
2365 #endif
2367 /* Record this as an active process, with its channels. */
2368 chan_process[inchannel] = proc;
2369 p->infd = inchannel;
2370 p->outfd = outchannel;
2372 if (inchannel > max_desc)
2373 max_desc = inchannel;
2375 buffer = Fplist_get (contact, QCbuffer);
2376 if (NILP (buffer))
2377 buffer = name;
2378 buffer = Fget_buffer_create (buffer);
2379 pset_buffer (p, buffer);
2381 pset_childp (p, contact);
2382 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2383 pset_type (p, Qpipe);
2384 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2385 pset_filter (p, Fplist_get (contact, QCfilter));
2386 eassert (NILP (p->log));
2387 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2388 p->kill_without_query = 1;
2389 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2390 pset_command (p, Qt);
2391 eassert (! p->pty_flag);
2393 if (!EQ (p->command, Qt))
2394 add_process_read_fd (inchannel);
2395 p->adaptive_read_buffering
2396 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2397 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2399 /* Make the process marker point into the process buffer (if any). */
2400 if (BUFFERP (buffer))
2401 set_marker_both (p->mark, buffer,
2402 BUF_ZV (XBUFFER (buffer)),
2403 BUF_ZV_BYTE (XBUFFER (buffer)));
2406 /* Setup coding systems for communicating with the network stream. */
2408 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2409 Lisp_Object coding_systems = Qt;
2410 Lisp_Object val;
2412 tem = Fplist_get (contact, QCcoding);
2413 val = Qnil;
2414 if (!NILP (tem))
2416 val = tem;
2417 if (CONSP (val))
2418 val = XCAR (val);
2420 else if (!NILP (Vcoding_system_for_read))
2421 val = Vcoding_system_for_read;
2422 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2423 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2424 /* We dare not decode end-of-line format by setting VAL to
2425 Qraw_text, because the existing Emacs Lisp libraries
2426 assume that they receive bare code including a sequence of
2427 CR LF. */
2428 val = Qnil;
2429 else
2431 if (CONSP (coding_systems))
2432 val = XCAR (coding_systems);
2433 else if (CONSP (Vdefault_process_coding_system))
2434 val = XCAR (Vdefault_process_coding_system);
2435 else
2436 val = Qnil;
2438 pset_decode_coding_system (p, val);
2440 if (!NILP (tem))
2442 val = tem;
2443 if (CONSP (val))
2444 val = XCDR (val);
2446 else if (!NILP (Vcoding_system_for_write))
2447 val = Vcoding_system_for_write;
2448 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2449 val = Qnil;
2450 else
2452 if (CONSP (coding_systems))
2453 val = XCDR (coding_systems);
2454 else if (CONSP (Vdefault_process_coding_system))
2455 val = XCDR (Vdefault_process_coding_system);
2456 else
2457 val = Qnil;
2459 pset_encode_coding_system (p, val);
2461 /* This may signal an error. */
2462 setup_process_coding_systems (proc);
2464 pset_decoding_buf (p, empty_unibyte_string);
2465 eassert (p->decoding_carryover == 0);
2466 pset_encoding_buf (p, empty_unibyte_string);
2468 specpdl_ptr = specpdl + specpdl_count;
2470 return proc;
2474 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2475 The address family of sa is not included in the result. */
2477 Lisp_Object
2478 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2480 Lisp_Object address;
2481 ptrdiff_t i;
2482 unsigned char *cp;
2483 struct Lisp_Vector *p;
2485 /* Workaround for a bug in getsockname on BSD: Names bound to
2486 sockets in the UNIX domain are inaccessible; getsockname returns
2487 a zero length name. */
2488 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2489 return empty_unibyte_string;
2491 switch (sa->sa_family)
2493 case AF_INET:
2495 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2496 len = sizeof (sin->sin_addr) + 1;
2497 address = Fmake_vector (make_number (len), Qnil);
2498 p = XVECTOR (address);
2499 p->contents[--len] = make_number (ntohs (sin->sin_port));
2500 cp = (unsigned char *) &sin->sin_addr;
2501 break;
2503 #ifdef AF_INET6
2504 case AF_INET6:
2506 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2507 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2508 len = sizeof (sin6->sin6_addr) / 2 + 1;
2509 address = Fmake_vector (make_number (len), Qnil);
2510 p = XVECTOR (address);
2511 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2512 for (i = 0; i < len; i++)
2513 p->contents[i] = make_number (ntohs (ip6[i]));
2514 return address;
2516 #endif
2517 #ifdef HAVE_LOCAL_SOCKETS
2518 case AF_LOCAL:
2520 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2521 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2522 /* If the first byte is NUL, the name is a Linux abstract
2523 socket name, and the name can contain embedded NULs. If
2524 it's not, we have a NUL-terminated string. Be careful not
2525 to walk past the end of the object looking for the name
2526 terminator, however. */
2527 if (name_length > 0 && sockun->sun_path[0] != '\0')
2529 const char *terminator
2530 = memchr (sockun->sun_path, '\0', name_length);
2532 if (terminator)
2533 name_length = terminator - (const char *) sockun->sun_path;
2536 return make_unibyte_string (sockun->sun_path, name_length);
2538 #endif
2539 default:
2540 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2541 address = Fcons (make_number (sa->sa_family),
2542 Fmake_vector (make_number (len), Qnil));
2543 p = XVECTOR (XCDR (address));
2544 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2545 break;
2548 i = 0;
2549 while (i < len)
2550 p->contents[i++] = make_number (*cp++);
2552 return address;
2555 /* Convert an internal struct addrinfo to a Lisp object. */
2557 static Lisp_Object
2558 conv_addrinfo_to_lisp (struct addrinfo *res)
2560 Lisp_Object protocol = make_number (res->ai_protocol);
2561 eassert (XINT (protocol) == res->ai_protocol);
2562 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2566 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2568 static ptrdiff_t
2569 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2571 struct Lisp_Vector *p;
2573 if (VECTORP (address))
2575 p = XVECTOR (address);
2576 if (p->header.size == 5)
2578 *familyp = AF_INET;
2579 return sizeof (struct sockaddr_in);
2581 #ifdef AF_INET6
2582 else if (p->header.size == 9)
2584 *familyp = AF_INET6;
2585 return sizeof (struct sockaddr_in6);
2587 #endif
2589 #ifdef HAVE_LOCAL_SOCKETS
2590 else if (STRINGP (address))
2592 *familyp = AF_LOCAL;
2593 return sizeof (struct sockaddr_un);
2595 #endif
2596 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2597 && VECTORP (XCDR (address)))
2599 struct sockaddr *sa;
2600 p = XVECTOR (XCDR (address));
2601 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2602 return 0;
2603 *familyp = XINT (XCAR (address));
2604 return p->header.size + sizeof (sa->sa_family);
2606 return 0;
2609 /* Convert an address object (vector or string) to an internal sockaddr.
2611 The address format has been basically validated by
2612 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2613 it could have come from user data. So if FAMILY is not valid,
2614 we return after zeroing *SA. */
2616 static void
2617 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2619 register struct Lisp_Vector *p;
2620 register unsigned char *cp = NULL;
2621 register int i;
2622 EMACS_INT hostport;
2624 memset (sa, 0, len);
2626 if (VECTORP (address))
2628 p = XVECTOR (address);
2629 if (family == AF_INET)
2631 DECLARE_POINTER_ALIAS (sin, struct sockaddr_in, sa);
2632 len = sizeof (sin->sin_addr) + 1;
2633 hostport = XINT (p->contents[--len]);
2634 sin->sin_port = htons (hostport);
2635 cp = (unsigned char *)&sin->sin_addr;
2636 sa->sa_family = family;
2638 #ifdef AF_INET6
2639 else if (family == AF_INET6)
2641 DECLARE_POINTER_ALIAS (sin6, struct sockaddr_in6, sa);
2642 DECLARE_POINTER_ALIAS (ip6, uint16_t, &sin6->sin6_addr);
2643 len = sizeof (sin6->sin6_addr) / 2 + 1;
2644 hostport = XINT (p->contents[--len]);
2645 sin6->sin6_port = htons (hostport);
2646 for (i = 0; i < len; i++)
2647 if (INTEGERP (p->contents[i]))
2649 int j = XFASTINT (p->contents[i]) & 0xffff;
2650 ip6[i] = ntohs (j);
2652 sa->sa_family = family;
2653 return;
2655 #endif
2656 else
2657 return;
2659 else if (STRINGP (address))
2661 #ifdef HAVE_LOCAL_SOCKETS
2662 if (family == AF_LOCAL)
2664 DECLARE_POINTER_ALIAS (sockun, struct sockaddr_un, sa);
2665 cp = SDATA (address);
2666 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2667 sockun->sun_path[i] = *cp++;
2668 sa->sa_family = family;
2670 #endif
2671 return;
2673 else
2675 p = XVECTOR (XCDR (address));
2676 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2679 for (i = 0; i < len; i++)
2680 if (INTEGERP (p->contents[i]))
2681 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2684 #ifdef DATAGRAM_SOCKETS
2685 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2686 1, 1, 0,
2687 doc: /* Get the current datagram address associated with PROCESS.
2688 If PROCESS is a non-blocking network process that hasn't been fully
2689 set up yet, this function will block until socket setup has completed. */)
2690 (Lisp_Object process)
2692 int channel;
2694 CHECK_PROCESS (process);
2696 if (NETCONN_P (process))
2697 wait_for_socket_fds (process, "process-datagram-address");
2699 if (!DATAGRAM_CONN_P (process))
2700 return Qnil;
2702 channel = XPROCESS (process)->infd;
2703 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2704 datagram_address[channel].len);
2707 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2708 2, 2, 0,
2709 doc: /* Set the datagram address for PROCESS to ADDRESS.
2710 Return nil upon error setting address, ADDRESS otherwise.
2712 If PROCESS is a non-blocking network process that hasn't been fully
2713 set up yet, this function will block until socket setup has completed. */)
2714 (Lisp_Object process, Lisp_Object address)
2716 int channel;
2717 int family;
2718 ptrdiff_t len;
2720 CHECK_PROCESS (process);
2722 if (NETCONN_P (process))
2723 wait_for_socket_fds (process, "set-process-datagram-address");
2725 if (!DATAGRAM_CONN_P (process))
2726 return Qnil;
2728 channel = XPROCESS (process)->infd;
2730 len = get_lisp_to_sockaddr_size (address, &family);
2731 if (len == 0 || datagram_address[channel].len != len)
2732 return Qnil;
2733 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2734 return address;
2736 #endif
2739 static const struct socket_options {
2740 /* The name of this option. Should be lowercase version of option
2741 name without SO_ prefix. */
2742 const char *name;
2743 /* Option level SOL_... */
2744 int optlevel;
2745 /* Option number SO_... */
2746 int optnum;
2747 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2748 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2749 } socket_options[] =
2751 #ifdef SO_BINDTODEVICE
2752 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2753 #endif
2754 #ifdef SO_BROADCAST
2755 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2756 #endif
2757 #ifdef SO_DONTROUTE
2758 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2759 #endif
2760 #ifdef SO_KEEPALIVE
2761 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2762 #endif
2763 #ifdef SO_LINGER
2764 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2765 #endif
2766 #ifdef SO_OOBINLINE
2767 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2768 #endif
2769 #ifdef SO_PRIORITY
2770 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2771 #endif
2772 #ifdef SO_REUSEADDR
2773 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2774 #endif
2775 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2778 /* Set option OPT to value VAL on socket S.
2780 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2781 Signals an error if setting a known option fails.
2784 static int
2785 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2787 char *name;
2788 const struct socket_options *sopt;
2789 int ret = 0;
2791 CHECK_SYMBOL (opt);
2793 name = SSDATA (SYMBOL_NAME (opt));
2794 for (sopt = socket_options; sopt->name; sopt++)
2795 if (strcmp (name, sopt->name) == 0)
2796 break;
2798 switch (sopt->opttype)
2800 case SOPT_BOOL:
2802 int optval;
2803 optval = NILP (val) ? 0 : 1;
2804 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2805 &optval, sizeof (optval));
2806 break;
2809 case SOPT_INT:
2811 int optval;
2812 if (TYPE_RANGED_INTEGERP (int, val))
2813 optval = XINT (val);
2814 else
2815 error ("Bad option value for %s", name);
2816 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2817 &optval, sizeof (optval));
2818 break;
2821 #ifdef SO_BINDTODEVICE
2822 case SOPT_IFNAME:
2824 char devname[IFNAMSIZ + 1];
2826 /* This is broken, at least in the Linux 2.4 kernel.
2827 To unbind, the arg must be a zero integer, not the empty string.
2828 This should work on all systems. KFS. 2003-09-23. */
2829 memset (devname, 0, sizeof devname);
2830 if (STRINGP (val))
2832 char *arg = SSDATA (val);
2833 int len = min (strlen (arg), IFNAMSIZ);
2834 memcpy (devname, arg, len);
2836 else if (!NILP (val))
2837 error ("Bad option value for %s", name);
2838 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2839 devname, IFNAMSIZ);
2840 break;
2842 #endif
2844 #ifdef SO_LINGER
2845 case SOPT_LINGER:
2847 struct linger linger;
2849 linger.l_onoff = 1;
2850 linger.l_linger = 0;
2851 if (TYPE_RANGED_INTEGERP (int, val))
2852 linger.l_linger = XINT (val);
2853 else
2854 linger.l_onoff = NILP (val) ? 0 : 1;
2855 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2856 &linger, sizeof (linger));
2857 break;
2859 #endif
2861 default:
2862 return 0;
2865 if (ret < 0)
2867 int setsockopt_errno = errno;
2868 report_file_errno ("Cannot set network option", list2 (opt, val),
2869 setsockopt_errno);
2872 return (1 << sopt->optbit);
2876 DEFUN ("set-network-process-option",
2877 Fset_network_process_option, Sset_network_process_option,
2878 3, 4, 0,
2879 doc: /* For network process PROCESS set option OPTION to value VALUE.
2880 See `make-network-process' for a list of options and values.
2881 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2882 OPTION is not a supported option, return nil instead; otherwise return t.
2884 If PROCESS is a non-blocking network process that hasn't been fully
2885 set up yet, this function will block until socket setup has completed. */)
2886 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2888 int s;
2889 struct Lisp_Process *p;
2891 CHECK_PROCESS (process);
2892 p = XPROCESS (process);
2893 if (!NETCONN1_P (p))
2894 error ("Process is not a network process");
2896 wait_for_socket_fds (process, "set-network-process-option");
2898 s = p->infd;
2899 if (s < 0)
2900 error ("Process is not running");
2902 if (set_socket_option (s, option, value))
2904 pset_childp (p, Fplist_put (p->childp, option, value));
2905 return Qt;
2908 if (NILP (no_error))
2909 error ("Unknown or unsupported option");
2911 return Qnil;
2915 DEFUN ("serial-process-configure",
2916 Fserial_process_configure,
2917 Sserial_process_configure,
2918 0, MANY, 0,
2919 doc: /* Configure speed, bytesize, etc. of a serial process.
2921 Arguments are specified as keyword/argument pairs. Attributes that
2922 are not given are re-initialized from the process's current
2923 configuration (available via the function `process-contact') or set to
2924 reasonable default values. The following arguments are defined:
2926 :process PROCESS
2927 :name NAME
2928 :buffer BUFFER
2929 :port PORT
2930 -- Any of these arguments can be given to identify the process that is
2931 to be configured. If none of these arguments is given, the current
2932 buffer's process is used.
2934 :speed SPEED -- SPEED is the speed of the serial port in bits per
2935 second, also called baud rate. Any value can be given for SPEED, but
2936 most serial ports work only at a few defined values between 1200 and
2937 115200, with 9600 being the most common value. If SPEED is nil, the
2938 serial port is not configured any further, i.e., all other arguments
2939 are ignored. This may be useful for special serial ports such as
2940 Bluetooth-to-serial converters which can only be configured through AT
2941 commands. A value of nil for SPEED can be used only when passed
2942 through `make-serial-process' or `serial-term'.
2944 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2945 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2947 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2948 `odd' (use odd parity), or the symbol `even' (use even parity). If
2949 PARITY is not given, no parity is used.
2951 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2952 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2953 is not given or nil, 1 stopbit is used.
2955 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2956 flowcontrol to be used, which is either nil (don't use flowcontrol),
2957 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2958 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2959 flowcontrol is used.
2961 `serial-process-configure' is called by `make-serial-process' for the
2962 initial configuration of the serial port.
2964 Examples:
2966 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2968 \(serial-process-configure
2969 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2971 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2973 usage: (serial-process-configure &rest ARGS) */)
2974 (ptrdiff_t nargs, Lisp_Object *args)
2976 struct Lisp_Process *p;
2977 Lisp_Object contact = Qnil;
2978 Lisp_Object proc = Qnil;
2980 contact = Flist (nargs, args);
2982 proc = Fplist_get (contact, QCprocess);
2983 if (NILP (proc))
2984 proc = Fplist_get (contact, QCname);
2985 if (NILP (proc))
2986 proc = Fplist_get (contact, QCbuffer);
2987 if (NILP (proc))
2988 proc = Fplist_get (contact, QCport);
2989 proc = get_process (proc);
2990 p = XPROCESS (proc);
2991 if (!EQ (p->type, Qserial))
2992 error ("Not a serial process");
2994 if (NILP (Fplist_get (p->childp, QCspeed)))
2995 return Qnil;
2997 serial_configure (p, contact);
2998 return Qnil;
3001 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
3002 0, MANY, 0,
3003 doc: /* Create and return a serial port process.
3005 In Emacs, serial port connections are represented by process objects,
3006 so input and output work as for subprocesses, and `delete-process'
3007 closes a serial port connection. However, a serial process has no
3008 process id, it cannot be signaled, and the status codes are different
3009 from normal processes.
3011 `make-serial-process' creates a process and a buffer, on which you
3012 probably want to use `process-send-string'. Try \\[serial-term] for
3013 an interactive terminal. See below for examples.
3015 Arguments are specified as keyword/argument pairs. The following
3016 arguments are defined:
3018 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3019 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
3020 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3021 the backslashes in strings).
3023 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3024 which this function calls.
3026 :name NAME -- NAME is the name of the process. If NAME is not given,
3027 the value of PORT is used.
3029 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3030 with the process. Process output goes at the end of that buffer,
3031 unless you specify a filter function to handle the output. If BUFFER
3032 is not given, the value of NAME is used.
3034 :coding CODING -- If CODING is a symbol, it specifies the coding
3035 system used for both reading and writing for this process. If CODING
3036 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3037 ENCODING is used for writing.
3039 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3040 the process is running. If BOOL is not given, query before exiting.
3042 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3043 In the stopped state, a serial process does not accept incoming data,
3044 but you can send outgoing data. The stopped state is cleared by
3045 `continue-process' and set by `stop-process'.
3047 :filter FILTER -- Install FILTER as the process filter.
3049 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3051 :plist PLIST -- Install PLIST as the initial plist of the process.
3053 :bytesize
3054 :parity
3055 :stopbits
3056 :flowcontrol
3057 -- This function calls `serial-process-configure' to handle these
3058 arguments.
3060 The original argument list, possibly modified by later configuration,
3061 is available via the function `process-contact'.
3063 Examples:
3065 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3067 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3069 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3071 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3073 usage: (make-serial-process &rest ARGS) */)
3074 (ptrdiff_t nargs, Lisp_Object *args)
3076 int fd = -1;
3077 Lisp_Object proc, contact, port;
3078 struct Lisp_Process *p;
3079 Lisp_Object name, buffer;
3080 Lisp_Object tem, val;
3081 ptrdiff_t specpdl_count;
3083 if (nargs == 0)
3084 return Qnil;
3086 contact = Flist (nargs, args);
3088 port = Fplist_get (contact, QCport);
3089 if (NILP (port))
3090 error ("No port specified");
3091 CHECK_STRING (port);
3093 if (NILP (Fplist_member (contact, QCspeed)))
3094 error (":speed not specified");
3095 if (!NILP (Fplist_get (contact, QCspeed)))
3096 CHECK_NUMBER (Fplist_get (contact, QCspeed));
3098 name = Fplist_get (contact, QCname);
3099 if (NILP (name))
3100 name = port;
3101 CHECK_STRING (name);
3102 proc = make_process (name);
3103 specpdl_count = SPECPDL_INDEX ();
3104 record_unwind_protect (remove_process, proc);
3105 p = XPROCESS (proc);
3107 fd = serial_open (port);
3108 p->open_fd[SUBPROCESS_STDIN] = fd;
3109 p->infd = fd;
3110 p->outfd = fd;
3111 if (fd > max_desc)
3112 max_desc = fd;
3113 chan_process[fd] = proc;
3115 buffer = Fplist_get (contact, QCbuffer);
3116 if (NILP (buffer))
3117 buffer = name;
3118 buffer = Fget_buffer_create (buffer);
3119 pset_buffer (p, buffer);
3121 pset_childp (p, contact);
3122 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3123 pset_type (p, Qserial);
3124 pset_sentinel (p, Fplist_get (contact, QCsentinel));
3125 pset_filter (p, Fplist_get (contact, QCfilter));
3126 eassert (NILP (p->log));
3127 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3128 p->kill_without_query = 1;
3129 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3130 pset_command (p, Qt);
3131 eassert (! p->pty_flag);
3133 if (!EQ (p->command, Qt))
3134 add_process_read_fd (fd);
3136 if (BUFFERP (buffer))
3138 set_marker_both (p->mark, buffer,
3139 BUF_ZV (XBUFFER (buffer)),
3140 BUF_ZV_BYTE (XBUFFER (buffer)));
3143 tem = Fplist_member (contact, QCcoding);
3144 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3145 tem = Qnil;
3147 val = Qnil;
3148 if (!NILP (tem))
3150 val = XCAR (XCDR (tem));
3151 if (CONSP (val))
3152 val = XCAR (val);
3154 else if (!NILP (Vcoding_system_for_read))
3155 val = Vcoding_system_for_read;
3156 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3157 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3158 val = Qnil;
3159 pset_decode_coding_system (p, val);
3161 val = Qnil;
3162 if (!NILP (tem))
3164 val = XCAR (XCDR (tem));
3165 if (CONSP (val))
3166 val = XCDR (val);
3168 else if (!NILP (Vcoding_system_for_write))
3169 val = Vcoding_system_for_write;
3170 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3171 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3172 val = Qnil;
3173 pset_encode_coding_system (p, val);
3175 setup_process_coding_systems (proc);
3176 pset_decoding_buf (p, empty_unibyte_string);
3177 eassert (p->decoding_carryover == 0);
3178 pset_encoding_buf (p, empty_unibyte_string);
3179 p->inherit_coding_system_flag
3180 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3182 Fserial_process_configure (nargs, args);
3184 specpdl_ptr = specpdl + specpdl_count;
3186 return proc;
3189 static void
3190 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
3191 Lisp_Object service, Lisp_Object name)
3193 Lisp_Object tem;
3194 struct Lisp_Process *p = XPROCESS (proc);
3195 Lisp_Object contact = p->childp;
3196 Lisp_Object coding_systems = Qt;
3197 Lisp_Object val;
3199 tem = Fplist_member (contact, QCcoding);
3200 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3201 tem = Qnil; /* No error message (too late!). */
3203 /* Setup coding systems for communicating with the network stream. */
3204 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3206 if (!NILP (tem))
3208 val = XCAR (XCDR (tem));
3209 if (CONSP (val))
3210 val = XCAR (val);
3212 else if (!NILP (Vcoding_system_for_read))
3213 val = Vcoding_system_for_read;
3214 else if ((!NILP (p->buffer)
3215 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3216 || (NILP (p->buffer)
3217 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3218 /* We dare not decode end-of-line format by setting VAL to
3219 Qraw_text, because the existing Emacs Lisp libraries
3220 assume that they receive bare code including a sequence of
3221 CR LF. */
3222 val = Qnil;
3223 else
3225 if (NILP (host) || NILP (service))
3226 coding_systems = Qnil;
3227 else
3228 coding_systems = CALLN (Ffind_operation_coding_system,
3229 Qopen_network_stream, name, p->buffer,
3230 host, service);
3231 if (CONSP (coding_systems))
3232 val = XCAR (coding_systems);
3233 else if (CONSP (Vdefault_process_coding_system))
3234 val = XCAR (Vdefault_process_coding_system);
3235 else
3236 val = Qnil;
3238 pset_decode_coding_system (p, val);
3240 if (!NILP (tem))
3242 val = XCAR (XCDR (tem));
3243 if (CONSP (val))
3244 val = XCDR (val);
3246 else if (!NILP (Vcoding_system_for_write))
3247 val = Vcoding_system_for_write;
3248 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3249 val = Qnil;
3250 else
3252 if (EQ (coding_systems, Qt))
3254 if (NILP (host) || NILP (service))
3255 coding_systems = Qnil;
3256 else
3257 coding_systems = CALLN (Ffind_operation_coding_system,
3258 Qopen_network_stream, name, p->buffer,
3259 host, service);
3261 if (CONSP (coding_systems))
3262 val = XCDR (coding_systems);
3263 else if (CONSP (Vdefault_process_coding_system))
3264 val = XCDR (Vdefault_process_coding_system);
3265 else
3266 val = Qnil;
3268 pset_encode_coding_system (p, val);
3270 pset_decoding_buf (p, empty_unibyte_string);
3271 p->decoding_carryover = 0;
3272 pset_encoding_buf (p, empty_unibyte_string);
3274 p->inherit_coding_system_flag
3275 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3278 #ifdef HAVE_GNUTLS
3279 static void
3280 finish_after_tls_connection (Lisp_Object proc)
3282 struct Lisp_Process *p = XPROCESS (proc);
3283 Lisp_Object contact = p->childp;
3284 Lisp_Object result = Qt;
3286 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3287 result = call3 (Qnsm_verify_connection,
3288 proc,
3289 Fplist_get (contact, QChost),
3290 Fplist_get (contact, QCservice));
3292 if (NILP (result))
3294 pset_status (p, list2 (Qfailed,
3295 build_string ("The Network Security Manager stopped the connections")));
3296 deactivate_process (proc);
3298 else if (p->outfd < 0)
3300 /* The counterparty may have closed the connection (especially
3301 if the NSM prompt above take a long time), so recheck the file
3302 descriptor here. */
3303 pset_status (p, Qfailed);
3304 deactivate_process (proc);
3306 else if ((fd_callback_info[p->outfd].flags & NON_BLOCKING_CONNECT_FD) == 0)
3308 /* If we cleared the connection wait mask before we did the TLS
3309 setup, then we have to say that the process is finally "open"
3310 here. */
3311 pset_status (p, Qrun);
3312 /* Execute the sentinel here. If we had relied on status_notify
3313 to do it later, it will read input from the process before
3314 calling the sentinel. */
3315 exec_sentinel (proc, build_string ("open\n"));
3318 #endif
3320 static void
3321 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3322 Lisp_Object use_external_socket_p)
3324 int s = -1, outch, inch;
3325 int xerrno = 0;
3326 int family;
3327 int ret;
3328 ptrdiff_t addrlen;
3329 struct Lisp_Process *p = XPROCESS (proc);
3330 Lisp_Object contact = p->childp;
3331 int optbits = 0;
3332 int socket_to_use = -1;
3334 if (!NILP (use_external_socket_p))
3336 socket_to_use = external_sock_fd;
3338 /* Ensure we don't consume the external socket twice. */
3339 external_sock_fd = -1;
3342 /* Do this in case we never enter the while-loop below. */
3343 s = -1;
3345 struct sockaddr *sa = NULL;
3346 ptrdiff_t count = SPECPDL_INDEX ();
3347 record_unwind_protect_nothing ();
3348 ptrdiff_t count1 = SPECPDL_INDEX ();
3350 while (!NILP (addrinfos))
3352 Lisp_Object addrinfo = XCAR (addrinfos);
3353 addrinfos = XCDR (addrinfos);
3354 int protocol = XINT (XCAR (addrinfo));
3355 Lisp_Object ip_address = XCDR (addrinfo);
3357 #ifdef WINDOWSNT
3358 retry_connect:
3359 #endif
3361 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3362 sa = xrealloc (sa, addrlen);
3363 set_unwind_protect_ptr (count, xfree, sa);
3364 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3366 s = socket_to_use;
3367 if (s < 0)
3369 int socktype = p->socktype | SOCK_CLOEXEC;
3370 if (p->is_non_blocking_client)
3371 socktype |= SOCK_NONBLOCK;
3372 s = socket (family, socktype, protocol);
3373 if (s < 0)
3375 xerrno = errno;
3376 continue;
3380 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3382 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3383 if (ret < 0)
3385 xerrno = errno;
3386 emacs_close (s);
3387 s = -1;
3388 if (0 <= socket_to_use)
3389 break;
3390 continue;
3394 #ifdef DATAGRAM_SOCKETS
3395 if (!p->is_server && p->socktype == SOCK_DGRAM)
3396 break;
3397 #endif /* DATAGRAM_SOCKETS */
3399 /* Make us close S if quit. */
3400 record_unwind_protect_int (close_file_unwind, s);
3402 /* Parse network options in the arg list. We simply ignore anything
3403 which isn't a known option (including other keywords). An error
3404 is signaled if setting a known option fails. */
3406 Lisp_Object params = contact, key, val;
3408 while (!NILP (params))
3410 key = XCAR (params);
3411 params = XCDR (params);
3412 val = XCAR (params);
3413 params = XCDR (params);
3414 optbits |= set_socket_option (s, key, val);
3418 if (p->is_server)
3420 /* Configure as a server socket. */
3422 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3423 explicit :reuseaddr key to override this. */
3424 #ifdef HAVE_LOCAL_SOCKETS
3425 if (family != AF_LOCAL)
3426 #endif
3427 if (!(optbits & (1 << OPIX_REUSEADDR)))
3429 int optval = 1;
3430 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3431 report_file_error ("Cannot set reuse option on server socket", Qnil);
3434 /* If passed a socket descriptor, it should be already bound. */
3435 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3436 report_file_error ("Cannot bind server socket", Qnil);
3438 #ifdef HAVE_GETSOCKNAME
3439 if (p->port == 0
3440 #ifdef HAVE_LOCAL_SOCKETS
3441 && family != AF_LOCAL
3442 #endif
3445 struct sockaddr_in sa1;
3446 socklen_t len1 = sizeof (sa1);
3447 #ifdef AF_INET6
3448 /* The code below assumes the port is at the same offset
3449 and of the same width in both IPv4 and IPv6
3450 structures, but the standards don't guarantee that,
3451 so verify it here. */
3452 struct sockaddr_in6 sa6;
3453 verify ((offsetof (struct sockaddr_in, sin_port)
3454 == offsetof (struct sockaddr_in6, sin6_port))
3455 && sizeof (sa1.sin_port) == sizeof (sa6.sin6_port));
3456 #endif
3457 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3458 if (getsockname (s, psa1, &len1) == 0)
3460 Lisp_Object service = make_number (ntohs (sa1.sin_port));
3461 contact = Fplist_put (contact, QCservice, service);
3462 /* Save the port number so that we can stash it in
3463 the process object later. */
3464 DECLARE_POINTER_ALIAS (psa, struct sockaddr_in, sa);
3465 psa->sin_port = sa1.sin_port;
3468 #endif
3470 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3471 report_file_error ("Cannot listen on server socket", Qnil);
3473 break;
3476 maybe_quit ();
3478 ret = connect (s, sa, addrlen);
3479 xerrno = errno;
3481 if (ret == 0 || xerrno == EISCONN)
3483 /* The unwind-protect will be discarded afterwards. */
3484 break;
3487 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3488 break;
3490 #ifndef WINDOWSNT
3491 if (xerrno == EINTR)
3493 /* Unlike most other syscalls connect() cannot be called
3494 again. (That would return EALREADY.) The proper way to
3495 wait for completion is pselect(). */
3496 int sc;
3497 socklen_t len;
3498 fd_set fdset;
3499 retry_select:
3500 FD_ZERO (&fdset);
3501 FD_SET (s, &fdset);
3502 maybe_quit ();
3503 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3504 if (sc == -1)
3506 if (errno == EINTR)
3507 goto retry_select;
3508 else
3509 report_file_error ("Failed select", Qnil);
3511 eassert (sc > 0);
3513 len = sizeof xerrno;
3514 eassert (FD_ISSET (s, &fdset));
3515 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3516 report_file_error ("Failed getsockopt", Qnil);
3517 if (xerrno == 0)
3518 break;
3519 if (NILP (addrinfos))
3520 report_file_errno ("Failed connect", Qnil, xerrno);
3522 #endif /* !WINDOWSNT */
3524 /* Discard the unwind protect closing S. */
3525 specpdl_ptr = specpdl + count1;
3526 emacs_close (s);
3527 s = -1;
3528 if (0 <= socket_to_use)
3529 break;
3531 #ifdef WINDOWSNT
3532 if (xerrno == EINTR)
3533 goto retry_connect;
3534 #endif
3537 if (s >= 0)
3539 #ifdef DATAGRAM_SOCKETS
3540 if (p->socktype == SOCK_DGRAM)
3542 if (datagram_address[s].sa)
3543 emacs_abort ();
3545 datagram_address[s].sa = xmalloc (addrlen);
3546 datagram_address[s].len = addrlen;
3547 if (p->is_server)
3549 Lisp_Object remote;
3550 memset (datagram_address[s].sa, 0, addrlen);
3551 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3553 int rfamily;
3554 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3555 if (rlen != 0 && rfamily == family
3556 && rlen == addrlen)
3557 conv_lisp_to_sockaddr (rfamily, remote,
3558 datagram_address[s].sa, rlen);
3561 else
3562 memcpy (datagram_address[s].sa, sa, addrlen);
3564 #endif
3566 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3567 conv_sockaddr_to_lisp (sa, addrlen));
3568 #ifdef HAVE_GETSOCKNAME
3569 if (!p->is_server)
3571 struct sockaddr_storage sa1;
3572 socklen_t len1 = sizeof (sa1);
3573 DECLARE_POINTER_ALIAS (psa1, struct sockaddr, &sa1);
3574 if (getsockname (s, psa1, &len1) == 0)
3575 contact = Fplist_put (contact, QClocal,
3576 conv_sockaddr_to_lisp (psa1, len1));
3578 #endif
3581 if (s < 0)
3583 const char *err = (p->is_server
3584 ? "make server process failed"
3585 : "make client process failed");
3587 /* If non-blocking got this far - and failed - assume non-blocking is
3588 not supported after all. This is probably a wrong assumption, but
3589 the normal blocking calls to open-network-stream handles this error
3590 better. */
3591 if (p->is_non_blocking_client)
3593 Lisp_Object data = get_file_errno_data (err, contact, xerrno);
3595 pset_status (p, list2 (Fcar (data), Fcdr (data)));
3596 unbind_to (count, Qnil);
3597 return;
3600 report_file_errno (err, contact, xerrno);
3603 inch = s;
3604 outch = s;
3606 chan_process[inch] = proc;
3608 fcntl (inch, F_SETFL, O_NONBLOCK);
3610 p = XPROCESS (proc);
3611 p->open_fd[SUBPROCESS_STDIN] = inch;
3612 p->infd = inch;
3613 p->outfd = outch;
3615 /* Discard the unwind protect for closing S, if any. */
3616 specpdl_ptr = specpdl + count1;
3618 if (p->is_server && p->socktype != SOCK_DGRAM)
3619 pset_status (p, Qlisten);
3621 /* Make the process marker point into the process buffer (if any). */
3622 if (BUFFERP (p->buffer))
3623 set_marker_both (p->mark, p->buffer,
3624 BUF_ZV (XBUFFER (p->buffer)),
3625 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3627 if (p->is_non_blocking_client)
3629 /* We may get here if connect did succeed immediately. However,
3630 in that case, we still need to signal this like a non-blocking
3631 connection. */
3632 if (! (connecting_status (p->status)
3633 && EQ (XCDR (p->status), addrinfos)))
3634 pset_status (p, Fcons (Qconnect, addrinfos));
3635 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3636 add_non_blocking_write_fd (inch);
3638 else
3639 /* A server may have a client filter setting of Qt, but it must
3640 still listen for incoming connects unless it is stopped. */
3641 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3642 || (EQ (p->status, Qlisten) && NILP (p->command)))
3643 add_process_read_fd (inch);
3645 if (inch > max_desc)
3646 max_desc = inch;
3648 /* Set up the masks based on the process filter. */
3649 set_process_filter_masks (p);
3651 setup_process_coding_systems (proc);
3653 #ifdef HAVE_GNUTLS
3654 /* Continue the asynchronous connection. */
3655 if (!NILP (p->gnutls_boot_parameters))
3657 Lisp_Object boot, params = p->gnutls_boot_parameters;
3659 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3660 p->gnutls_boot_parameters = Qnil;
3662 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3663 /* Run sentinels, etc. */
3664 finish_after_tls_connection (proc);
3665 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3667 deactivate_process (proc);
3668 if (NILP (boot))
3669 pset_status (p, list2 (Qfailed,
3670 build_string ("TLS negotiation failed")));
3671 else
3672 pset_status (p, list2 (Qfailed, boot));
3675 #endif
3677 unbind_to (count, Qnil);
3680 /* Create a network stream/datagram client/server process. Treated
3681 exactly like a normal process when reading and writing. Primary
3682 differences are in status display and process deletion. A network
3683 connection has no PID; you cannot signal it. All you can do is
3684 stop/continue it and deactivate/close it via delete-process. */
3686 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3687 0, MANY, 0,
3688 doc: /* Create and return a network server or client process.
3690 In Emacs, network connections are represented by process objects, so
3691 input and output work as for subprocesses and `delete-process' closes
3692 a network connection. However, a network process has no process id,
3693 it cannot be signaled, and the status codes are different from normal
3694 processes.
3696 Arguments are specified as keyword/argument pairs. The following
3697 arguments are defined:
3699 :name NAME -- NAME is name for process. It is modified if necessary
3700 to make it unique.
3702 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3703 with the process. Process output goes at end of that buffer, unless
3704 you specify a filter function to handle the output. BUFFER may be
3705 also nil, meaning that this process is not associated with any buffer.
3707 :host HOST -- HOST is name of the host to connect to, or its IP
3708 address. The symbol `local' specifies the local host. If specified
3709 for a server process, it must be a valid name or address for the local
3710 host, and only clients connecting to that address will be accepted.
3712 :service SERVICE -- SERVICE is name of the service desired, or an
3713 integer specifying a port number to connect to. If SERVICE is t,
3714 a random port number is selected for the server. A port number can
3715 be specified as an integer string, e.g., "80", as well as an integer.
3717 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3718 stream type connection, `datagram' creates a datagram type connection,
3719 `seqpacket' creates a reliable datagram connection.
3721 :family FAMILY -- FAMILY is the address (and protocol) family for the
3722 service specified by HOST and SERVICE. The default (nil) is to use
3723 whatever address family (IPv4 or IPv6) that is defined for the host
3724 and port number specified by HOST and SERVICE. Other address families
3725 supported are:
3726 local -- for a local (i.e. UNIX) address specified by SERVICE.
3727 ipv4 -- use IPv4 address family only.
3728 ipv6 -- use IPv6 address family only.
3730 :local ADDRESS -- ADDRESS is the local address used for the connection.
3731 This parameter is ignored when opening a client process. When specified
3732 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3734 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3735 connection. This parameter is ignored when opening a stream server
3736 process. For a datagram server process, it specifies the initial
3737 setting of the remote datagram address. When specified for a client
3738 process, the FAMILY, HOST, and SERVICE args are ignored.
3740 The format of ADDRESS depends on the address family:
3741 - An IPv4 address is represented as a vector of integers [A B C D P]
3742 corresponding to numeric IP address A.B.C.D and port number P.
3743 - A local address is represented as a string with the address in the
3744 local address space.
3745 - An "unsupported family" address is represented by a cons (F . AV)
3746 where F is the family number and AV is a vector containing the socket
3747 address data with one element per address data byte. Do not rely on
3748 this format in portable code, as it may depend on implementation
3749 defined constants, data sizes, and data structure alignment.
3751 :coding CODING -- If CODING is a symbol, it specifies the coding
3752 system used for both reading and writing for this process. If CODING
3753 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3754 ENCODING is used for writing.
3756 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3757 process, return without waiting for the connection to complete;
3758 instead, the sentinel function will be called with second arg matching
3759 "open" (if successful) or "failed" when the connect completes.
3760 Default is to use a blocking connect (i.e. wait) for stream type
3761 connections.
3763 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3764 running when Emacs is exited.
3766 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3767 In the stopped state, a server process does not accept new
3768 connections, and a client process does not handle incoming traffic.
3769 The stopped state is cleared by `continue-process' and set by
3770 `stop-process'.
3772 :filter FILTER -- Install FILTER as the process filter.
3774 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3775 process filter are multibyte, otherwise they are unibyte.
3776 If this keyword is not specified, the strings are multibyte if
3777 the default value of `enable-multibyte-characters' is non-nil.
3779 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3781 :log LOG -- Install LOG as the server process log function. This
3782 function is called when the server accepts a network connection from a
3783 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3784 is the server process, CLIENT is the new process for the connection,
3785 and MESSAGE is a string.
3787 :plist PLIST -- Install PLIST as the new process's initial plist.
3789 :tls-parameters LIST -- is a list that should be supplied if you're
3790 opening a TLS connection. The first element is the TLS type (either
3791 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3792 be a keyword list accepted by gnutls-boot (as returned by
3793 `gnutls-boot-parameters').
3795 :server QLEN -- if QLEN is non-nil, create a server process for the
3796 specified FAMILY, SERVICE, and connection type (stream or datagram).
3797 If QLEN is an integer, it is used as the max. length of the server's
3798 pending connection queue (also known as the backlog); the default
3799 queue length is 5. Default is to create a client process.
3801 The following network options can be specified for this connection:
3803 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3804 :dontroute BOOL -- Only send to directly connected hosts.
3805 :keepalive BOOL -- Send keep-alive messages on network stream.
3806 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3807 :oobinline BOOL -- Place out-of-band data in receive data stream.
3808 :priority INT -- Set protocol defined priority for sent packets.
3809 :reuseaddr BOOL -- Allow reusing a recently used local address
3810 (this is allowed by default for a server process).
3811 :bindtodevice NAME -- bind to interface NAME. Using this may require
3812 special privileges on some systems.
3813 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3814 been passed to Emacs. If Emacs wasn't
3815 passed a socket, this option is silently
3816 ignored.
3819 Consult the relevant system programmer's manual pages for more
3820 information on using these options.
3823 A server process will listen for and accept connections from clients.
3824 When a client connection is accepted, a new network process is created
3825 for the connection with the following parameters:
3827 - The client's process name is constructed by concatenating the server
3828 process's NAME and a client identification string.
3829 - If the FILTER argument is non-nil, the client process will not get a
3830 separate process buffer; otherwise, the client's process buffer is a newly
3831 created buffer named after the server process's BUFFER name or process
3832 NAME concatenated with the client identification string.
3833 - The connection type and the process filter and sentinel parameters are
3834 inherited from the server process's TYPE, FILTER and SENTINEL.
3835 - The client process's contact info is set according to the client's
3836 addressing information (typically an IP address and a port number).
3837 - The client process's plist is initialized from the server's plist.
3839 Notice that the FILTER and SENTINEL args are never used directly by
3840 the server process. Also, the BUFFER argument is not used directly by
3841 the server process, but via the optional :log function, accepted (and
3842 failed) connections may be logged in the server process's buffer.
3844 The original argument list, modified with the actual connection
3845 information, is available via the `process-contact' function.
3847 usage: (make-network-process &rest ARGS) */)
3848 (ptrdiff_t nargs, Lisp_Object *args)
3850 Lisp_Object proc;
3851 Lisp_Object contact;
3852 struct Lisp_Process *p;
3853 const char *portstring UNINIT;
3854 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3855 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3856 #ifdef HAVE_LOCAL_SOCKETS
3857 struct sockaddr_un address_un;
3858 #endif
3859 EMACS_INT port = 0;
3860 Lisp_Object tem;
3861 Lisp_Object name, buffer, host, service, address;
3862 Lisp_Object filter, sentinel, use_external_socket_p;
3863 Lisp_Object addrinfos = Qnil;
3864 int socktype;
3865 int family = -1;
3866 enum { any_protocol = 0 };
3867 #ifdef HAVE_GETADDRINFO_A
3868 struct gaicb *dns_request = NULL;
3869 #endif
3870 ptrdiff_t count = SPECPDL_INDEX ();
3872 if (nargs == 0)
3873 return Qnil;
3875 /* Save arguments for process-contact and clone-process. */
3876 contact = Flist (nargs, args);
3878 #ifdef WINDOWSNT
3879 /* Ensure socket support is loaded if available. */
3880 init_winsock (TRUE);
3881 #endif
3883 /* :type TYPE (nil: stream, datagram */
3884 tem = Fplist_get (contact, QCtype);
3885 if (NILP (tem))
3886 socktype = SOCK_STREAM;
3887 #ifdef DATAGRAM_SOCKETS
3888 else if (EQ (tem, Qdatagram))
3889 socktype = SOCK_DGRAM;
3890 #endif
3891 #ifdef HAVE_SEQPACKET
3892 else if (EQ (tem, Qseqpacket))
3893 socktype = SOCK_SEQPACKET;
3894 #endif
3895 else
3896 error ("Unsupported connection type");
3898 name = Fplist_get (contact, QCname);
3899 buffer = Fplist_get (contact, QCbuffer);
3900 filter = Fplist_get (contact, QCfilter);
3901 sentinel = Fplist_get (contact, QCsentinel);
3902 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3903 Lisp_Object server = Fplist_get (contact, QCserver);
3904 bool nowait = !NILP (Fplist_get (contact, QCnowait));
3906 if (!NILP (server) && nowait)
3907 error ("`:server' is incompatible with `:nowait'");
3908 CHECK_STRING (name);
3910 /* :local ADDRESS or :remote ADDRESS */
3911 if (NILP (server))
3912 address = Fplist_get (contact, QCremote);
3913 else
3914 address = Fplist_get (contact, QClocal);
3915 if (!NILP (address))
3917 host = service = Qnil;
3919 if (!get_lisp_to_sockaddr_size (address, &family))
3920 error ("Malformed :address");
3922 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3923 goto open_socket;
3926 /* :family FAMILY -- nil (for Inet), local, or integer. */
3927 tem = Fplist_get (contact, QCfamily);
3928 if (NILP (tem))
3930 #ifdef AF_INET6
3931 family = AF_UNSPEC;
3932 #else
3933 family = AF_INET;
3934 #endif
3936 #ifdef HAVE_LOCAL_SOCKETS
3937 else if (EQ (tem, Qlocal))
3938 family = AF_LOCAL;
3939 #endif
3940 #ifdef AF_INET6
3941 else if (EQ (tem, Qipv6))
3942 family = AF_INET6;
3943 #endif
3944 else if (EQ (tem, Qipv4))
3945 family = AF_INET;
3946 else if (TYPE_RANGED_INTEGERP (int, tem))
3947 family = XINT (tem);
3948 else
3949 error ("Unknown address family");
3951 /* :service SERVICE -- string, integer (port number), or t (random port). */
3952 service = Fplist_get (contact, QCservice);
3954 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3955 host = Fplist_get (contact, QChost);
3956 if (NILP (host))
3958 /* The "connection" function gets it bind info from the address we're
3959 given, so use this dummy address if nothing is specified. */
3960 #ifdef HAVE_LOCAL_SOCKETS
3961 if (family != AF_LOCAL)
3962 #endif
3963 host = build_string ("127.0.0.1");
3965 else
3967 if (EQ (host, Qlocal))
3968 /* Depending on setup, "localhost" may map to different IPv4 and/or
3969 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3970 host = build_string ("127.0.0.1");
3971 CHECK_STRING (host);
3974 #ifdef HAVE_LOCAL_SOCKETS
3975 if (family == AF_LOCAL)
3977 if (!NILP (host))
3979 message (":family local ignores the :host property");
3980 contact = Fplist_put (contact, QChost, Qnil);
3981 host = Qnil;
3983 CHECK_STRING (service);
3984 if (sizeof address_un.sun_path <= SBYTES (service))
3985 error ("Service name too long");
3986 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3987 goto open_socket;
3989 #endif
3991 /* Slow down polling to every ten seconds.
3992 Some kernels have a bug which causes retrying connect to fail
3993 after a connect. Polling can interfere with gethostbyname too. */
3994 #ifdef POLL_FOR_INPUT
3995 if (socktype != SOCK_DGRAM)
3997 record_unwind_protect_void (run_all_atimers);
3998 bind_polling_period (10);
4000 #endif
4002 if (!NILP (host))
4004 /* SERVICE can either be a string or int.
4005 Convert to a C string for later use by getaddrinfo. */
4006 if (EQ (service, Qt))
4008 portstring = "0";
4009 portstringlen = 1;
4011 else if (INTEGERP (service))
4013 portstring = portbuf;
4014 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
4016 else
4018 CHECK_STRING (service);
4019 portstring = SSDATA (service);
4020 portstringlen = SBYTES (service);
4024 #ifdef HAVE_GETADDRINFO_A
4025 if (!NILP (host) && nowait)
4027 ptrdiff_t hostlen = SBYTES (host);
4028 struct req
4030 struct gaicb gaicb;
4031 struct addrinfo hints;
4032 char str[FLEXIBLE_ARRAY_MEMBER];
4033 } *req = xmalloc (FLEXSIZEOF (struct req, str,
4034 hostlen + 1 + portstringlen + 1));
4035 dns_request = &req->gaicb;
4036 dns_request->ar_name = req->str;
4037 dns_request->ar_service = req->str + hostlen + 1;
4038 dns_request->ar_request = &req->hints;
4039 dns_request->ar_result = NULL;
4040 memset (&req->hints, 0, sizeof req->hints);
4041 req->hints.ai_family = family;
4042 req->hints.ai_socktype = socktype;
4043 strcpy (req->str, SSDATA (host));
4044 strcpy (req->str + hostlen + 1, portstring);
4046 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
4047 if (ret)
4048 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
4050 goto open_socket;
4052 #endif /* HAVE_GETADDRINFO_A */
4054 /* If we have a host, use getaddrinfo to resolve both host and service.
4055 Otherwise, use getservbyname to lookup the service. */
4057 if (!NILP (host))
4059 struct addrinfo *res, *lres;
4060 int ret;
4062 maybe_quit ();
4064 struct addrinfo hints;
4065 memset (&hints, 0, sizeof hints);
4066 hints.ai_family = family;
4067 hints.ai_socktype = socktype;
4069 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
4070 if (ret)
4071 #ifdef HAVE_GAI_STRERROR
4073 synchronize_system_messages_locale ();
4074 char const *str = gai_strerror (ret);
4075 if (! NILP (Vlocale_coding_system))
4076 str = SSDATA (code_convert_string_norecord
4077 (build_string (str), Vlocale_coding_system, 0));
4078 error ("%s/%s %s", SSDATA (host), portstring, str);
4080 #else
4081 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
4082 #endif
4084 for (lres = res; lres; lres = lres->ai_next)
4085 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
4087 addrinfos = Fnreverse (addrinfos);
4089 freeaddrinfo (res);
4091 goto open_socket;
4094 /* No hostname has been specified (e.g., a local server process). */
4096 if (EQ (service, Qt))
4097 port = 0;
4098 else if (INTEGERP (service))
4099 port = XINT (service);
4100 else
4102 CHECK_STRING (service);
4104 port = -1;
4105 if (SBYTES (service) != 0)
4107 /* Allow the service to be a string containing the port number,
4108 because that's allowed if you have getaddrbyname. */
4109 char *service_end;
4110 long int lport = strtol (SSDATA (service), &service_end, 10);
4111 if (service_end == SSDATA (service) + SBYTES (service))
4112 port = lport;
4113 else
4115 struct servent *svc_info
4116 = getservbyname (SSDATA (service),
4117 socktype == SOCK_DGRAM ? "udp" : "tcp");
4118 if (svc_info)
4119 port = ntohs (svc_info->s_port);
4124 if (! (0 <= port && port < 1 << 16))
4126 AUTO_STRING (unknown_service, "Unknown service: %s");
4127 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
4130 open_socket:
4132 if (!NILP (buffer))
4133 buffer = Fget_buffer_create (buffer);
4135 /* Unwind bind_polling_period. */
4136 unbind_to (count, Qnil);
4138 proc = make_process (name);
4139 record_unwind_protect (remove_process, proc);
4140 p = XPROCESS (proc);
4141 pset_childp (p, contact);
4142 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
4143 pset_type (p, Qnetwork);
4145 pset_buffer (p, buffer);
4146 pset_sentinel (p, sentinel);
4147 pset_filter (p, filter);
4148 pset_log (p, Fplist_get (contact, QClog));
4149 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
4150 p->kill_without_query = 1;
4151 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
4152 pset_command (p, Qt);
4153 eassert (p->pid == 0);
4154 p->backlog = 5;
4155 eassert (! p->is_non_blocking_client);
4156 eassert (! p->is_server);
4157 p->port = port;
4158 p->socktype = socktype;
4159 #ifdef HAVE_GETADDRINFO_A
4160 eassert (! p->dns_request);
4161 #endif
4162 #ifdef HAVE_GNUTLS
4163 tem = Fplist_get (contact, QCtls_parameters);
4164 CHECK_LIST (tem);
4165 p->gnutls_boot_parameters = tem;
4166 #endif
4168 set_network_socket_coding_system (proc, host, service, name);
4170 /* :server QLEN */
4171 p->is_server = !NILP (server);
4172 if (TYPE_RANGED_INTEGERP (int, server))
4173 p->backlog = XINT (server);
4175 /* :nowait BOOL */
4176 if (!p->is_server && socktype != SOCK_DGRAM && nowait)
4177 p->is_non_blocking_client = true;
4179 bool postpone_connection = false;
4180 #ifdef HAVE_GETADDRINFO_A
4181 /* With async address resolution, the list of addresses is empty, so
4182 postpone connecting to the server. */
4183 if (!p->is_server && NILP (addrinfos))
4185 p->dns_request = dns_request;
4186 p->status = list1 (Qconnect);
4187 postpone_connection = true;
4189 #endif
4190 if (! postpone_connection)
4191 connect_network_socket (proc, addrinfos, use_external_socket_p);
4193 specpdl_ptr = specpdl + count;
4194 return proc;
4198 #ifdef HAVE_NET_IF_H
4200 #ifdef SIOCGIFCONF
4201 static Lisp_Object
4202 network_interface_list (void)
4204 struct ifconf ifconf;
4205 struct ifreq *ifreq;
4206 void *buf = NULL;
4207 ptrdiff_t buf_size = 512;
4208 int s;
4209 Lisp_Object res;
4210 ptrdiff_t count;
4212 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4213 if (s < 0)
4214 return Qnil;
4215 count = SPECPDL_INDEX ();
4216 record_unwind_protect_int (close_file_unwind, s);
4220 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4221 ifconf.ifc_buf = buf;
4222 ifconf.ifc_len = buf_size;
4223 if (ioctl (s, SIOCGIFCONF, &ifconf))
4225 emacs_close (s);
4226 xfree (buf);
4227 return Qnil;
4230 while (ifconf.ifc_len == buf_size);
4232 res = unbind_to (count, Qnil);
4233 ifreq = ifconf.ifc_req;
4234 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4236 struct ifreq *ifq = ifreq;
4237 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4238 #define SIZEOF_IFREQ(sif) \
4239 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4240 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4242 int len = SIZEOF_IFREQ (ifq);
4243 #else
4244 int len = sizeof (*ifreq);
4245 #endif
4246 char namebuf[sizeof (ifq->ifr_name) + 1];
4247 ifreq = (struct ifreq *) ((char *) ifreq + len);
4249 if (ifq->ifr_addr.sa_family != AF_INET)
4250 continue;
4252 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4253 namebuf[sizeof (ifq->ifr_name)] = 0;
4254 res = Fcons (Fcons (build_string (namebuf),
4255 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4256 sizeof (struct sockaddr))),
4257 res);
4260 xfree (buf);
4261 return res;
4263 #endif /* SIOCGIFCONF */
4265 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4267 struct ifflag_def {
4268 int flag_bit;
4269 const char *flag_sym;
4272 static const struct ifflag_def ifflag_table[] = {
4273 #ifdef IFF_UP
4274 { IFF_UP, "up" },
4275 #endif
4276 #ifdef IFF_BROADCAST
4277 { IFF_BROADCAST, "broadcast" },
4278 #endif
4279 #ifdef IFF_DEBUG
4280 { IFF_DEBUG, "debug" },
4281 #endif
4282 #ifdef IFF_LOOPBACK
4283 { IFF_LOOPBACK, "loopback" },
4284 #endif
4285 #ifdef IFF_POINTOPOINT
4286 { IFF_POINTOPOINT, "pointopoint" },
4287 #endif
4288 #ifdef IFF_RUNNING
4289 { IFF_RUNNING, "running" },
4290 #endif
4291 #ifdef IFF_NOARP
4292 { IFF_NOARP, "noarp" },
4293 #endif
4294 #ifdef IFF_PROMISC
4295 { IFF_PROMISC, "promisc" },
4296 #endif
4297 #ifdef IFF_NOTRAILERS
4298 #ifdef NS_IMPL_COCOA
4299 /* Really means smart, notrailers is obsolete. */
4300 { IFF_NOTRAILERS, "smart" },
4301 #else
4302 { IFF_NOTRAILERS, "notrailers" },
4303 #endif
4304 #endif
4305 #ifdef IFF_ALLMULTI
4306 { IFF_ALLMULTI, "allmulti" },
4307 #endif
4308 #ifdef IFF_MASTER
4309 { IFF_MASTER, "master" },
4310 #endif
4311 #ifdef IFF_SLAVE
4312 { IFF_SLAVE, "slave" },
4313 #endif
4314 #ifdef IFF_MULTICAST
4315 { IFF_MULTICAST, "multicast" },
4316 #endif
4317 #ifdef IFF_PORTSEL
4318 { IFF_PORTSEL, "portsel" },
4319 #endif
4320 #ifdef IFF_AUTOMEDIA
4321 { IFF_AUTOMEDIA, "automedia" },
4322 #endif
4323 #ifdef IFF_DYNAMIC
4324 { IFF_DYNAMIC, "dynamic" },
4325 #endif
4326 #ifdef IFF_OACTIVE
4327 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4328 #endif
4329 #ifdef IFF_SIMPLEX
4330 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4331 #endif
4332 #ifdef IFF_LINK0
4333 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4334 #endif
4335 #ifdef IFF_LINK1
4336 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4337 #endif
4338 #ifdef IFF_LINK2
4339 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4340 #endif
4341 { 0, 0 }
4344 static Lisp_Object
4345 network_interface_info (Lisp_Object ifname)
4347 struct ifreq rq;
4348 Lisp_Object res = Qnil;
4349 Lisp_Object elt;
4350 int s;
4351 bool any = 0;
4352 ptrdiff_t count;
4353 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4354 && defined HAVE_GETIFADDRS && defined LLADDR)
4355 struct ifaddrs *ifap;
4356 #endif
4358 CHECK_STRING (ifname);
4360 if (sizeof rq.ifr_name <= SBYTES (ifname))
4361 error ("interface name too long");
4362 lispstpcpy (rq.ifr_name, ifname);
4364 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4365 if (s < 0)
4366 return Qnil;
4367 count = SPECPDL_INDEX ();
4368 record_unwind_protect_int (close_file_unwind, s);
4370 elt = Qnil;
4371 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4372 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4374 int flags = rq.ifr_flags;
4375 const struct ifflag_def *fp;
4376 int fnum;
4378 /* If flags is smaller than int (i.e. short) it may have the high bit set
4379 due to IFF_MULTICAST. In that case, sign extending it into
4380 an int is wrong. */
4381 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4382 flags = (unsigned short) rq.ifr_flags;
4384 any = 1;
4385 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4387 if (flags & fp->flag_bit)
4389 elt = Fcons (intern (fp->flag_sym), elt);
4390 flags -= fp->flag_bit;
4393 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4395 if (flags & 1)
4397 elt = Fcons (make_number (fnum), elt);
4401 #endif
4402 res = Fcons (elt, res);
4404 elt = Qnil;
4405 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4406 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4408 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4409 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4410 int n;
4412 any = 1;
4413 for (n = 0; n < 6; n++)
4414 p->contents[n] = make_number (((unsigned char *)
4415 &rq.ifr_hwaddr.sa_data[0])
4416 [n]);
4417 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4419 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4420 if (getifaddrs (&ifap) != -1)
4422 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4423 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4424 struct ifaddrs *it;
4426 for (it = ifap; it != NULL; it = it->ifa_next)
4428 DECLARE_POINTER_ALIAS (sdl, struct sockaddr_dl, it->ifa_addr);
4429 unsigned char linkaddr[6];
4430 int n;
4432 if (it->ifa_addr->sa_family != AF_LINK
4433 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4434 || sdl->sdl_alen != 6)
4435 continue;
4437 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4438 for (n = 0; n < 6; n++)
4439 p->contents[n] = make_number (linkaddr[n]);
4441 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4442 break;
4445 #ifdef HAVE_FREEIFADDRS
4446 freeifaddrs (ifap);
4447 #endif
4449 #endif /* HAVE_GETIFADDRS && LLADDR */
4451 res = Fcons (elt, res);
4453 elt = Qnil;
4454 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4455 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4457 any = 1;
4458 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4459 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4460 #else
4461 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4462 #endif
4464 #endif
4465 res = Fcons (elt, res);
4467 elt = Qnil;
4468 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4469 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4471 any = 1;
4472 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4474 #endif
4475 res = Fcons (elt, res);
4477 elt = Qnil;
4478 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4479 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4481 any = 1;
4482 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4484 #endif
4485 res = Fcons (elt, res);
4487 return unbind_to (count, any ? res : Qnil);
4489 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4490 #endif /* defined (HAVE_NET_IF_H) */
4492 DEFUN ("network-interface-list", Fnetwork_interface_list,
4493 Snetwork_interface_list, 0, 0, 0,
4494 doc: /* Return an alist of all network interfaces and their network address.
4495 Each element is a cons, the car of which is a string containing the
4496 interface name, and the cdr is the network address in internal
4497 format; see the description of ADDRESS in `make-network-process'.
4499 If the information is not available, return nil. */)
4500 (void)
4502 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4503 return network_interface_list ();
4504 #else
4505 return Qnil;
4506 #endif
4509 DEFUN ("network-interface-info", Fnetwork_interface_info,
4510 Snetwork_interface_info, 1, 1, 0,
4511 doc: /* Return information about network interface named IFNAME.
4512 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4513 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4514 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4515 FLAGS is the current flags of the interface.
4517 Data that is unavailable is returned as nil. */)
4518 (Lisp_Object ifname)
4520 #if ((defined HAVE_NET_IF_H \
4521 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4522 || defined SIOCGIFFLAGS)) \
4523 || defined WINDOWSNT)
4524 return network_interface_info (ifname);
4525 #else
4526 return Qnil;
4527 #endif
4530 /* Turn off input and output for process PROC. */
4532 static void
4533 deactivate_process (Lisp_Object proc)
4535 int inchannel;
4536 struct Lisp_Process *p = XPROCESS (proc);
4537 int i;
4539 #ifdef HAVE_GNUTLS
4540 /* Delete GnuTLS structures in PROC, if any. */
4541 emacs_gnutls_deinit (proc);
4542 #endif /* HAVE_GNUTLS */
4544 if (p->read_output_delay > 0)
4546 if (--process_output_delay_count < 0)
4547 process_output_delay_count = 0;
4548 p->read_output_delay = 0;
4549 p->read_output_skip = 0;
4552 /* Beware SIGCHLD hereabouts. */
4554 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4555 close_process_fd (&p->open_fd[i]);
4557 inchannel = p->infd;
4558 if (inchannel >= 0)
4560 p->infd = -1;
4561 p->outfd = -1;
4562 #ifdef DATAGRAM_SOCKETS
4563 if (DATAGRAM_CHAN_P (inchannel))
4565 xfree (datagram_address[inchannel].sa);
4566 datagram_address[inchannel].sa = 0;
4567 datagram_address[inchannel].len = 0;
4569 #endif
4570 chan_process[inchannel] = Qnil;
4571 delete_read_fd (inchannel);
4572 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4573 delete_write_fd (inchannel);
4574 if (inchannel == max_desc)
4575 recompute_max_desc ();
4580 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4581 0, 4, 0,
4582 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4583 It is given to their filter functions.
4584 Optional argument PROCESS means to return only after output is
4585 received from PROCESS or PROCESS closes the connection.
4587 Optional second argument SECONDS and third argument MILLISEC
4588 specify a timeout; return after that much time even if there is
4589 no subprocess output. If SECONDS is a floating point number,
4590 it specifies a fractional number of seconds to wait.
4591 The MILLISEC argument is obsolete and should be avoided.
4593 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4594 from PROCESS only, suspending reading output from other processes.
4595 If JUST-THIS-ONE is an integer, don't run any timers either.
4596 Return non-nil if we received any output from PROCESS (or, if PROCESS
4597 is nil, from any process) before the timeout expired or the
4598 corresponding connection was closed. */)
4599 (Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec,
4600 Lisp_Object just_this_one)
4602 intmax_t secs;
4603 int nsecs;
4605 if (! NILP (process))
4607 CHECK_PROCESS (process);
4608 struct Lisp_Process *proc = XPROCESS (process);
4610 /* Can't wait for a process that is dedicated to a different
4611 thread. */
4612 if (!EQ (proc->thread, Qnil) && !EQ (proc->thread, Fcurrent_thread ()))
4614 Lisp_Object proc_thread_name = XTHREAD (proc->thread)->name;
4616 error ("Attempt to accept output from process %s locked to thread %s",
4617 SDATA (proc->name),
4618 STRINGP (proc_thread_name)
4619 ? SDATA (proc_thread_name)
4620 : SDATA (Fprin1_to_string (proc->thread, Qt)));
4623 else
4624 just_this_one = Qnil;
4626 if (!NILP (millisec))
4627 { /* Obsolete calling convention using integers rather than floats. */
4628 CHECK_NUMBER (millisec);
4629 if (NILP (seconds))
4630 seconds = make_float (XINT (millisec) / 1000.0);
4631 else
4633 CHECK_NUMBER (seconds);
4634 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4638 secs = 0;
4639 nsecs = -1;
4641 if (!NILP (seconds))
4643 if (INTEGERP (seconds))
4645 if (XINT (seconds) > 0)
4647 secs = XINT (seconds);
4648 nsecs = 0;
4651 else if (FLOATP (seconds))
4653 if (XFLOAT_DATA (seconds) > 0)
4655 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4656 secs = min (t.tv_sec, WAIT_READING_MAX);
4657 nsecs = t.tv_nsec;
4660 else
4661 wrong_type_argument (Qnumberp, seconds);
4663 else if (! NILP (process))
4664 nsecs = 0;
4666 return
4667 ((wait_reading_process_output (secs, nsecs, 0, 0,
4668 Qnil,
4669 !NILP (process) ? XPROCESS (process) : NULL,
4670 (NILP (just_this_one) ? 0
4671 : !INTEGERP (just_this_one) ? 1 : -1))
4672 <= 0)
4673 ? Qnil : Qt);
4676 /* Accept a connection for server process SERVER on CHANNEL. */
4678 static EMACS_INT connect_counter = 0;
4680 static void
4681 server_accept_connection (Lisp_Object server, int channel)
4683 Lisp_Object buffer;
4684 Lisp_Object contact, host, service;
4685 struct Lisp_Process *ps = XPROCESS (server);
4686 struct Lisp_Process *p;
4687 int s;
4688 union u_sockaddr {
4689 struct sockaddr sa;
4690 struct sockaddr_in in;
4691 #ifdef AF_INET6
4692 struct sockaddr_in6 in6;
4693 #endif
4694 #ifdef HAVE_LOCAL_SOCKETS
4695 struct sockaddr_un un;
4696 #endif
4697 } saddr;
4698 socklen_t len = sizeof saddr;
4699 ptrdiff_t count;
4701 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4703 if (s < 0)
4705 int code = errno;
4706 if (!would_block (code) && !NILP (ps->log))
4707 call3 (ps->log, server, Qnil,
4708 concat3 (build_string ("accept failed with code"),
4709 Fnumber_to_string (make_number (code)),
4710 build_string ("\n")));
4711 return;
4714 count = SPECPDL_INDEX ();
4715 record_unwind_protect_int (close_file_unwind, s);
4717 connect_counter++;
4719 /* Setup a new process to handle the connection. */
4721 /* Generate a unique identification of the caller, and build contact
4722 information for this process. */
4723 host = Qt;
4724 service = Qnil;
4725 Lisp_Object args[11];
4726 int nargs = 0;
4727 #define HOST_FORMAT_IN "%d.%d.%d.%d"
4728 #define HOST_FORMAT_IN6 "%x:%x:%x:%x:%x:%x:%x:%x"
4729 AUTO_STRING (host_format_in, HOST_FORMAT_IN);
4730 AUTO_STRING (host_format_in6, HOST_FORMAT_IN6);
4731 AUTO_STRING (procname_format_in, "%s <"HOST_FORMAT_IN":%d>");
4732 AUTO_STRING (procname_format_in6, "%s <["HOST_FORMAT_IN6"]:%d>");
4733 AUTO_STRING (procname_format_default, "%s <%d>");
4734 switch (saddr.sa.sa_family)
4736 case AF_INET:
4738 args[nargs++] = procname_format_in;
4739 args[nargs++] = host_format_in;
4740 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4741 service = make_number (ntohs (saddr.in.sin_port));
4742 for (int i = 0; i < 4; i++)
4743 args[nargs++] = make_number (ip[i]);
4744 host = Fformat (5, args + 1);
4745 args[nargs++] = service;
4747 break;
4749 #ifdef AF_INET6
4750 case AF_INET6:
4752 args[nargs++] = procname_format_in6;
4753 args[nargs++] = host_format_in6;
4754 DECLARE_POINTER_ALIAS (ip6, uint16_t, &saddr.in6.sin6_addr);
4755 service = make_number (ntohs (saddr.in.sin_port));
4756 for (int i = 0; i < 8; i++)
4757 args[nargs++] = make_number (ip6[i]);
4758 host = Fformat (9, args + 1);
4759 args[nargs++] = service;
4761 break;
4762 #endif
4764 default:
4765 args[nargs++] = procname_format_default;
4766 nargs++;
4767 args[nargs++] = make_number (connect_counter);
4768 break;
4771 /* Create a new buffer name for this process if it doesn't have a
4772 filter. The new buffer name is based on the buffer name or
4773 process name of the server process concatenated with the caller
4774 identification. */
4776 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4777 || EQ (ps->filter, Qt)))
4778 buffer = Qnil;
4779 else
4781 buffer = ps->buffer;
4782 if (!NILP (buffer))
4783 buffer = Fbuffer_name (buffer);
4784 else
4785 buffer = ps->name;
4786 if (!NILP (buffer))
4788 args[1] = buffer;
4789 buffer = Fget_buffer_create (Fformat (nargs, args));
4793 /* Generate a unique name for the new server process. Combine the
4794 server process name with the caller identification. */
4796 args[1] = ps->name;
4797 Lisp_Object name = Fformat (nargs, args);
4798 Lisp_Object proc = make_process (name);
4800 chan_process[s] = proc;
4802 fcntl (s, F_SETFL, O_NONBLOCK);
4804 p = XPROCESS (proc);
4806 /* Build new contact information for this setup. */
4807 contact = Fcopy_sequence (ps->childp);
4808 contact = Fplist_put (contact, QCserver, Qnil);
4809 contact = Fplist_put (contact, QChost, host);
4810 if (!NILP (service))
4811 contact = Fplist_put (contact, QCservice, service);
4812 contact = Fplist_put (contact, QCremote,
4813 conv_sockaddr_to_lisp (&saddr.sa, len));
4814 #ifdef HAVE_GETSOCKNAME
4815 len = sizeof saddr;
4816 if (getsockname (s, &saddr.sa, &len) == 0)
4817 contact = Fplist_put (contact, QClocal,
4818 conv_sockaddr_to_lisp (&saddr.sa, len));
4819 #endif
4821 pset_childp (p, contact);
4822 pset_plist (p, Fcopy_sequence (ps->plist));
4823 pset_type (p, Qnetwork);
4825 pset_buffer (p, buffer);
4826 pset_sentinel (p, ps->sentinel);
4827 pset_filter (p, ps->filter);
4828 eassert (NILP (p->command));
4829 eassert (p->pid == 0);
4831 /* Discard the unwind protect for closing S. */
4832 specpdl_ptr = specpdl + count;
4834 p->open_fd[SUBPROCESS_STDIN] = s;
4835 p->infd = s;
4836 p->outfd = s;
4837 pset_status (p, Qrun);
4839 /* Client processes for accepted connections are not stopped initially. */
4840 if (!EQ (p->filter, Qt))
4841 add_process_read_fd (s);
4842 if (s > max_desc)
4843 max_desc = s;
4845 /* Setup coding system for new process based on server process.
4846 This seems to be the proper thing to do, as the coding system
4847 of the new process should reflect the settings at the time the
4848 server socket was opened; not the current settings. */
4850 pset_decode_coding_system (p, ps->decode_coding_system);
4851 pset_encode_coding_system (p, ps->encode_coding_system);
4852 setup_process_coding_systems (proc);
4854 pset_decoding_buf (p, empty_unibyte_string);
4855 eassert (p->decoding_carryover == 0);
4856 pset_encoding_buf (p, empty_unibyte_string);
4858 p->inherit_coding_system_flag
4859 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4861 AUTO_STRING (dash, "-");
4862 AUTO_STRING (nl, "\n");
4863 Lisp_Object host_string = STRINGP (host) ? host : dash;
4865 if (!NILP (ps->log))
4867 AUTO_STRING (accept_from, "accept from ");
4868 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4871 AUTO_STRING (open_from, "open from ");
4872 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4875 #ifdef HAVE_GETADDRINFO_A
4876 static Lisp_Object
4877 check_for_dns (Lisp_Object proc)
4879 struct Lisp_Process *p = XPROCESS (proc);
4880 Lisp_Object addrinfos = Qnil;
4882 /* Sanity check. */
4883 if (! p->dns_request)
4884 return Qnil;
4886 int ret = gai_error (p->dns_request);
4887 if (ret == EAI_INPROGRESS)
4888 return Qt;
4890 /* We got a response. */
4891 if (ret == 0)
4893 struct addrinfo *res;
4895 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4896 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4898 addrinfos = Fnreverse (addrinfos);
4900 /* The DNS lookup failed. */
4901 else if (connecting_status (p->status))
4903 deactivate_process (proc);
4904 pset_status (p, (list2
4905 (Qfailed,
4906 concat3 (build_string ("Name lookup of "),
4907 build_string (p->dns_request->ar_name),
4908 build_string (" failed")))));
4911 free_dns_request (proc);
4913 /* This process should not already be connected (or killed). */
4914 if (! connecting_status (p->status))
4915 return Qnil;
4917 return addrinfos;
4920 #endif /* HAVE_GETADDRINFO_A */
4922 static void
4923 wait_for_socket_fds (Lisp_Object process, char const *name)
4925 while (XPROCESS (process)->infd < 0
4926 && connecting_status (XPROCESS (process)->status))
4928 add_to_log ("Waiting for socket from %s...", build_string (name));
4929 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4933 static void
4934 wait_while_connecting (Lisp_Object process)
4936 while (connecting_status (XPROCESS (process)->status))
4938 add_to_log ("Waiting for connection...");
4939 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4943 static void
4944 wait_for_tls_negotiation (Lisp_Object process)
4946 #ifdef HAVE_GNUTLS
4947 while (XPROCESS (process)->gnutls_p
4948 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4950 add_to_log ("Waiting for TLS...");
4951 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4953 #endif
4956 static void
4957 wait_reading_process_output_unwind (int data)
4959 clear_waiting_thread_info ();
4960 waiting_for_user_input_p = data;
4963 /* This is here so breakpoints can be put on it. */
4964 static void
4965 wait_reading_process_output_1 (void)
4969 /* Read and dispose of subprocess output while waiting for timeout to
4970 elapse and/or keyboard input to be available.
4972 TIME_LIMIT is:
4973 timeout in seconds
4974 If negative, gobble data immediately available but don't wait for any.
4976 NSECS is:
4977 an additional duration to wait, measured in nanoseconds
4978 If TIME_LIMIT is zero, then:
4979 If NSECS == 0, there is no limit.
4980 If NSECS > 0, the timeout consists of NSECS only.
4981 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4983 READ_KBD is:
4984 0 to ignore keyboard input, or
4985 1 to return when input is available, or
4986 -1 meaning caller will actually read the input, so don't throw to
4987 the quit handler
4989 DO_DISPLAY means redisplay should be done to show subprocess
4990 output that arrives.
4992 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4993 (and gobble terminal input into the buffer if any arrives).
4995 If WAIT_PROC is specified, wait until something arrives from that
4996 process.
4998 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4999 (suspending output from other processes). A negative value
5000 means don't run any timers either.
5002 Return positive if we received input from WAIT_PROC (or from any
5003 process if WAIT_PROC is null), zero if we attempted to receive
5004 input but got none, and negative if we didn't even try. */
5007 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
5008 bool do_display,
5009 Lisp_Object wait_for_cell,
5010 struct Lisp_Process *wait_proc, int just_wait_proc)
5012 int channel, nfds;
5013 fd_set Available;
5014 fd_set Writeok;
5015 bool check_write;
5016 int check_delay;
5017 bool no_avail;
5018 int xerrno;
5019 Lisp_Object proc;
5020 struct timespec timeout, end_time, timer_delay;
5021 struct timespec got_output_end_time = invalid_timespec ();
5022 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
5023 int got_some_output = -1;
5024 uintmax_t prev_wait_proc_nbytes_read = wait_proc ? wait_proc->nbytes_read : 0;
5025 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5026 bool retry_for_async;
5027 #endif
5028 ptrdiff_t count = SPECPDL_INDEX ();
5030 /* Close to the current time if known, an invalid timespec otherwise. */
5031 struct timespec now = invalid_timespec ();
5033 eassert (wait_proc == NULL
5034 || EQ (wait_proc->thread, Qnil)
5035 || XTHREAD (wait_proc->thread) == current_thread);
5037 FD_ZERO (&Available);
5038 FD_ZERO (&Writeok);
5040 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
5041 && !(CONSP (wait_proc->status)
5042 && EQ (XCAR (wait_proc->status), Qexit)))
5043 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5045 record_unwind_protect_int (wait_reading_process_output_unwind,
5046 waiting_for_user_input_p);
5047 waiting_for_user_input_p = read_kbd;
5049 if (TYPE_MAXIMUM (time_t) < time_limit)
5050 time_limit = TYPE_MAXIMUM (time_t);
5052 if (time_limit < 0 || nsecs < 0)
5053 wait = MINIMUM;
5054 else if (time_limit > 0 || nsecs > 0)
5056 wait = TIMEOUT;
5057 now = current_timespec ();
5058 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
5060 else
5061 wait = INFINITY;
5063 while (1)
5065 bool process_skipped = false;
5067 /* If calling from keyboard input, do not quit
5068 since we want to return C-g as an input character.
5069 Otherwise, do pending quit if requested. */
5070 if (read_kbd >= 0)
5071 maybe_quit ();
5072 else if (pending_signals)
5073 process_pending_signals ();
5075 /* Exit now if the cell we're waiting for became non-nil. */
5076 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5077 break;
5079 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5081 Lisp_Object process_list_head, aproc;
5082 struct Lisp_Process *p;
5084 retry_for_async = false;
5085 FOR_EACH_PROCESS(process_list_head, aproc)
5087 p = XPROCESS (aproc);
5089 if (! wait_proc || p == wait_proc)
5091 #ifdef HAVE_GETADDRINFO_A
5092 /* Check for pending DNS requests. */
5093 if (p->dns_request)
5095 Lisp_Object addrinfos = check_for_dns (aproc);
5096 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
5097 connect_network_socket (aproc, addrinfos, Qnil);
5098 else
5099 retry_for_async = true;
5101 #endif
5102 #ifdef HAVE_GNUTLS
5103 /* Continue TLS negotiation. */
5104 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
5105 && p->is_non_blocking_client)
5107 gnutls_try_handshake (p);
5108 p->gnutls_handshakes_tried++;
5110 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
5112 gnutls_verify_boot (aproc, Qnil);
5113 finish_after_tls_connection (aproc);
5115 else
5117 retry_for_async = true;
5118 if (p->gnutls_handshakes_tried
5119 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
5121 deactivate_process (aproc);
5122 pset_status (p, list2 (Qfailed,
5123 build_string ("TLS negotiation failed")));
5127 #endif
5131 #endif /* GETADDRINFO_A or GNUTLS */
5133 /* Compute time from now till when time limit is up. */
5134 /* Exit if already run out. */
5135 if (wait == TIMEOUT)
5137 if (!timespec_valid_p (now))
5138 now = current_timespec ();
5139 if (timespec_cmp (end_time, now) <= 0)
5140 break;
5141 timeout = timespec_sub (end_time, now);
5143 else
5144 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
5146 /* Normally we run timers here.
5147 But not if wait_for_cell; in those cases,
5148 the wait is supposed to be short,
5149 and those callers cannot handle running arbitrary Lisp code here. */
5150 if (NILP (wait_for_cell)
5151 && just_wait_proc >= 0)
5155 unsigned old_timers_run = timers_run;
5156 struct buffer *old_buffer = current_buffer;
5157 Lisp_Object old_window = selected_window;
5159 timer_delay = timer_check ();
5161 /* If a timer has run, this might have changed buffers
5162 an alike. Make read_key_sequence aware of that. */
5163 if (timers_run != old_timers_run
5164 && (old_buffer != current_buffer
5165 || !EQ (old_window, selected_window))
5166 && waiting_for_user_input_p == -1)
5167 record_asynch_buffer_change ();
5169 if (timers_run != old_timers_run && do_display)
5170 /* We must retry, since a timer may have requeued itself
5171 and that could alter the time_delay. */
5172 redisplay_preserve_echo_area (9);
5173 else
5174 break;
5176 while (!detect_input_pending ());
5178 /* If there is unread keyboard input, also return. */
5179 if (read_kbd != 0
5180 && requeued_events_pending_p ())
5181 break;
5183 /* This is so a breakpoint can be put here. */
5184 if (!timespec_valid_p (timer_delay))
5185 wait_reading_process_output_1 ();
5188 /* Cause C-g and alarm signals to take immediate action,
5189 and cause input available signals to zero out timeout.
5191 It is important that we do this before checking for process
5192 activity. If we get a SIGCHLD after the explicit checks for
5193 process activity, timeout is the only way we will know. */
5194 if (read_kbd < 0)
5195 set_waiting_for_input (&timeout);
5197 /* If status of something has changed, and no input is
5198 available, notify the user of the change right away. After
5199 this explicit check, we'll let the SIGCHLD handler zap
5200 timeout to get our attention. */
5201 if (update_tick != process_tick)
5203 fd_set Atemp;
5204 fd_set Ctemp;
5206 if (kbd_on_hold_p ())
5207 FD_ZERO (&Atemp);
5208 else
5209 compute_input_wait_mask (&Atemp);
5210 compute_write_mask (&Ctemp);
5212 timeout = make_timespec (0, 0);
5213 if ((thread_select (pselect, max_desc + 1,
5214 &Atemp,
5215 (num_pending_connects > 0 ? &Ctemp : NULL),
5216 NULL, &timeout, NULL)
5217 <= 0))
5219 /* It's okay for us to do this and then continue with
5220 the loop, since timeout has already been zeroed out. */
5221 clear_waiting_for_input ();
5222 got_some_output = status_notify (NULL, wait_proc);
5223 if (do_display) redisplay_preserve_echo_area (13);
5227 /* Don't wait for output from a non-running process. Just
5228 read whatever data has already been received. */
5229 if (wait_proc && wait_proc->raw_status_new)
5230 update_status (wait_proc);
5231 if (wait_proc
5232 && ! EQ (wait_proc->status, Qrun)
5233 && ! connecting_status (wait_proc->status))
5235 bool read_some_bytes = false;
5237 clear_waiting_for_input ();
5239 /* If data can be read from the process, do so until exhausted. */
5240 if (wait_proc->infd >= 0)
5242 XSETPROCESS (proc, wait_proc);
5244 while (true)
5246 int nread = read_process_output (proc, wait_proc->infd);
5247 if (nread < 0)
5249 if (errno == EIO || would_block (errno))
5250 break;
5252 else
5254 if (got_some_output < nread)
5255 got_some_output = nread;
5256 if (nread == 0)
5257 break;
5258 read_some_bytes = true;
5263 if (read_some_bytes && do_display)
5264 redisplay_preserve_echo_area (10);
5266 break;
5269 /* Wait till there is something to do. */
5271 if (wait_proc && just_wait_proc)
5273 if (wait_proc->infd < 0) /* Terminated. */
5274 break;
5275 FD_SET (wait_proc->infd, &Available);
5276 check_delay = 0;
5277 check_write = 0;
5279 else if (!NILP (wait_for_cell))
5281 compute_non_process_wait_mask (&Available);
5282 check_delay = 0;
5283 check_write = 0;
5285 else
5287 if (! read_kbd)
5288 compute_non_keyboard_wait_mask (&Available);
5289 else
5290 compute_input_wait_mask (&Available);
5291 compute_write_mask (&Writeok);
5292 check_delay = wait_proc ? 0 : process_output_delay_count;
5293 check_write = true;
5296 /* If frame size has changed or the window is newly mapped,
5297 redisplay now, before we start to wait. There is a race
5298 condition here; if a SIGIO arrives between now and the select
5299 and indicates that a frame is trashed, the select may block
5300 displaying a trashed screen. */
5301 if (frame_garbaged && do_display)
5303 clear_waiting_for_input ();
5304 redisplay_preserve_echo_area (11);
5305 if (read_kbd < 0)
5306 set_waiting_for_input (&timeout);
5309 /* Skip the `select' call if input is available and we're
5310 waiting for keyboard input or a cell change (which can be
5311 triggered by processing X events). In the latter case, set
5312 nfds to 1 to avoid breaking the loop. */
5313 no_avail = 0;
5314 if ((read_kbd || !NILP (wait_for_cell))
5315 && detect_input_pending ())
5317 nfds = read_kbd ? 0 : 1;
5318 no_avail = 1;
5319 FD_ZERO (&Available);
5321 else
5323 /* Set the timeout for adaptive read buffering if any
5324 process has non-zero read_output_skip and non-zero
5325 read_output_delay, and we are not reading output for a
5326 specific process. It is not executed if
5327 Vprocess_adaptive_read_buffering is nil. */
5328 if (process_output_skip && check_delay > 0)
5330 int adaptive_nsecs = timeout.tv_nsec;
5331 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5332 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5333 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
5335 proc = chan_process[channel];
5336 if (NILP (proc))
5337 continue;
5338 /* Find minimum non-zero read_output_delay among the
5339 processes with non-zero read_output_skip. */
5340 if (XPROCESS (proc)->read_output_delay > 0)
5342 check_delay--;
5343 if (!XPROCESS (proc)->read_output_skip)
5344 continue;
5345 FD_CLR (channel, &Available);
5346 process_skipped = true;
5347 XPROCESS (proc)->read_output_skip = 0;
5348 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5349 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5352 timeout = make_timespec (0, adaptive_nsecs);
5353 process_output_skip = 0;
5356 /* If we've got some output and haven't limited our timeout
5357 with adaptive read buffering, limit it. */
5358 if (got_some_output > 0 && !process_skipped
5359 && (timeout.tv_sec
5360 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5361 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5364 if (NILP (wait_for_cell) && just_wait_proc >= 0
5365 && timespec_valid_p (timer_delay)
5366 && timespec_cmp (timer_delay, timeout) < 0)
5368 if (!timespec_valid_p (now))
5369 now = current_timespec ();
5370 struct timespec timeout_abs = timespec_add (now, timeout);
5371 if (!timespec_valid_p (got_output_end_time)
5372 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5373 got_output_end_time = timeout_abs;
5374 timeout = timer_delay;
5376 else
5377 got_output_end_time = invalid_timespec ();
5379 /* NOW can become inaccurate if time can pass during pselect. */
5380 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5381 now = invalid_timespec ();
5383 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5384 if (retry_for_async
5385 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5387 timeout.tv_sec = 0;
5388 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5390 #endif
5392 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5393 #if defined HAVE_GLIB && !defined HAVE_NS
5394 nfds = xg_select (max_desc + 1,
5395 &Available, (check_write ? &Writeok : 0),
5396 NULL, &timeout, NULL);
5397 #elif defined HAVE_NS
5398 /* And NS builds call thread_select in ns_select. */
5399 nfds = ns_select (max_desc + 1,
5400 &Available, (check_write ? &Writeok : 0),
5401 NULL, &timeout, NULL);
5402 #else /* !HAVE_GLIB */
5403 nfds = thread_select (pselect, max_desc + 1,
5404 &Available,
5405 (check_write ? &Writeok : 0),
5406 NULL, &timeout, NULL);
5407 #endif /* !HAVE_GLIB */
5409 #ifdef HAVE_GNUTLS
5410 /* GnuTLS buffers data internally. In lowat mode it leaves
5411 some data in the TCP buffers so that select works, but
5412 with custom pull/push functions we need to check if some
5413 data is available in the buffers manually. */
5414 if (nfds == 0)
5416 fd_set tls_available;
5417 int set = 0;
5419 FD_ZERO (&tls_available);
5420 if (! wait_proc)
5422 /* We're not waiting on a specific process, so loop
5423 through all the channels and check for data.
5424 This is a workaround needed for some versions of
5425 the gnutls library -- 2.12.14 has been confirmed
5426 to need it. See
5427 http://comments.gmane.org/gmane.emacs.devel/145074 */
5428 for (channel = 0; channel < FD_SETSIZE; ++channel)
5429 if (! NILP (chan_process[channel]))
5431 struct Lisp_Process *p =
5432 XPROCESS (chan_process[channel]);
5433 if (p && p->gnutls_p && p->gnutls_state
5434 && ((emacs_gnutls_record_check_pending
5435 (p->gnutls_state))
5436 > 0))
5438 nfds++;
5439 eassert (p->infd == channel);
5440 FD_SET (p->infd, &tls_available);
5441 set++;
5445 else
5447 /* Check this specific channel. */
5448 if (wait_proc->gnutls_p /* Check for valid process. */
5449 && wait_proc->gnutls_state
5450 /* Do we have pending data? */
5451 && ((emacs_gnutls_record_check_pending
5452 (wait_proc->gnutls_state))
5453 > 0))
5455 nfds = 1;
5456 eassert (0 <= wait_proc->infd);
5457 /* Set to Available. */
5458 FD_SET (wait_proc->infd, &tls_available);
5459 set++;
5462 if (set)
5463 Available = tls_available;
5465 #endif
5468 xerrno = errno;
5470 /* Make C-g and alarm signals set flags again. */
5471 clear_waiting_for_input ();
5473 /* If we woke up due to SIGWINCH, actually change size now. */
5474 do_pending_window_change (0);
5476 if (nfds == 0)
5478 /* Exit the main loop if we've passed the requested timeout,
5479 or have read some bytes from our wait_proc (either directly
5480 in this call or indirectly through timers / process filters),
5481 or aren't skipping processes and got some output and
5482 haven't lowered our timeout due to timers or SIGIO and
5483 have waited a long amount of time due to repeated
5484 timers. */
5485 struct timespec huge_timespec
5486 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5487 struct timespec cmp_time = huge_timespec;
5488 if (wait < TIMEOUT
5489 || (wait_proc
5490 && wait_proc->nbytes_read != prev_wait_proc_nbytes_read))
5491 break;
5492 if (wait == TIMEOUT)
5493 cmp_time = end_time;
5494 if (!process_skipped && got_some_output > 0
5495 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5497 if (!timespec_valid_p (got_output_end_time))
5498 break;
5499 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5500 cmp_time = got_output_end_time;
5502 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5504 now = current_timespec ();
5505 if (timespec_cmp (cmp_time, now) <= 0)
5506 break;
5510 if (nfds < 0)
5512 if (xerrno == EINTR)
5513 no_avail = 1;
5514 else if (xerrno == EBADF)
5515 emacs_abort ();
5516 else
5517 report_file_errno ("Failed select", Qnil, xerrno);
5520 /* Check for keyboard input. */
5521 /* If there is any, return immediately
5522 to give it higher priority than subprocesses. */
5524 if (read_kbd != 0)
5526 unsigned old_timers_run = timers_run;
5527 struct buffer *old_buffer = current_buffer;
5528 Lisp_Object old_window = selected_window;
5529 bool leave = false;
5531 if (detect_input_pending_run_timers (do_display))
5533 swallow_events (do_display);
5534 if (detect_input_pending_run_timers (do_display))
5535 leave = true;
5538 /* If a timer has run, this might have changed buffers
5539 an alike. Make read_key_sequence aware of that. */
5540 if (timers_run != old_timers_run
5541 && waiting_for_user_input_p == -1
5542 && (old_buffer != current_buffer
5543 || !EQ (old_window, selected_window)))
5544 record_asynch_buffer_change ();
5546 if (leave)
5547 break;
5550 /* If there is unread keyboard input, also return. */
5551 if (read_kbd != 0
5552 && requeued_events_pending_p ())
5553 break;
5555 /* If we are not checking for keyboard input now,
5556 do process events (but don't run any timers).
5557 This is so that X events will be processed.
5558 Otherwise they may have to wait until polling takes place.
5559 That would causes delays in pasting selections, for example.
5561 (We used to do this only if wait_for_cell.) */
5562 if (read_kbd == 0 && detect_input_pending ())
5564 swallow_events (do_display);
5565 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5566 if (detect_input_pending ())
5567 break;
5568 #endif
5571 /* Exit now if the cell we're waiting for became non-nil. */
5572 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5573 break;
5575 #ifdef USABLE_SIGIO
5576 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5577 go read it. This can happen with X on BSD after logging out.
5578 In that case, there really is no input and no SIGIO,
5579 but select says there is input. */
5581 if (read_kbd && interrupt_input
5582 && keyboard_bit_set (&Available) && ! noninteractive)
5583 handle_input_available_signal (SIGIO);
5584 #endif
5586 /* If checking input just got us a size-change event from X,
5587 obey it now if we should. */
5588 if (read_kbd || ! NILP (wait_for_cell))
5589 do_pending_window_change (0);
5591 /* Check for data from a process. */
5592 if (no_avail || nfds == 0)
5593 continue;
5595 for (channel = 0; channel <= max_desc; ++channel)
5597 struct fd_callback_data *d = &fd_callback_info[channel];
5598 if (d->func
5599 && ((d->flags & FOR_READ
5600 && FD_ISSET (channel, &Available))
5601 || ((d->flags & FOR_WRITE)
5602 && FD_ISSET (channel, &Writeok))))
5603 d->func (channel, d->data);
5606 for (channel = 0; channel <= max_desc; channel++)
5608 if (FD_ISSET (channel, &Available)
5609 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
5610 == PROCESS_FD))
5612 int nread;
5614 /* If waiting for this channel, arrange to return as
5615 soon as no more input to be processed. No more
5616 waiting. */
5617 proc = chan_process[channel];
5618 if (NILP (proc))
5619 continue;
5621 /* If this is a server stream socket, accept connection. */
5622 if (EQ (XPROCESS (proc)->status, Qlisten))
5624 server_accept_connection (proc, channel);
5625 continue;
5628 /* Read data from the process, starting with our
5629 buffered-ahead character if we have one. */
5631 nread = read_process_output (proc, channel);
5632 if ((!wait_proc || wait_proc == XPROCESS (proc))
5633 && got_some_output < nread)
5634 got_some_output = nread;
5635 if (nread > 0)
5637 /* Vacuum up any leftovers without waiting. */
5638 if (wait_proc == XPROCESS (proc))
5639 wait = MINIMUM;
5640 /* Since read_process_output can run a filter,
5641 which can call accept-process-output,
5642 don't try to read from any other processes
5643 before doing the select again. */
5644 FD_ZERO (&Available);
5646 if (do_display)
5647 redisplay_preserve_echo_area (12);
5649 else if (nread == -1 && would_block (errno))
5651 #ifdef WINDOWSNT
5652 /* FIXME: Is this special case still needed? */
5653 /* Note that we cannot distinguish between no input
5654 available now and a closed pipe.
5655 With luck, a closed pipe will be accompanied by
5656 subprocess termination and SIGCHLD. */
5657 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5658 && !PIPECONN_P (proc))
5660 #endif
5661 #ifdef HAVE_PTYS
5662 /* On some OSs with ptys, when the process on one end of
5663 a pty exits, the other end gets an error reading with
5664 errno = EIO instead of getting an EOF (0 bytes read).
5665 Therefore, if we get an error reading and errno =
5666 EIO, just continue, because the child process has
5667 exited and should clean itself up soon (e.g. when we
5668 get a SIGCHLD). */
5669 else if (nread == -1 && errno == EIO)
5671 struct Lisp_Process *p = XPROCESS (proc);
5673 /* Clear the descriptor now, so we only raise the
5674 signal once. */
5675 delete_read_fd (channel);
5677 if (p->pid == -2)
5679 /* If the EIO occurs on a pty, the SIGCHLD handler's
5680 waitpid call will not find the process object to
5681 delete. Do it here. */
5682 p->tick = ++process_tick;
5683 pset_status (p, Qfailed);
5686 #endif /* HAVE_PTYS */
5687 /* If we can detect process termination, don't consider the
5688 process gone just because its pipe is closed. */
5689 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5690 && !PIPECONN_P (proc))
5692 else if (nread == 0 && PIPECONN_P (proc))
5694 /* Preserve status of processes already terminated. */
5695 XPROCESS (proc)->tick = ++process_tick;
5696 deactivate_process (proc);
5697 if (EQ (XPROCESS (proc)->status, Qrun))
5698 pset_status (XPROCESS (proc),
5699 list2 (Qexit, make_number (0)));
5701 else
5703 /* Preserve status of processes already terminated. */
5704 XPROCESS (proc)->tick = ++process_tick;
5705 deactivate_process (proc);
5706 if (XPROCESS (proc)->raw_status_new)
5707 update_status (XPROCESS (proc));
5708 if (EQ (XPROCESS (proc)->status, Qrun))
5709 pset_status (XPROCESS (proc),
5710 list2 (Qexit, make_number (256)));
5713 if (FD_ISSET (channel, &Writeok)
5714 && (fd_callback_info[channel].flags
5715 & NON_BLOCKING_CONNECT_FD) != 0)
5717 struct Lisp_Process *p;
5719 delete_write_fd (channel);
5721 proc = chan_process[channel];
5722 if (NILP (proc))
5723 continue;
5725 p = XPROCESS (proc);
5727 #ifndef WINDOWSNT
5729 socklen_t xlen = sizeof (xerrno);
5730 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5731 xerrno = errno;
5733 #else
5734 /* On MS-Windows, getsockopt clears the error for the
5735 entire process, which may not be the right thing; see
5736 w32.c. Use getpeername instead. */
5738 struct sockaddr pname;
5739 socklen_t pnamelen = sizeof (pname);
5741 /* If connection failed, getpeername will fail. */
5742 xerrno = 0;
5743 if (getpeername (channel, &pname, &pnamelen) < 0)
5745 /* Obtain connect failure code through error slippage. */
5746 char dummy;
5747 xerrno = errno;
5748 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5749 xerrno = errno;
5752 #endif
5753 if (xerrno)
5755 Lisp_Object addrinfos
5756 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5757 if (!NILP (addrinfos))
5758 XSETCDR (p->status, XCDR (addrinfos));
5759 else
5761 p->tick = ++process_tick;
5762 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5764 deactivate_process (proc);
5765 if (!NILP (addrinfos))
5766 connect_network_socket (proc, addrinfos, Qnil);
5768 else
5770 #ifdef HAVE_GNUTLS
5771 /* If we have an incompletely set up TLS connection,
5772 then defer the sentinel signaling until
5773 later. */
5774 if (NILP (p->gnutls_boot_parameters)
5775 && !p->gnutls_p)
5776 #endif
5778 pset_status (p, Qrun);
5779 /* Execute the sentinel here. If we had relied on
5780 status_notify to do it later, it will read input
5781 from the process before calling the sentinel. */
5782 exec_sentinel (proc, build_string ("open\n"));
5785 if (0 <= p->infd && !EQ (p->filter, Qt)
5786 && !EQ (p->command, Qt))
5787 add_process_read_fd (p->infd);
5790 } /* End for each file descriptor. */
5791 } /* End while exit conditions not met. */
5793 unbind_to (count, Qnil);
5795 /* If calling from keyboard input, do not quit
5796 since we want to return C-g as an input character.
5797 Otherwise, do pending quit if requested. */
5798 if (read_kbd >= 0)
5800 /* Prevent input_pending from remaining set if we quit. */
5801 clear_input_pending ();
5802 maybe_quit ();
5805 /* Timers and/or process filters that we have run could have themselves called
5806 `accept-process-output' (and by that indirectly this function), thus
5807 possibly reading some (or all) output of wait_proc without us noticing it.
5808 This could potentially lead to an endless wait (dealt with earlier in the
5809 function) and/or a wrong return value (dealt with here). */
5810 if (wait_proc && wait_proc->nbytes_read != prev_wait_proc_nbytes_read)
5811 got_some_output = min (INT_MAX, (wait_proc->nbytes_read
5812 - prev_wait_proc_nbytes_read));
5814 return got_some_output;
5817 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5819 static Lisp_Object
5820 read_process_output_call (Lisp_Object fun_and_args)
5822 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5825 static Lisp_Object
5826 read_process_output_error_handler (Lisp_Object error_val)
5828 cmd_error_internal (error_val, "error in process filter: ");
5829 Vinhibit_quit = Qt;
5830 update_echo_area ();
5831 Fsleep_for (make_number (2), Qnil);
5832 return Qt;
5835 static void
5836 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5837 ssize_t nbytes,
5838 struct coding_system *coding);
5840 /* Read pending output from the process channel,
5841 starting with our buffered-ahead character if we have one.
5842 Yield number of decoded characters read.
5844 This function reads at most 4096 characters.
5845 If you want to read all available subprocess output,
5846 you must call it repeatedly until it returns zero.
5848 The characters read are decoded according to PROC's coding-system
5849 for decoding. */
5851 static int
5852 read_process_output (Lisp_Object proc, int channel)
5854 ssize_t nbytes;
5855 struct Lisp_Process *p = XPROCESS (proc);
5856 struct coding_system *coding = proc_decode_coding_system[channel];
5857 int carryover = p->decoding_carryover;
5858 enum { readmax = 4096 };
5859 ptrdiff_t count = SPECPDL_INDEX ();
5860 Lisp_Object odeactivate;
5861 char chars[sizeof coding->carryover + readmax];
5863 if (carryover)
5864 /* See the comment above. */
5865 memcpy (chars, SDATA (p->decoding_buf), carryover);
5867 #ifdef DATAGRAM_SOCKETS
5868 /* We have a working select, so proc_buffered_char is always -1. */
5869 if (DATAGRAM_CHAN_P (channel))
5871 socklen_t len = datagram_address[channel].len;
5872 nbytes = recvfrom (channel, chars + carryover, readmax,
5873 0, datagram_address[channel].sa, &len);
5875 else
5876 #endif
5878 bool buffered = proc_buffered_char[channel] >= 0;
5879 if (buffered)
5881 chars[carryover] = proc_buffered_char[channel];
5882 proc_buffered_char[channel] = -1;
5884 #ifdef HAVE_GNUTLS
5885 if (p->gnutls_p && p->gnutls_state)
5886 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5887 readmax - buffered);
5888 else
5889 #endif
5890 nbytes = emacs_read (channel, chars + carryover + buffered,
5891 readmax - buffered);
5892 if (nbytes > 0 && p->adaptive_read_buffering)
5894 int delay = p->read_output_delay;
5895 if (nbytes < 256)
5897 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5899 if (delay == 0)
5900 process_output_delay_count++;
5901 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5904 else if (delay > 0 && nbytes == readmax - buffered)
5906 delay -= READ_OUTPUT_DELAY_INCREMENT;
5907 if (delay == 0)
5908 process_output_delay_count--;
5910 p->read_output_delay = delay;
5911 if (delay)
5913 p->read_output_skip = 1;
5914 process_output_skip = 1;
5917 nbytes += buffered;
5918 nbytes += buffered && nbytes <= 0;
5921 p->decoding_carryover = 0;
5923 /* At this point, NBYTES holds number of bytes just received
5924 (including the one in proc_buffered_char[channel]). */
5925 if (nbytes <= 0)
5927 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5928 return nbytes;
5929 coding->mode |= CODING_MODE_LAST_BLOCK;
5932 /* Ignore carryover, it's been added by a previous iteration already. */
5933 p->nbytes_read += nbytes;
5935 /* Now set NBYTES how many bytes we must decode. */
5936 nbytes += carryover;
5938 odeactivate = Vdeactivate_mark;
5939 /* There's no good reason to let process filters change the current
5940 buffer, and many callers of accept-process-output, sit-for, and
5941 friends don't expect current-buffer to be changed from under them. */
5942 record_unwind_current_buffer ();
5944 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5946 /* Handling the process output should not deactivate the mark. */
5947 Vdeactivate_mark = odeactivate;
5949 unbind_to (count, Qnil);
5950 return nbytes;
5953 static void
5954 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5955 ssize_t nbytes,
5956 struct coding_system *coding)
5958 Lisp_Object outstream = p->filter;
5959 Lisp_Object text;
5960 bool outer_running_asynch_code = running_asynch_code;
5961 int waiting = waiting_for_user_input_p;
5963 #if 0
5964 Lisp_Object obuffer, okeymap;
5965 XSETBUFFER (obuffer, current_buffer);
5966 okeymap = BVAR (current_buffer, keymap);
5967 #endif
5969 /* We inhibit quit here instead of just catching it so that
5970 hitting ^G when a filter happens to be running won't screw
5971 it up. */
5972 specbind (Qinhibit_quit, Qt);
5973 specbind (Qlast_nonmenu_event, Qt);
5975 /* In case we get recursively called,
5976 and we already saved the match data nonrecursively,
5977 save the same match data in safely recursive fashion. */
5978 if (outer_running_asynch_code)
5980 Lisp_Object tem;
5981 /* Don't clobber the CURRENT match data, either! */
5982 tem = Fmatch_data (Qnil, Qnil, Qnil);
5983 restore_search_regs ();
5984 record_unwind_save_match_data ();
5985 Fset_match_data (tem, Qt);
5988 /* For speed, if a search happens within this code,
5989 save the match data in a special nonrecursive fashion. */
5990 running_asynch_code = 1;
5992 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5993 text = coding->dst_object;
5994 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5995 /* A new coding system might be found. */
5996 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5998 pset_decode_coding_system (p, Vlast_coding_system_used);
6000 /* Don't call setup_coding_system for
6001 proc_decode_coding_system[channel] here. It is done in
6002 detect_coding called via decode_coding above. */
6004 /* If a coding system for encoding is not yet decided, we set
6005 it as the same as coding-system for decoding.
6007 But, before doing that we must check if
6008 proc_encode_coding_system[p->outfd] surely points to a
6009 valid memory because p->outfd will be changed once EOF is
6010 sent to the process. */
6011 if (NILP (p->encode_coding_system) && p->outfd >= 0
6012 && proc_encode_coding_system[p->outfd])
6014 pset_encode_coding_system
6015 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
6016 setup_coding_system (p->encode_coding_system,
6017 proc_encode_coding_system[p->outfd]);
6021 if (coding->carryover_bytes > 0)
6023 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
6024 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
6025 memcpy (SDATA (p->decoding_buf), coding->carryover,
6026 coding->carryover_bytes);
6027 p->decoding_carryover = coding->carryover_bytes;
6029 if (SBYTES (text) > 0)
6030 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6031 sometimes it's simply wrong to wrap (e.g. when called from
6032 accept-process-output). */
6033 internal_condition_case_1 (read_process_output_call,
6034 list3 (outstream, make_lisp_proc (p), text),
6035 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6036 read_process_output_error_handler);
6038 /* If we saved the match data nonrecursively, restore it now. */
6039 restore_search_regs ();
6040 running_asynch_code = outer_running_asynch_code;
6042 /* Restore waiting_for_user_input_p as it was
6043 when we were called, in case the filter clobbered it. */
6044 waiting_for_user_input_p = waiting;
6046 #if 0 /* Call record_asynch_buffer_change unconditionally,
6047 because we might have changed minor modes or other things
6048 that affect key bindings. */
6049 if (! EQ (Fcurrent_buffer (), obuffer)
6050 || ! EQ (current_buffer->keymap, okeymap))
6051 #endif
6052 /* But do it only if the caller is actually going to read events.
6053 Otherwise there's no need to make him wake up, and it could
6054 cause trouble (for example it would make sit_for return). */
6055 if (waiting_for_user_input_p == -1)
6056 record_asynch_buffer_change ();
6059 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
6060 Sinternal_default_process_filter, 2, 2, 0,
6061 doc: /* Function used as default process filter.
6062 This inserts the process's output into its buffer, if there is one.
6063 Otherwise it discards the output. */)
6064 (Lisp_Object proc, Lisp_Object text)
6066 struct Lisp_Process *p;
6067 ptrdiff_t opoint;
6069 CHECK_PROCESS (proc);
6070 p = XPROCESS (proc);
6071 CHECK_STRING (text);
6073 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
6075 Lisp_Object old_read_only;
6076 ptrdiff_t old_begv, old_zv;
6077 ptrdiff_t old_begv_byte, old_zv_byte;
6078 ptrdiff_t before, before_byte;
6079 ptrdiff_t opoint_byte;
6080 struct buffer *b;
6082 Fset_buffer (p->buffer);
6083 opoint = PT;
6084 opoint_byte = PT_BYTE;
6085 old_read_only = BVAR (current_buffer, read_only);
6086 old_begv = BEGV;
6087 old_zv = ZV;
6088 old_begv_byte = BEGV_BYTE;
6089 old_zv_byte = ZV_BYTE;
6091 bset_read_only (current_buffer, Qnil);
6093 /* Insert new output into buffer at the current end-of-output
6094 marker, thus preserving logical ordering of input and output. */
6095 if (XMARKER (p->mark)->buffer)
6096 set_point_from_marker (p->mark);
6097 else
6098 SET_PT_BOTH (ZV, ZV_BYTE);
6099 before = PT;
6100 before_byte = PT_BYTE;
6102 /* If the output marker is outside of the visible region, save
6103 the restriction and widen. */
6104 if (! (BEGV <= PT && PT <= ZV))
6105 Fwiden ();
6107 /* Adjust the multibyteness of TEXT to that of the buffer. */
6108 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
6109 != ! STRING_MULTIBYTE (text))
6110 text = (STRING_MULTIBYTE (text)
6111 ? Fstring_as_unibyte (text)
6112 : Fstring_to_multibyte (text));
6113 /* Insert before markers in case we are inserting where
6114 the buffer's mark is, and the user's next command is Meta-y. */
6115 insert_from_string_before_markers (text, 0, 0,
6116 SCHARS (text), SBYTES (text), 0);
6118 /* Make sure the process marker's position is valid when the
6119 process buffer is changed in the signal_after_change above.
6120 W3 is known to do that. */
6121 if (BUFFERP (p->buffer)
6122 && (b = XBUFFER (p->buffer), b != current_buffer))
6123 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
6124 else
6125 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6127 update_mode_lines = 23;
6129 /* Make sure opoint and the old restrictions
6130 float ahead of any new text just as point would. */
6131 if (opoint >= before)
6133 opoint += PT - before;
6134 opoint_byte += PT_BYTE - before_byte;
6136 if (old_begv > before)
6138 old_begv += PT - before;
6139 old_begv_byte += PT_BYTE - before_byte;
6141 if (old_zv >= before)
6143 old_zv += PT - before;
6144 old_zv_byte += PT_BYTE - before_byte;
6147 /* If the restriction isn't what it should be, set it. */
6148 if (old_begv != BEGV || old_zv != ZV)
6149 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
6151 bset_read_only (current_buffer, old_read_only);
6152 SET_PT_BOTH (opoint, opoint_byte);
6154 return Qnil;
6157 /* Sending data to subprocess. */
6159 /* In send_process, when a write fails temporarily,
6160 wait_reading_process_output is called. It may execute user code,
6161 e.g. timers, that attempts to write new data to the same process.
6162 We must ensure that data is sent in the right order, and not
6163 interspersed half-completed with other writes (Bug#10815). This is
6164 handled by the write_queue element of struct process. It is a list
6165 with each entry having the form
6167 (string . (offset . length))
6169 where STRING is a lisp string, OFFSET is the offset into the
6170 string's byte sequence from which we should begin to send, and
6171 LENGTH is the number of bytes left to send. */
6173 /* Create a new entry in write_queue.
6174 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6175 BUF is a pointer to the string sequence of the input_obj or a C
6176 string in case of Qt or Qnil. */
6178 static void
6179 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
6180 const char *buf, ptrdiff_t len, bool front)
6182 ptrdiff_t offset;
6183 Lisp_Object entry, obj;
6185 if (STRINGP (input_obj))
6187 offset = buf - SSDATA (input_obj);
6188 obj = input_obj;
6190 else
6192 offset = 0;
6193 obj = make_unibyte_string (buf, len);
6196 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
6198 if (front)
6199 pset_write_queue (p, Fcons (entry, p->write_queue));
6200 else
6201 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
6204 /* Remove the first element in the write_queue of process P, put its
6205 contents in OBJ, BUF and LEN, and return true. If the
6206 write_queue is empty, return false. */
6208 static bool
6209 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
6210 const char **buf, ptrdiff_t *len)
6212 Lisp_Object entry, offset_length;
6213 ptrdiff_t offset;
6215 if (NILP (p->write_queue))
6216 return 0;
6218 entry = XCAR (p->write_queue);
6219 pset_write_queue (p, XCDR (p->write_queue));
6221 *obj = XCAR (entry);
6222 offset_length = XCDR (entry);
6224 *len = XINT (XCDR (offset_length));
6225 offset = XINT (XCAR (offset_length));
6226 *buf = SSDATA (*obj) + offset;
6228 return 1;
6231 /* Send some data to process PROC.
6232 BUF is the beginning of the data; LEN is the number of characters.
6233 OBJECT is the Lisp object that the data comes from. If OBJECT is
6234 nil or t, it means that the data comes from C string.
6236 If OBJECT is not nil, the data is encoded by PROC's coding-system
6237 for encoding before it is sent.
6239 This function can evaluate Lisp code and can garbage collect. */
6241 static void
6242 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6243 Lisp_Object object)
6245 struct Lisp_Process *p = XPROCESS (proc);
6246 ssize_t rv;
6247 struct coding_system *coding;
6249 if (NETCONN_P (proc))
6251 wait_while_connecting (proc);
6252 wait_for_tls_negotiation (proc);
6255 if (p->raw_status_new)
6256 update_status (p);
6257 if (! EQ (p->status, Qrun))
6258 error ("Process %s not running", SDATA (p->name));
6259 if (p->outfd < 0)
6260 error ("Output file descriptor of %s is closed", SDATA (p->name));
6262 coding = proc_encode_coding_system[p->outfd];
6263 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6265 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6266 || (BUFFERP (object)
6267 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6268 || EQ (object, Qt))
6270 pset_encode_coding_system
6271 (p, complement_process_encoding_system (p->encode_coding_system));
6272 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6274 /* The coding system for encoding was changed to raw-text
6275 because we sent a unibyte text previously. Now we are
6276 sending a multibyte text, thus we must encode it by the
6277 original coding system specified for the current process.
6279 Another reason we come here is that the coding system
6280 was just complemented and a new one was returned by
6281 complement_process_encoding_system. */
6282 setup_coding_system (p->encode_coding_system, coding);
6283 Vlast_coding_system_used = p->encode_coding_system;
6285 coding->src_multibyte = 1;
6287 else
6289 coding->src_multibyte = 0;
6290 /* For sending a unibyte text, character code conversion should
6291 not take place but EOL conversion should. So, setup raw-text
6292 or one of the subsidiary if we have not yet done it. */
6293 if (CODING_REQUIRE_ENCODING (coding))
6295 if (CODING_REQUIRE_FLUSHING (coding))
6297 /* But, before changing the coding, we must flush out data. */
6298 coding->mode |= CODING_MODE_LAST_BLOCK;
6299 send_process (proc, "", 0, Qt);
6300 coding->mode &= CODING_MODE_LAST_BLOCK;
6302 setup_coding_system (raw_text_coding_system
6303 (Vlast_coding_system_used),
6304 coding);
6305 coding->src_multibyte = 0;
6308 coding->dst_multibyte = 0;
6310 if (CODING_REQUIRE_ENCODING (coding))
6312 coding->dst_object = Qt;
6313 if (BUFFERP (object))
6315 ptrdiff_t from_byte, from, to;
6316 ptrdiff_t save_pt, save_pt_byte;
6317 struct buffer *cur = current_buffer;
6319 set_buffer_internal (XBUFFER (object));
6320 save_pt = PT, save_pt_byte = PT_BYTE;
6322 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6323 from = BYTE_TO_CHAR (from_byte);
6324 to = BYTE_TO_CHAR (from_byte + len);
6325 TEMP_SET_PT_BOTH (from, from_byte);
6326 encode_coding_object (coding, object, from, from_byte,
6327 to, from_byte + len, Qt);
6328 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6329 set_buffer_internal (cur);
6331 else if (STRINGP (object))
6333 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6334 SBYTES (object), Qt);
6336 else
6338 coding->dst_object = make_unibyte_string (buf, len);
6339 coding->produced = len;
6342 len = coding->produced;
6343 object = coding->dst_object;
6344 buf = SSDATA (object);
6347 /* If there is already data in the write_queue, put the new data
6348 in the back of queue. Otherwise, ignore it. */
6349 if (!NILP (p->write_queue))
6350 write_queue_push (p, object, buf, len, 0);
6352 do /* while !NILP (p->write_queue) */
6354 ptrdiff_t cur_len = -1;
6355 const char *cur_buf;
6356 Lisp_Object cur_object;
6358 /* If write_queue is empty, ignore it. */
6359 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6361 cur_len = len;
6362 cur_buf = buf;
6363 cur_object = object;
6366 while (cur_len > 0)
6368 /* Send this batch, using one or more write calls. */
6369 ptrdiff_t written = 0;
6370 int outfd = p->outfd;
6371 #ifdef DATAGRAM_SOCKETS
6372 if (DATAGRAM_CHAN_P (outfd))
6374 rv = sendto (outfd, cur_buf, cur_len,
6375 0, datagram_address[outfd].sa,
6376 datagram_address[outfd].len);
6377 if (rv >= 0)
6378 written = rv;
6379 else if (errno == EMSGSIZE)
6380 report_file_error ("Sending datagram", proc);
6382 else
6383 #endif
6385 #ifdef HAVE_GNUTLS
6386 if (p->gnutls_p && p->gnutls_state)
6387 written = emacs_gnutls_write (p, cur_buf, cur_len);
6388 else
6389 #endif
6390 written = emacs_write_sig (outfd, cur_buf, cur_len);
6391 rv = (written ? 0 : -1);
6392 if (p->read_output_delay > 0
6393 && p->adaptive_read_buffering == 1)
6395 p->read_output_delay = 0;
6396 process_output_delay_count--;
6397 p->read_output_skip = 0;
6401 if (rv < 0)
6403 if (would_block (errno))
6404 /* Buffer is full. Wait, accepting input;
6405 that may allow the program
6406 to finish doing output and read more. */
6408 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6409 /* A gross hack to work around a bug in FreeBSD.
6410 In the following sequence, read(2) returns
6411 bogus data:
6413 write(2) 1022 bytes
6414 write(2) 954 bytes, get EAGAIN
6415 read(2) 1024 bytes in process_read_output
6416 read(2) 11 bytes in process_read_output
6418 That is, read(2) returns more bytes than have
6419 ever been written successfully. The 1033 bytes
6420 read are the 1022 bytes written successfully
6421 after processing (for example with CRs added if
6422 the terminal is set up that way which it is
6423 here). The same bytes will be seen again in a
6424 later read(2), without the CRs. */
6426 if (errno == EAGAIN)
6428 int flags = FWRITE;
6429 ioctl (p->outfd, TIOCFLUSH, &flags);
6431 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6433 /* Put what we should have written in wait_queue. */
6434 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6435 wait_reading_process_output (0, 20 * 1000 * 1000,
6436 0, 0, Qnil, NULL, 0);
6437 /* Reread queue, to see what is left. */
6438 break;
6440 else if (errno == EPIPE)
6442 p->raw_status_new = 0;
6443 pset_status (p, list2 (Qexit, make_number (256)));
6444 p->tick = ++process_tick;
6445 deactivate_process (proc);
6446 error ("process %s no longer connected to pipe; closed it",
6447 SDATA (p->name));
6449 else
6450 /* This is a real error. */
6451 report_file_error ("Writing to process", proc);
6453 cur_buf += written;
6454 cur_len -= written;
6457 while (!NILP (p->write_queue));
6460 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6461 3, 3, 0,
6462 doc: /* Send current contents of region as input to PROCESS.
6463 PROCESS may be a process, a buffer, the name of a process or buffer, or
6464 nil, indicating the current buffer's process.
6465 Called from program, takes three arguments, PROCESS, START and END.
6466 If the region is larger than the input buffer of the process (the
6467 length of which depends on the process connection type and the
6468 operating system), it is sent in several bunches. This may happen
6469 even for shorter regions. Output from processes can arrive in between
6470 bunches.
6472 If PROCESS is a non-blocking network process that hasn't been fully
6473 set up yet, this function will block until socket setup has completed. */)
6474 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6476 Lisp_Object proc = get_process (process);
6477 ptrdiff_t start_byte, end_byte;
6479 validate_region (&start, &end);
6481 start_byte = CHAR_TO_BYTE (XINT (start));
6482 end_byte = CHAR_TO_BYTE (XINT (end));
6484 if (XINT (start) < GPT && XINT (end) > GPT)
6485 move_gap_both (XINT (start), start_byte);
6487 if (NETCONN_P (proc))
6488 wait_while_connecting (proc);
6490 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6491 end_byte - start_byte, Fcurrent_buffer ());
6493 return Qnil;
6496 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6497 2, 2, 0,
6498 doc: /* Send PROCESS the contents of STRING as input.
6499 PROCESS may be a process, a buffer, the name of a process or buffer, or
6500 nil, indicating the current buffer's process.
6501 If STRING is larger than the input buffer of the process (the length
6502 of which depends on the process connection type and the operating
6503 system), it is sent in several bunches. This may happen even for
6504 shorter strings. Output from processes can arrive in between bunches.
6506 If PROCESS is a non-blocking network process that hasn't been fully
6507 set up yet, this function will block until socket setup has completed. */)
6508 (Lisp_Object process, Lisp_Object string)
6510 CHECK_STRING (string);
6511 Lisp_Object proc = get_process (process);
6512 send_process (proc, SSDATA (string),
6513 SBYTES (string), string);
6514 return Qnil;
6517 /* Return the foreground process group for the tty/pty that
6518 the process P uses. */
6519 static pid_t
6520 emacs_get_tty_pgrp (struct Lisp_Process *p)
6522 pid_t gid = -1;
6524 #ifdef TIOCGPGRP
6525 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6527 int fd;
6528 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6529 master side. Try the slave side. */
6530 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6532 if (fd != -1)
6534 ioctl (fd, TIOCGPGRP, &gid);
6535 emacs_close (fd);
6538 #endif /* defined (TIOCGPGRP ) */
6540 return gid;
6543 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6544 Sprocess_running_child_p, 0, 1, 0,
6545 doc: /* Return non-nil if PROCESS has given the terminal to a
6546 child. If the operating system does not make it possible to find out,
6547 return t. If we can find out, return the numeric ID of the foreground
6548 process group. */)
6549 (Lisp_Object process)
6551 /* Initialize in case ioctl doesn't exist or gives an error,
6552 in a way that will cause returning t. */
6553 Lisp_Object proc = get_process (process);
6554 struct Lisp_Process *p = XPROCESS (proc);
6556 if (!EQ (p->type, Qreal))
6557 error ("Process %s is not a subprocess",
6558 SDATA (p->name));
6559 if (p->infd < 0)
6560 error ("Process %s is not active",
6561 SDATA (p->name));
6563 pid_t gid = emacs_get_tty_pgrp (p);
6565 if (gid == p->pid)
6566 return Qnil;
6567 if (gid != -1)
6568 return make_number (gid);
6569 return Qt;
6572 /* Send a signal number SIGNO to PROCESS.
6573 If CURRENT_GROUP is t, that means send to the process group
6574 that currently owns the terminal being used to communicate with PROCESS.
6575 This is used for various commands in shell mode.
6576 If CURRENT_GROUP is lambda, that means send to the process group
6577 that currently owns the terminal, but only if it is NOT the shell itself.
6579 If NOMSG is false, insert signal-announcements into process's buffers
6580 right away.
6582 If we can, we try to signal PROCESS by sending control characters
6583 down the pty. This allows us to signal inferiors who have changed
6584 their uid, for which kill would return an EPERM error. */
6586 static void
6587 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6588 bool nomsg)
6590 Lisp_Object proc;
6591 struct Lisp_Process *p;
6592 pid_t gid;
6593 bool no_pgrp = 0;
6595 proc = get_process (process);
6596 p = XPROCESS (proc);
6598 if (!EQ (p->type, Qreal))
6599 error ("Process %s is not a subprocess",
6600 SDATA (p->name));
6601 if (p->infd < 0)
6602 error ("Process %s is not active",
6603 SDATA (p->name));
6605 if (!p->pty_flag)
6606 current_group = Qnil;
6608 /* If we are using pgrps, get a pgrp number and make it negative. */
6609 if (NILP (current_group))
6610 /* Send the signal to the shell's process group. */
6611 gid = p->pid;
6612 else
6614 #ifdef SIGNALS_VIA_CHARACTERS
6615 /* If possible, send signals to the entire pgrp
6616 by sending an input character to it. */
6618 struct termios t;
6619 cc_t *sig_char = NULL;
6621 tcgetattr (p->infd, &t);
6623 switch (signo)
6625 case SIGINT:
6626 sig_char = &t.c_cc[VINTR];
6627 break;
6629 case SIGQUIT:
6630 sig_char = &t.c_cc[VQUIT];
6631 break;
6633 case SIGTSTP:
6634 #ifdef VSWTCH
6635 sig_char = &t.c_cc[VSWTCH];
6636 #else
6637 sig_char = &t.c_cc[VSUSP];
6638 #endif
6639 break;
6642 if (sig_char && *sig_char != CDISABLE)
6644 send_process (proc, (char *) sig_char, 1, Qnil);
6645 return;
6647 /* If we can't send the signal with a character,
6648 fall through and send it another way. */
6650 /* The code above may fall through if it can't
6651 handle the signal. */
6652 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6654 #ifdef TIOCGPGRP
6655 /* Get the current pgrp using the tty itself, if we have that.
6656 Otherwise, use the pty to get the pgrp.
6657 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6658 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6659 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6660 His patch indicates that if TIOCGPGRP returns an error, then
6661 we should just assume that p->pid is also the process group id. */
6663 gid = emacs_get_tty_pgrp (p);
6665 if (gid == -1)
6666 /* If we can't get the information, assume
6667 the shell owns the tty. */
6668 gid = p->pid;
6670 /* It is not clear whether anything really can set GID to -1.
6671 Perhaps on some system one of those ioctls can or could do so.
6672 Or perhaps this is vestigial. */
6673 if (gid == -1)
6674 no_pgrp = 1;
6675 #else /* ! defined (TIOCGPGRP) */
6676 /* Can't select pgrps on this system, so we know that
6677 the child itself heads the pgrp. */
6678 gid = p->pid;
6679 #endif /* ! defined (TIOCGPGRP) */
6681 /* If current_group is lambda, and the shell owns the terminal,
6682 don't send any signal. */
6683 if (EQ (current_group, Qlambda) && gid == p->pid)
6684 return;
6687 #ifdef SIGCONT
6688 if (signo == SIGCONT)
6690 p->raw_status_new = 0;
6691 pset_status (p, Qrun);
6692 p->tick = ++process_tick;
6693 if (!nomsg)
6695 status_notify (NULL, NULL);
6696 redisplay_preserve_echo_area (13);
6699 #endif
6701 #ifdef TIOCSIGSEND
6702 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6703 We don't know whether the bug is fixed in later HP-UX versions. */
6704 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6705 return;
6706 #endif
6708 /* If we don't have process groups, send the signal to the immediate
6709 subprocess. That isn't really right, but it's better than any
6710 obvious alternative. */
6711 pid_t pid = no_pgrp ? gid : - gid;
6713 /* Do not kill an already-reaped process, as that could kill an
6714 innocent bystander that happens to have the same process ID. */
6715 sigset_t oldset;
6716 block_child_signal (&oldset);
6717 if (p->alive)
6718 kill (pid, signo);
6719 unblock_child_signal (&oldset);
6722 DEFUN ("internal-default-interrupt-process",
6723 Finternal_default_interrupt_process,
6724 Sinternal_default_interrupt_process, 0, 2, 0,
6725 doc: /* Default function to interrupt process PROCESS.
6726 It shall be the last element in list `interrupt-process-functions'.
6727 See function `interrupt-process' for more details on usage. */)
6728 (Lisp_Object process, Lisp_Object current_group)
6730 process_send_signal (process, SIGINT, current_group, 0);
6731 return process;
6734 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6735 doc: /* Interrupt process PROCESS.
6736 PROCESS may be a process, a buffer, or the name of a process or buffer.
6737 No arg or nil means current buffer's process.
6738 Second arg CURRENT-GROUP non-nil means send signal to
6739 the current process-group of the process's controlling terminal
6740 rather than to the process's own process group.
6741 If the process is a shell, this means interrupt current subjob
6742 rather than the shell.
6744 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6745 don't send the signal.
6747 This function calls the functions of `interrupt-process-functions' in
6748 the order of the list, until one of them returns non-`nil'. */)
6749 (Lisp_Object process, Lisp_Object current_group)
6751 return CALLN (Frun_hook_with_args_until_success, Qinterrupt_process_functions,
6752 process, current_group);
6755 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6756 doc: /* Kill process PROCESS. May be process or name of one.
6757 See function `interrupt-process' for more details on usage. */)
6758 (Lisp_Object process, Lisp_Object current_group)
6760 process_send_signal (process, SIGKILL, current_group, 0);
6761 return process;
6764 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6765 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6766 See function `interrupt-process' for more details on usage. */)
6767 (Lisp_Object process, Lisp_Object current_group)
6769 process_send_signal (process, SIGQUIT, current_group, 0);
6770 return process;
6773 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6774 doc: /* Stop process PROCESS. May be process or name of one.
6775 See function `interrupt-process' for more details on usage.
6776 If PROCESS is a network or serial or pipe connection, inhibit handling
6777 of incoming traffic. */)
6778 (Lisp_Object process, Lisp_Object current_group)
6780 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6781 || PIPECONN_P (process)))
6783 struct Lisp_Process *p;
6785 p = XPROCESS (process);
6786 if (NILP (p->command)
6787 && p->infd >= 0)
6788 delete_read_fd (p->infd);
6789 pset_command (p, Qt);
6790 return process;
6792 #ifndef SIGTSTP
6793 error ("No SIGTSTP support");
6794 #else
6795 process_send_signal (process, SIGTSTP, current_group, 0);
6796 #endif
6797 return process;
6800 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6801 doc: /* Continue process PROCESS. May be process or name of one.
6802 See function `interrupt-process' for more details on usage.
6803 If PROCESS is a network or serial process, resume handling of incoming
6804 traffic. */)
6805 (Lisp_Object process, Lisp_Object current_group)
6807 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6808 || PIPECONN_P (process)))
6810 struct Lisp_Process *p;
6812 p = XPROCESS (process);
6813 if (EQ (p->command, Qt)
6814 && p->infd >= 0
6815 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6817 add_process_read_fd (p->infd);
6818 #ifdef WINDOWSNT
6819 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6820 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6821 #else /* not WINDOWSNT */
6822 tcflush (p->infd, TCIFLUSH);
6823 #endif /* not WINDOWSNT */
6825 pset_command (p, Qnil);
6826 return process;
6828 #ifdef SIGCONT
6829 process_send_signal (process, SIGCONT, current_group, 0);
6830 #else
6831 error ("No SIGCONT support");
6832 #endif
6833 return process;
6836 /* Return the integer value of the signal whose abbreviation is ABBR,
6837 or a negative number if there is no such signal. */
6838 static int
6839 abbr_to_signal (char const *name)
6841 int i, signo;
6842 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6844 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6845 name += 3;
6847 for (i = 0; i < sizeof sigbuf; i++)
6849 sigbuf[i] = c_toupper (name[i]);
6850 if (! sigbuf[i])
6851 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6854 return -1;
6857 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6858 2, 2, "sProcess (name or number): \nnSignal code: ",
6859 doc: /* Send PROCESS the signal with code SIGCODE.
6860 PROCESS may also be a number specifying the process id of the
6861 process to signal; in this case, the process need not be a child of
6862 this Emacs.
6863 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6864 (Lisp_Object process, Lisp_Object sigcode)
6866 pid_t pid;
6867 int signo;
6869 if (STRINGP (process))
6871 Lisp_Object tem = Fget_process (process);
6872 if (NILP (tem))
6874 Lisp_Object process_number
6875 = string_to_number (SSDATA (process), 10, 1);
6876 if (NUMBERP (process_number))
6877 tem = process_number;
6879 process = tem;
6881 else if (!NUMBERP (process))
6882 process = get_process (process);
6884 if (NILP (process))
6885 return process;
6887 if (NUMBERP (process))
6888 CONS_TO_INTEGER (process, pid_t, pid);
6889 else
6891 CHECK_PROCESS (process);
6892 pid = XPROCESS (process)->pid;
6893 if (pid <= 0)
6894 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6897 if (INTEGERP (sigcode))
6899 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6900 signo = XINT (sigcode);
6902 else
6904 char *name;
6906 CHECK_SYMBOL (sigcode);
6907 name = SSDATA (SYMBOL_NAME (sigcode));
6909 signo = abbr_to_signal (name);
6910 if (signo < 0)
6911 error ("Undefined signal name %s", name);
6914 return make_number (kill (pid, signo));
6917 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6918 doc: /* Make PROCESS see end-of-file in its input.
6919 EOF comes after any text already sent to it.
6920 PROCESS may be a process, a buffer, the name of a process or buffer, or
6921 nil, indicating the current buffer's process.
6922 If PROCESS is a network connection, or is a process communicating
6923 through a pipe (as opposed to a pty), then you cannot send any more
6924 text to PROCESS after you call this function.
6925 If PROCESS is a serial process, wait until all output written to the
6926 process has been transmitted to the serial port. */)
6927 (Lisp_Object process)
6929 Lisp_Object proc;
6930 struct coding_system *coding = NULL;
6931 int outfd;
6933 proc = get_process (process);
6935 if (NETCONN_P (proc))
6936 wait_while_connecting (proc);
6938 if (DATAGRAM_CONN_P (proc))
6939 return process;
6942 outfd = XPROCESS (proc)->outfd;
6943 if (outfd >= 0)
6944 coding = proc_encode_coding_system[outfd];
6946 /* Make sure the process is really alive. */
6947 if (XPROCESS (proc)->raw_status_new)
6948 update_status (XPROCESS (proc));
6949 if (! EQ (XPROCESS (proc)->status, Qrun))
6950 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6952 if (coding && CODING_REQUIRE_FLUSHING (coding))
6954 coding->mode |= CODING_MODE_LAST_BLOCK;
6955 send_process (proc, "", 0, Qnil);
6958 if (XPROCESS (proc)->pty_flag)
6959 send_process (proc, "\004", 1, Qnil);
6960 else if (EQ (XPROCESS (proc)->type, Qserial))
6962 #ifndef WINDOWSNT
6963 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6964 report_file_error ("Failed tcdrain", Qnil);
6965 #endif /* not WINDOWSNT */
6966 /* Do nothing on Windows because writes are blocking. */
6968 else
6970 struct Lisp_Process *p = XPROCESS (proc);
6971 int old_outfd = p->outfd;
6972 int new_outfd;
6974 #ifdef HAVE_SHUTDOWN
6975 /* If this is a network connection, or socketpair is used
6976 for communication with the subprocess, call shutdown to cause EOF.
6977 (In some old system, shutdown to socketpair doesn't work.
6978 Then we just can't win.) */
6979 if (0 <= old_outfd
6980 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6981 shutdown (old_outfd, 1);
6982 #endif
6983 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6984 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6985 if (new_outfd < 0)
6986 report_file_error ("Opening null device", Qnil);
6987 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6988 p->outfd = new_outfd;
6990 if (!proc_encode_coding_system[new_outfd])
6991 proc_encode_coding_system[new_outfd]
6992 = xmalloc (sizeof (struct coding_system));
6993 if (old_outfd >= 0)
6995 *proc_encode_coding_system[new_outfd]
6996 = *proc_encode_coding_system[old_outfd];
6997 memset (proc_encode_coding_system[old_outfd], 0,
6998 sizeof (struct coding_system));
7000 else
7001 setup_coding_system (p->encode_coding_system,
7002 proc_encode_coding_system[new_outfd]);
7004 return process;
7007 /* The main Emacs thread records child processes in three places:
7009 - Vprocess_alist, for asynchronous subprocesses, which are child
7010 processes visible to Lisp.
7012 - deleted_pid_list, for child processes invisible to Lisp,
7013 typically because of delete-process. These are recorded so that
7014 the processes can be reaped when they exit, so that the operating
7015 system's process table is not cluttered by zombies.
7017 - the local variable PID in Fcall_process, call_process_cleanup and
7018 call_process_kill, for synchronous subprocesses.
7019 record_unwind_protect is used to make sure this process is not
7020 forgotten: if the user interrupts call-process and the child
7021 process refuses to exit immediately even with two C-g's,
7022 call_process_kill adds PID's contents to deleted_pid_list before
7023 returning.
7025 The main Emacs thread invokes waitpid only on child processes that
7026 it creates and that have not been reaped. This avoid races on
7027 platforms such as GTK, where other threads create their own
7028 subprocesses which the main thread should not reap. For example,
7029 if the main thread attempted to reap an already-reaped child, it
7030 might inadvertently reap a GTK-created process that happened to
7031 have the same process ID. */
7033 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7034 its own SIGCHLD handling. On POSIXish systems, glib needs this to
7035 keep track of its own children. GNUstep is similar. */
7037 static void dummy_handler (int sig) {}
7038 static signal_handler_t volatile lib_child_handler;
7040 /* Handle a SIGCHLD signal by looking for known child processes of
7041 Emacs whose status have changed. For each one found, record its
7042 new status.
7044 All we do is change the status; we do not run sentinels or print
7045 notifications. That is saved for the next time keyboard input is
7046 done, in order to avoid timing errors.
7048 ** WARNING: this can be called during garbage collection.
7049 Therefore, it must not be fooled by the presence of mark bits in
7050 Lisp objects.
7052 ** USG WARNING: Although it is not obvious from the documentation
7053 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7054 signal() before executing at least one wait(), otherwise the
7055 handler will be called again, resulting in an infinite loop. The
7056 relevant portion of the documentation reads "SIGCLD signals will be
7057 queued and the signal-catching function will be continually
7058 reentered until the queue is empty". Invoking signal() causes the
7059 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7060 Inc.
7062 ** Malloc WARNING: This should never call malloc either directly or
7063 indirectly; if it does, that is a bug. */
7065 static void
7066 handle_child_signal (int sig)
7068 Lisp_Object tail, proc;
7070 /* Find the process that signaled us, and record its status. */
7072 /* The process can have been deleted by Fdelete_process, or have
7073 been started asynchronously by Fcall_process. */
7074 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
7076 bool all_pids_are_fixnums
7077 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
7078 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
7079 Lisp_Object head = XCAR (tail);
7080 Lisp_Object xpid;
7081 if (! CONSP (head))
7082 continue;
7083 xpid = XCAR (head);
7084 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
7086 pid_t deleted_pid;
7087 if (INTEGERP (xpid))
7088 deleted_pid = XINT (xpid);
7089 else
7090 deleted_pid = XFLOAT_DATA (xpid);
7091 if (child_status_changed (deleted_pid, 0, 0))
7093 if (STRINGP (XCDR (head)))
7094 unlink (SSDATA (XCDR (head)));
7095 XSETCAR (tail, Qnil);
7100 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7101 FOR_EACH_PROCESS (tail, proc)
7103 struct Lisp_Process *p = XPROCESS (proc);
7104 int status;
7106 if (p->alive
7107 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
7109 /* Change the status of the process that was found. */
7110 p->tick = ++process_tick;
7111 p->raw_status = status;
7112 p->raw_status_new = 1;
7114 /* If process has terminated, stop waiting for its output. */
7115 if (WIFSIGNALED (status) || WIFEXITED (status))
7117 bool clear_desc_flag = 0;
7118 p->alive = 0;
7119 if (p->infd >= 0)
7120 clear_desc_flag = 1;
7122 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7123 if (clear_desc_flag)
7124 delete_read_fd (p->infd);
7129 lib_child_handler (sig);
7130 #ifdef NS_IMPL_GNUSTEP
7131 /* NSTask in GNUstep sets its child handler each time it is called.
7132 So we must re-set ours. */
7133 catch_child_signal ();
7134 #endif
7137 static void
7138 deliver_child_signal (int sig)
7140 deliver_process_signal (sig, handle_child_signal);
7144 static Lisp_Object
7145 exec_sentinel_error_handler (Lisp_Object error_val)
7147 /* Make sure error_val is a cons cell, as all the rest of error
7148 handling expects that, and will barf otherwise. */
7149 if (!CONSP (error_val))
7150 error_val = Fcons (Qerror, error_val);
7151 cmd_error_internal (error_val, "error in process sentinel: ");
7152 Vinhibit_quit = Qt;
7153 update_echo_area ();
7154 Fsleep_for (make_number (2), Qnil);
7155 return Qt;
7158 static void
7159 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
7161 Lisp_Object sentinel, odeactivate;
7162 struct Lisp_Process *p = XPROCESS (proc);
7163 ptrdiff_t count = SPECPDL_INDEX ();
7164 bool outer_running_asynch_code = running_asynch_code;
7165 int waiting = waiting_for_user_input_p;
7167 if (inhibit_sentinels)
7168 return;
7170 odeactivate = Vdeactivate_mark;
7171 #if 0
7172 Lisp_Object obuffer, okeymap;
7173 XSETBUFFER (obuffer, current_buffer);
7174 okeymap = BVAR (current_buffer, keymap);
7175 #endif
7177 /* There's no good reason to let sentinels change the current
7178 buffer, and many callers of accept-process-output, sit-for, and
7179 friends don't expect current-buffer to be changed from under them. */
7180 record_unwind_current_buffer ();
7182 sentinel = p->sentinel;
7184 /* Inhibit quit so that random quits don't screw up a running filter. */
7185 specbind (Qinhibit_quit, Qt);
7186 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
7188 /* In case we get recursively called,
7189 and we already saved the match data nonrecursively,
7190 save the same match data in safely recursive fashion. */
7191 if (outer_running_asynch_code)
7193 Lisp_Object tem;
7194 tem = Fmatch_data (Qnil, Qnil, Qnil);
7195 restore_search_regs ();
7196 record_unwind_save_match_data ();
7197 Fset_match_data (tem, Qt);
7200 /* For speed, if a search happens within this code,
7201 save the match data in a special nonrecursive fashion. */
7202 running_asynch_code = 1;
7204 internal_condition_case_1 (read_process_output_call,
7205 list3 (sentinel, proc, reason),
7206 !NILP (Vdebug_on_error) ? Qnil : Qerror,
7207 exec_sentinel_error_handler);
7209 /* If we saved the match data nonrecursively, restore it now. */
7210 restore_search_regs ();
7211 running_asynch_code = outer_running_asynch_code;
7213 Vdeactivate_mark = odeactivate;
7215 /* Restore waiting_for_user_input_p as it was
7216 when we were called, in case the filter clobbered it. */
7217 waiting_for_user_input_p = waiting;
7219 #if 0
7220 if (! EQ (Fcurrent_buffer (), obuffer)
7221 || ! EQ (current_buffer->keymap, okeymap))
7222 #endif
7223 /* But do it only if the caller is actually going to read events.
7224 Otherwise there's no need to make him wake up, and it could
7225 cause trouble (for example it would make sit_for return). */
7226 if (waiting_for_user_input_p == -1)
7227 record_asynch_buffer_change ();
7229 unbind_to (count, Qnil);
7232 /* Report all recent events of a change in process status
7233 (either run the sentinel or output a message).
7234 This is usually done while Emacs is waiting for keyboard input
7235 but can be done at other times.
7237 Return positive if any input was received from WAIT_PROC (or from
7238 any process if WAIT_PROC is null), zero if input was attempted but
7239 none received, and negative if we didn't even try. */
7241 static int
7242 status_notify (struct Lisp_Process *deleting_process,
7243 struct Lisp_Process *wait_proc)
7245 Lisp_Object proc;
7246 Lisp_Object tail, msg;
7247 int got_some_output = -1;
7249 tail = Qnil;
7250 msg = Qnil;
7252 /* Set this now, so that if new processes are created by sentinels
7253 that we run, we get called again to handle their status changes. */
7254 update_tick = process_tick;
7256 FOR_EACH_PROCESS (tail, proc)
7258 Lisp_Object symbol;
7259 register struct Lisp_Process *p = XPROCESS (proc);
7261 if (p->tick != p->update_tick)
7263 p->update_tick = p->tick;
7265 /* If process is still active, read any output that remains. */
7266 while (! EQ (p->filter, Qt)
7267 && ! connecting_status (p->status)
7268 && ! EQ (p->status, Qlisten)
7269 /* Network or serial process not stopped: */
7270 && ! EQ (p->command, Qt)
7271 && p->infd >= 0
7272 && p != deleting_process)
7274 int nread = read_process_output (proc, p->infd);
7275 if ((!wait_proc || wait_proc == XPROCESS (proc))
7276 && got_some_output < nread)
7277 got_some_output = nread;
7278 if (nread <= 0)
7279 break;
7282 /* Get the text to use for the message. */
7283 if (p->raw_status_new)
7284 update_status (p);
7285 msg = status_message (p);
7287 /* If process is terminated, deactivate it or delete it. */
7288 symbol = p->status;
7289 if (CONSP (p->status))
7290 symbol = XCAR (p->status);
7292 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7293 || EQ (symbol, Qclosed))
7295 if (delete_exited_processes)
7296 remove_process (proc);
7297 else
7298 deactivate_process (proc);
7301 /* The actions above may have further incremented p->tick.
7302 So set p->update_tick again so that an error in the sentinel will
7303 not cause this code to be run again. */
7304 p->update_tick = p->tick;
7305 /* Now output the message suitably. */
7306 exec_sentinel (proc, msg);
7307 if (BUFFERP (p->buffer))
7308 /* In case it uses %s in mode-line-format. */
7309 bset_update_mode_line (XBUFFER (p->buffer));
7311 } /* end for */
7313 return got_some_output;
7316 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7317 Sinternal_default_process_sentinel, 2, 2, 0,
7318 doc: /* Function used as default sentinel for processes.
7319 This inserts a status message into the process's buffer, if there is one. */)
7320 (Lisp_Object proc, Lisp_Object msg)
7322 Lisp_Object buffer, symbol;
7323 struct Lisp_Process *p;
7324 CHECK_PROCESS (proc);
7325 p = XPROCESS (proc);
7326 buffer = p->buffer;
7327 symbol = p->status;
7328 if (CONSP (symbol))
7329 symbol = XCAR (symbol);
7331 if (!EQ (symbol, Qrun) && !NILP (buffer))
7333 Lisp_Object tem;
7334 struct buffer *old = current_buffer;
7335 ptrdiff_t opoint, opoint_byte;
7336 ptrdiff_t before, before_byte;
7338 /* Avoid error if buffer is deleted
7339 (probably that's why the process is dead, too). */
7340 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7341 return Qnil;
7342 Fset_buffer (buffer);
7344 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7345 msg = (code_convert_string_norecord
7346 (msg, Vlocale_coding_system, 1));
7348 opoint = PT;
7349 opoint_byte = PT_BYTE;
7350 /* Insert new output into buffer
7351 at the current end-of-output marker,
7352 thus preserving logical ordering of input and output. */
7353 if (XMARKER (p->mark)->buffer)
7354 Fgoto_char (p->mark);
7355 else
7356 SET_PT_BOTH (ZV, ZV_BYTE);
7358 before = PT;
7359 before_byte = PT_BYTE;
7361 tem = BVAR (current_buffer, read_only);
7362 bset_read_only (current_buffer, Qnil);
7363 insert_string ("\nProcess ");
7364 { /* FIXME: temporary kludge. */
7365 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7366 insert_string (" ");
7367 Finsert (1, &msg);
7368 bset_read_only (current_buffer, tem);
7369 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7371 if (opoint >= before)
7372 SET_PT_BOTH (opoint + (PT - before),
7373 opoint_byte + (PT_BYTE - before_byte));
7374 else
7375 SET_PT_BOTH (opoint, opoint_byte);
7377 set_buffer_internal (old);
7379 return Qnil;
7383 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7384 Sset_process_coding_system, 1, 3, 0,
7385 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7386 DECODING will be used to decode subprocess output and ENCODING to
7387 encode subprocess input. */)
7388 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7390 CHECK_PROCESS (process);
7392 struct Lisp_Process *p = XPROCESS (process);
7394 Fcheck_coding_system (decoding);
7395 Fcheck_coding_system (encoding);
7396 encoding = coding_inherit_eol_type (encoding, Qnil);
7397 pset_decode_coding_system (p, decoding);
7398 pset_encode_coding_system (p, encoding);
7400 /* If the sockets haven't been set up yet, the final setup part of
7401 this will be called asynchronously. */
7402 if (p->infd < 0 || p->outfd < 0)
7403 return Qnil;
7405 setup_process_coding_systems (process);
7407 return Qnil;
7410 DEFUN ("process-coding-system",
7411 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7412 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7413 (register Lisp_Object process)
7415 CHECK_PROCESS (process);
7416 return Fcons (XPROCESS (process)->decode_coding_system,
7417 XPROCESS (process)->encode_coding_system);
7420 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7421 Sset_process_filter_multibyte, 2, 2, 0,
7422 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7423 If FLAG is non-nil, the filter is given multibyte strings.
7424 If FLAG is nil, the filter is given unibyte strings. In this case,
7425 all character code conversion except for end-of-line conversion is
7426 suppressed. */)
7427 (Lisp_Object process, Lisp_Object flag)
7429 CHECK_PROCESS (process);
7431 struct Lisp_Process *p = XPROCESS (process);
7432 if (NILP (flag))
7433 pset_decode_coding_system
7434 (p, raw_text_coding_system (p->decode_coding_system));
7436 /* If the sockets haven't been set up yet, the final setup part of
7437 this will be called asynchronously. */
7438 if (p->infd < 0 || p->outfd < 0)
7439 return Qnil;
7441 setup_process_coding_systems (process);
7443 return Qnil;
7446 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7447 Sprocess_filter_multibyte_p, 1, 1, 0,
7448 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7449 (Lisp_Object process)
7451 CHECK_PROCESS (process);
7452 struct Lisp_Process *p = XPROCESS (process);
7453 if (p->infd < 0)
7454 return Qnil;
7455 struct coding_system *coding = proc_decode_coding_system[p->infd];
7456 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7462 # ifdef HAVE_GPM
7464 void
7465 add_gpm_wait_descriptor (int desc)
7467 add_keyboard_wait_descriptor (desc);
7470 void
7471 delete_gpm_wait_descriptor (int desc)
7473 delete_keyboard_wait_descriptor (desc);
7476 # endif
7478 # ifdef USABLE_SIGIO
7480 /* Return true if *MASK has a bit set
7481 that corresponds to one of the keyboard input descriptors. */
7483 static bool
7484 keyboard_bit_set (fd_set *mask)
7486 int fd;
7488 for (fd = 0; fd <= max_desc; fd++)
7489 if (FD_ISSET (fd, mask)
7490 && ((fd_callback_info[fd].flags & (FOR_READ | KEYBOARD_FD))
7491 == (FOR_READ | KEYBOARD_FD)))
7492 return 1;
7494 return 0;
7496 # endif
7498 #else /* not subprocesses */
7500 /* This is referenced in thread.c:run_thread (which is never actually
7501 called, since threads are not enabled for this configuration. */
7502 void
7503 update_processes_for_thread_death (Lisp_Object dying_thread)
7507 /* Defined in msdos.c. */
7508 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7509 struct timespec *, void *);
7511 /* Implementation of wait_reading_process_output, assuming that there
7512 are no subprocesses. Used only by the MS-DOS build.
7514 Wait for timeout to elapse and/or keyboard input to be available.
7516 TIME_LIMIT is:
7517 timeout in seconds
7518 If negative, gobble data immediately available but don't wait for any.
7520 NSECS is:
7521 an additional duration to wait, measured in nanoseconds
7522 If TIME_LIMIT is zero, then:
7523 If NSECS == 0, there is no limit.
7524 If NSECS > 0, the timeout consists of NSECS only.
7525 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7527 READ_KBD is:
7528 0 to ignore keyboard input, or
7529 1 to return when input is available, or
7530 -1 means caller will actually read the input, so don't throw to
7531 the quit handler.
7533 see full version for other parameters. We know that wait_proc will
7534 always be NULL, since `subprocesses' isn't defined.
7536 DO_DISPLAY means redisplay should be done to show subprocess
7537 output that arrives.
7539 Return -1 signifying we got no output and did not try. */
7542 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7543 bool do_display,
7544 Lisp_Object wait_for_cell,
7545 struct Lisp_Process *wait_proc, int just_wait_proc)
7547 register int nfds;
7548 struct timespec end_time, timeout;
7549 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7551 if (TYPE_MAXIMUM (time_t) < time_limit)
7552 time_limit = TYPE_MAXIMUM (time_t);
7554 if (time_limit < 0 || nsecs < 0)
7555 wait = MINIMUM;
7556 else if (time_limit > 0 || nsecs > 0)
7558 wait = TIMEOUT;
7559 end_time = timespec_add (current_timespec (),
7560 make_timespec (time_limit, nsecs));
7562 else
7563 wait = INFINITY;
7565 /* Turn off periodic alarms (in case they are in use)
7566 and then turn off any other atimers,
7567 because the select emulator uses alarms. */
7568 stop_polling ();
7569 turn_on_atimers (0);
7571 while (1)
7573 bool timeout_reduced_for_timers = false;
7574 fd_set waitchannels;
7575 int xerrno;
7577 /* If calling from keyboard input, do not quit
7578 since we want to return C-g as an input character.
7579 Otherwise, do pending quit if requested. */
7580 if (read_kbd >= 0)
7581 maybe_quit ();
7583 /* Exit now if the cell we're waiting for became non-nil. */
7584 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7585 break;
7587 /* Compute time from now till when time limit is up. */
7588 /* Exit if already run out. */
7589 if (wait == TIMEOUT)
7591 struct timespec now = current_timespec ();
7592 if (timespec_cmp (end_time, now) <= 0)
7593 break;
7594 timeout = timespec_sub (end_time, now);
7596 else
7597 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7599 /* If our caller will not immediately handle keyboard events,
7600 run timer events directly.
7601 (Callers that will immediately read keyboard events
7602 call timer_delay on their own.) */
7603 if (NILP (wait_for_cell))
7605 struct timespec timer_delay;
7609 unsigned old_timers_run = timers_run;
7610 timer_delay = timer_check ();
7611 if (timers_run != old_timers_run && do_display)
7612 /* We must retry, since a timer may have requeued itself
7613 and that could alter the time delay. */
7614 redisplay_preserve_echo_area (14);
7615 else
7616 break;
7618 while (!detect_input_pending ());
7620 /* If there is unread keyboard input, also return. */
7621 if (read_kbd != 0
7622 && requeued_events_pending_p ())
7623 break;
7625 if (timespec_valid_p (timer_delay))
7627 if (timespec_cmp (timer_delay, timeout) < 0)
7629 timeout = timer_delay;
7630 timeout_reduced_for_timers = true;
7635 /* Cause C-g and alarm signals to take immediate action,
7636 and cause input available signals to zero out timeout. */
7637 if (read_kbd < 0)
7638 set_waiting_for_input (&timeout);
7640 /* If a frame has been newly mapped and needs updating,
7641 reprocess its display stuff. */
7642 if (frame_garbaged && do_display)
7644 clear_waiting_for_input ();
7645 redisplay_preserve_echo_area (15);
7646 if (read_kbd < 0)
7647 set_waiting_for_input (&timeout);
7650 /* Wait till there is something to do. */
7651 FD_ZERO (&waitchannels);
7652 if (read_kbd && detect_input_pending ())
7653 nfds = 0;
7654 else
7656 if (read_kbd || !NILP (wait_for_cell))
7657 FD_SET (0, &waitchannels);
7658 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7661 xerrno = errno;
7663 /* Make C-g and alarm signals set flags again. */
7664 clear_waiting_for_input ();
7666 /* If we woke up due to SIGWINCH, actually change size now. */
7667 do_pending_window_change (0);
7669 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7670 /* We waited the full specified time, so return now. */
7671 break;
7673 if (nfds == -1)
7675 /* If the system call was interrupted, then go around the
7676 loop again. */
7677 if (xerrno == EINTR)
7678 FD_ZERO (&waitchannels);
7679 else
7680 report_file_errno ("Failed select", Qnil, xerrno);
7683 /* Check for keyboard input. */
7685 if (read_kbd
7686 && detect_input_pending_run_timers (do_display))
7688 swallow_events (do_display);
7689 if (detect_input_pending_run_timers (do_display))
7690 break;
7693 /* If there is unread keyboard input, also return. */
7694 if (read_kbd
7695 && requeued_events_pending_p ())
7696 break;
7698 /* If wait_for_cell. check for keyboard input
7699 but don't run any timers.
7700 ??? (It seems wrong to me to check for keyboard
7701 input at all when wait_for_cell, but the code
7702 has been this way since July 1994.
7703 Try changing this after version 19.31.) */
7704 if (! NILP (wait_for_cell)
7705 && detect_input_pending ())
7707 swallow_events (do_display);
7708 if (detect_input_pending ())
7709 break;
7712 /* Exit now if the cell we're waiting for became non-nil. */
7713 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7714 break;
7717 start_polling ();
7719 return -1;
7722 #endif /* not subprocesses */
7724 /* The following functions are needed even if async subprocesses are
7725 not supported. Some of them are no-op stubs in that case. */
7727 #ifdef HAVE_TIMERFD
7729 /* Add FD, which is a descriptor returned by timerfd_create,
7730 to the set of non-keyboard input descriptors. */
7732 void
7733 add_timer_wait_descriptor (int fd)
7735 add_read_fd (fd, timerfd_callback, NULL);
7736 fd_callback_info[fd].flags &= ~KEYBOARD_FD;
7739 #endif /* HAVE_TIMERFD */
7741 /* If program file NAME starts with /: for quoting a magic
7742 name, remove that, preserving the multibyteness of NAME. */
7744 Lisp_Object
7745 remove_slash_colon (Lisp_Object name)
7747 return
7748 (SREF (name, 0) == '/' && SREF (name, 1) == ':'
7749 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7750 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7751 : name);
7754 /* Add DESC to the set of keyboard input descriptors. */
7756 void
7757 add_keyboard_wait_descriptor (int desc)
7759 #ifdef subprocesses /* Actually means "not MSDOS". */
7760 eassert (desc >= 0 && desc < FD_SETSIZE);
7761 fd_callback_info[desc].flags &= ~PROCESS_FD;
7762 fd_callback_info[desc].flags |= (FOR_READ | KEYBOARD_FD);
7763 if (desc > max_desc)
7764 max_desc = desc;
7765 #endif
7768 /* From now on, do not expect DESC to give keyboard input. */
7770 void
7771 delete_keyboard_wait_descriptor (int desc)
7773 #ifdef subprocesses
7774 eassert (desc >= 0 && desc < FD_SETSIZE);
7776 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7778 if (desc == max_desc)
7779 recompute_max_desc ();
7780 #endif
7783 /* Setup coding systems of PROCESS. */
7785 void
7786 setup_process_coding_systems (Lisp_Object process)
7788 #ifdef subprocesses
7789 struct Lisp_Process *p = XPROCESS (process);
7790 int inch = p->infd;
7791 int outch = p->outfd;
7792 Lisp_Object coding_system;
7794 if (inch < 0 || outch < 0)
7795 return;
7797 if (!proc_decode_coding_system[inch])
7798 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7799 coding_system = p->decode_coding_system;
7800 if (EQ (p->filter, Qinternal_default_process_filter)
7801 && BUFFERP (p->buffer))
7803 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7804 coding_system = raw_text_coding_system (coding_system);
7806 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7808 if (!proc_encode_coding_system[outch])
7809 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7810 setup_coding_system (p->encode_coding_system,
7811 proc_encode_coding_system[outch]);
7812 #endif
7815 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7816 doc: /* Return the (or a) live process associated with BUFFER.
7817 BUFFER may be a buffer or the name of one.
7818 Return nil if all processes associated with BUFFER have been
7819 deleted or killed. */)
7820 (register Lisp_Object buffer)
7822 #ifdef subprocesses
7823 register Lisp_Object buf, tail, proc;
7825 if (NILP (buffer)) return Qnil;
7826 buf = Fget_buffer (buffer);
7827 if (NILP (buf)) return Qnil;
7829 FOR_EACH_PROCESS (tail, proc)
7830 if (EQ (XPROCESS (proc)->buffer, buf))
7831 return proc;
7832 #endif /* subprocesses */
7833 return Qnil;
7836 DEFUN ("process-inherit-coding-system-flag",
7837 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7838 1, 1, 0,
7839 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7840 If this flag is t, `buffer-file-coding-system' of the buffer
7841 associated with PROCESS will inherit the coding system used to decode
7842 the process output. */)
7843 (register Lisp_Object process)
7845 #ifdef subprocesses
7846 CHECK_PROCESS (process);
7847 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7848 #else
7849 /* Ignore the argument and return the value of
7850 inherit-process-coding-system. */
7851 return inherit_process_coding_system ? Qt : Qnil;
7852 #endif
7855 /* Kill all processes associated with `buffer'.
7856 If `buffer' is nil, kill all processes. */
7858 void
7859 kill_buffer_processes (Lisp_Object buffer)
7861 #ifdef subprocesses
7862 Lisp_Object tail, proc;
7864 FOR_EACH_PROCESS (tail, proc)
7865 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7867 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7868 Fdelete_process (proc);
7869 else if (XPROCESS (proc)->infd >= 0)
7870 process_send_signal (proc, SIGHUP, Qnil, 1);
7872 #else /* subprocesses */
7873 /* Since we have no subprocesses, this does nothing. */
7874 #endif /* subprocesses */
7877 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7878 Swaiting_for_user_input_p, 0, 0, 0,
7879 doc: /* Return non-nil if Emacs is waiting for input from the user.
7880 This is intended for use by asynchronous process output filters and sentinels. */)
7881 (void)
7883 #ifdef subprocesses
7884 return (waiting_for_user_input_p ? Qt : Qnil);
7885 #else
7886 return Qnil;
7887 #endif
7890 /* Stop reading input from keyboard sources. */
7892 void
7893 hold_keyboard_input (void)
7895 kbd_is_on_hold = 1;
7898 /* Resume reading input from keyboard sources. */
7900 void
7901 unhold_keyboard_input (void)
7903 kbd_is_on_hold = 0;
7906 /* Return true if keyboard input is on hold, zero otherwise. */
7908 bool
7909 kbd_on_hold_p (void)
7911 return kbd_is_on_hold;
7915 /* Enumeration of and access to system processes a-la ps(1). */
7917 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7918 0, 0, 0,
7919 doc: /* Return a list of numerical process IDs of all running processes.
7920 If this functionality is unsupported, return nil.
7922 See `process-attributes' for getting attributes of a process given its ID. */)
7923 (void)
7925 return list_system_processes ();
7928 DEFUN ("process-attributes", Fprocess_attributes,
7929 Sprocess_attributes, 1, 1, 0,
7930 doc: /* Return attributes of the process given by its PID, a number.
7932 Value is an alist where each element is a cons cell of the form
7934 (KEY . VALUE)
7936 If this functionality is unsupported, the value is nil.
7938 See `list-system-processes' for getting a list of all process IDs.
7940 The KEYs of the attributes that this function may return are listed
7941 below, together with the type of the associated VALUE (in parentheses).
7942 Not all platforms support all of these attributes; unsupported
7943 attributes will not appear in the returned alist.
7944 Unless explicitly indicated otherwise, numbers can have either
7945 integer or floating point values.
7947 euid -- Effective user User ID of the process (number)
7948 user -- User name corresponding to euid (string)
7949 egid -- Effective user Group ID of the process (number)
7950 group -- Group name corresponding to egid (string)
7951 comm -- Command name (executable name only) (string)
7952 state -- Process state code, such as "S", "R", or "T" (string)
7953 ppid -- Parent process ID (number)
7954 pgrp -- Process group ID (number)
7955 sess -- Session ID, i.e. process ID of session leader (number)
7956 ttname -- Controlling tty name (string)
7957 tpgid -- ID of foreground process group on the process's tty (number)
7958 minflt -- number of minor page faults (number)
7959 majflt -- number of major page faults (number)
7960 cminflt -- cumulative number of minor page faults (number)
7961 cmajflt -- cumulative number of major page faults (number)
7962 utime -- user time used by the process, in (current-time) format,
7963 which is a list of integers (HIGH LOW USEC PSEC)
7964 stime -- system time used by the process (current-time)
7965 time -- sum of utime and stime (current-time)
7966 cutime -- user time used by the process and its children (current-time)
7967 cstime -- system time used by the process and its children (current-time)
7968 ctime -- sum of cutime and cstime (current-time)
7969 pri -- priority of the process (number)
7970 nice -- nice value of the process (number)
7971 thcount -- process thread count (number)
7972 start -- time the process started (current-time)
7973 vsize -- virtual memory size of the process in KB's (number)
7974 rss -- resident set size of the process in KB's (number)
7975 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7976 pcpu -- percents of CPU time used by the process (floating-point number)
7977 pmem -- percents of total physical memory used by process's resident set
7978 (floating-point number)
7979 args -- command line which invoked the process (string). */)
7980 ( Lisp_Object pid)
7982 return system_process_attributes (pid);
7985 #ifdef subprocesses
7986 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7987 Invoke this after init_process_emacs, and after glib and/or GNUstep
7988 futz with the SIGCHLD handler, but before Emacs forks any children.
7989 This function's caller should block SIGCHLD. */
7991 void
7992 catch_child_signal (void)
7994 struct sigaction action, old_action;
7995 sigset_t oldset;
7996 emacs_sigaction_init (&action, deliver_child_signal);
7997 block_child_signal (&oldset);
7998 sigaction (SIGCHLD, &action, &old_action);
7999 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
8000 || ! (old_action.sa_flags & SA_SIGINFO));
8002 if (old_action.sa_handler != deliver_child_signal)
8003 lib_child_handler
8004 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
8005 ? dummy_handler
8006 : old_action.sa_handler);
8007 unblock_child_signal (&oldset);
8009 #endif /* subprocesses */
8011 /* Limit the number of open files to the value it had at startup. */
8013 void
8014 restore_nofile_limit (void)
8016 #ifdef HAVE_SETRLIMIT
8017 if (FD_SETSIZE < nofile_limit.rlim_cur)
8018 setrlimit (RLIMIT_NOFILE, &nofile_limit);
8019 #endif
8023 /* This is not called "init_process" because that is the name of a
8024 Mach system call, so it would cause problems on Darwin systems. */
8025 void
8026 init_process_emacs (int sockfd)
8028 #ifdef subprocesses
8029 int i;
8031 inhibit_sentinels = 0;
8033 #ifndef CANNOT_DUMP
8034 if (! noninteractive || initialized)
8035 #endif
8037 #if defined HAVE_GLIB && !defined WINDOWSNT
8038 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8039 this should always fail, but is enough to initialize glib's
8040 private SIGCHLD handler, allowing catch_child_signal to copy
8041 it into lib_child_handler. */
8042 g_source_unref (g_child_watch_source_new (getpid ()));
8043 #endif
8044 catch_child_signal ();
8047 #ifdef HAVE_SETRLIMIT
8048 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8049 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
8050 nofile_limit.rlim_cur = 0;
8051 else if (FD_SETSIZE < nofile_limit.rlim_cur)
8053 struct rlimit rlim = nofile_limit;
8054 rlim.rlim_cur = FD_SETSIZE;
8055 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
8056 nofile_limit.rlim_cur = 0;
8058 #endif
8060 external_sock_fd = sockfd;
8061 max_desc = -1;
8062 memset (fd_callback_info, 0, sizeof (fd_callback_info));
8064 num_pending_connects = 0;
8066 process_output_delay_count = 0;
8067 process_output_skip = 0;
8069 /* Don't do this, it caused infinite select loops. The display
8070 method should call add_keyboard_wait_descriptor on stdin if it
8071 needs that. */
8072 #if 0
8073 FD_SET (0, &input_wait_mask);
8074 #endif
8076 Vprocess_alist = Qnil;
8077 deleted_pid_list = Qnil;
8078 for (i = 0; i < FD_SETSIZE; i++)
8080 chan_process[i] = Qnil;
8081 proc_buffered_char[i] = -1;
8083 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
8084 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
8085 #ifdef DATAGRAM_SOCKETS
8086 memset (datagram_address, 0, sizeof datagram_address);
8087 #endif
8089 #if defined (DARWIN_OS)
8090 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8091 processes. As such, we only change the default value. */
8092 if (initialized)
8094 char const *release = (STRINGP (Voperating_system_release)
8095 ? SSDATA (Voperating_system_release)
8096 : 0);
8097 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
8098 Vprocess_connection_type = Qnil;
8101 #endif
8102 #endif /* subprocesses */
8103 kbd_is_on_hold = 0;
8106 void
8107 syms_of_process (void)
8109 #ifdef subprocesses
8111 DEFSYM (Qprocessp, "processp");
8112 DEFSYM (Qrun, "run");
8113 DEFSYM (Qstop, "stop");
8114 DEFSYM (Qsignal, "signal");
8116 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8117 here again. */
8119 DEFSYM (Qopen, "open");
8120 DEFSYM (Qclosed, "closed");
8121 DEFSYM (Qconnect, "connect");
8122 DEFSYM (Qfailed, "failed");
8123 DEFSYM (Qlisten, "listen");
8124 DEFSYM (Qlocal, "local");
8125 DEFSYM (Qipv4, "ipv4");
8126 #ifdef AF_INET6
8127 DEFSYM (Qipv6, "ipv6");
8128 #endif
8129 DEFSYM (Qdatagram, "datagram");
8130 DEFSYM (Qseqpacket, "seqpacket");
8132 DEFSYM (QCport, ":port");
8133 DEFSYM (QCspeed, ":speed");
8134 DEFSYM (QCprocess, ":process");
8136 DEFSYM (QCbytesize, ":bytesize");
8137 DEFSYM (QCstopbits, ":stopbits");
8138 DEFSYM (QCparity, ":parity");
8139 DEFSYM (Qodd, "odd");
8140 DEFSYM (Qeven, "even");
8141 DEFSYM (QCflowcontrol, ":flowcontrol");
8142 DEFSYM (Qhw, "hw");
8143 DEFSYM (Qsw, "sw");
8144 DEFSYM (QCsummary, ":summary");
8146 DEFSYM (Qreal, "real");
8147 DEFSYM (Qnetwork, "network");
8148 DEFSYM (Qserial, "serial");
8149 DEFSYM (QCbuffer, ":buffer");
8150 DEFSYM (QChost, ":host");
8151 DEFSYM (QCservice, ":service");
8152 DEFSYM (QClocal, ":local");
8153 DEFSYM (QCremote, ":remote");
8154 DEFSYM (QCcoding, ":coding");
8155 DEFSYM (QCserver, ":server");
8156 DEFSYM (QCnowait, ":nowait");
8157 DEFSYM (QCsentinel, ":sentinel");
8158 DEFSYM (QCuse_external_socket, ":use-external-socket");
8159 DEFSYM (QCtls_parameters, ":tls-parameters");
8160 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
8161 DEFSYM (QClog, ":log");
8162 DEFSYM (QCnoquery, ":noquery");
8163 DEFSYM (QCstop, ":stop");
8164 DEFSYM (QCplist, ":plist");
8165 DEFSYM (QCcommand, ":command");
8166 DEFSYM (QCconnection_type, ":connection-type");
8167 DEFSYM (QCstderr, ":stderr");
8168 DEFSYM (Qpty, "pty");
8169 DEFSYM (Qpipe, "pipe");
8171 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
8173 staticpro (&Vprocess_alist);
8174 staticpro (&deleted_pid_list);
8176 #endif /* subprocesses */
8178 DEFSYM (QCname, ":name");
8179 DEFSYM (QCtype, ":type");
8181 DEFSYM (Qeuid, "euid");
8182 DEFSYM (Qegid, "egid");
8183 DEFSYM (Quser, "user");
8184 DEFSYM (Qgroup, "group");
8185 DEFSYM (Qcomm, "comm");
8186 DEFSYM (Qstate, "state");
8187 DEFSYM (Qppid, "ppid");
8188 DEFSYM (Qpgrp, "pgrp");
8189 DEFSYM (Qsess, "sess");
8190 DEFSYM (Qttname, "ttname");
8191 DEFSYM (Qtpgid, "tpgid");
8192 DEFSYM (Qminflt, "minflt");
8193 DEFSYM (Qmajflt, "majflt");
8194 DEFSYM (Qcminflt, "cminflt");
8195 DEFSYM (Qcmajflt, "cmajflt");
8196 DEFSYM (Qutime, "utime");
8197 DEFSYM (Qstime, "stime");
8198 DEFSYM (Qtime, "time");
8199 DEFSYM (Qcutime, "cutime");
8200 DEFSYM (Qcstime, "cstime");
8201 DEFSYM (Qctime, "ctime");
8202 #ifdef subprocesses
8203 DEFSYM (Qinternal_default_process_sentinel,
8204 "internal-default-process-sentinel");
8205 DEFSYM (Qinternal_default_process_filter,
8206 "internal-default-process-filter");
8207 #endif
8208 DEFSYM (Qpri, "pri");
8209 DEFSYM (Qnice, "nice");
8210 DEFSYM (Qthcount, "thcount");
8211 DEFSYM (Qstart, "start");
8212 DEFSYM (Qvsize, "vsize");
8213 DEFSYM (Qrss, "rss");
8214 DEFSYM (Qetime, "etime");
8215 DEFSYM (Qpcpu, "pcpu");
8216 DEFSYM (Qpmem, "pmem");
8217 DEFSYM (Qargs, "args");
8219 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
8220 doc: /* Non-nil means delete processes immediately when they exit.
8221 A value of nil means don't delete them until `list-processes' is run. */);
8223 delete_exited_processes = 1;
8225 #ifdef subprocesses
8226 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
8227 doc: /* Control type of device used to communicate with subprocesses.
8228 Values are nil to use a pipe, or t or `pty' to use a pty.
8229 The value has no effect if the system has no ptys or if all ptys are busy:
8230 then a pipe is used in any case.
8231 The value takes effect when `start-process' is called. */);
8232 Vprocess_connection_type = Qt;
8234 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8235 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8236 On some systems, when Emacs reads the output from a subprocess, the output data
8237 is read in very small blocks, potentially resulting in very poor performance.
8238 This behavior can be remedied to some extent by setting this variable to a
8239 non-nil value, as it will automatically delay reading from such processes, to
8240 allow them to produce more output before Emacs tries to read it.
8241 If the value is t, the delay is reset after each write to the process; any other
8242 non-nil value means that the delay is not reset on write.
8243 The variable takes effect when `start-process' is called. */);
8244 Vprocess_adaptive_read_buffering = Qt;
8246 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions,
8247 doc: /* List of functions to be called for `interrupt-process'.
8248 The arguments of the functions are the same as for `interrupt-process'.
8249 These functions are called in the order of the list, until one of them
8250 returns non-`nil'. */);
8251 Vinterrupt_process_functions = list1 (Qinternal_default_interrupt_process);
8253 DEFSYM (Qinternal_default_interrupt_process,
8254 "internal-default-interrupt-process");
8255 DEFSYM (Qinterrupt_process_functions, "interrupt-process-functions");
8257 defsubr (&Sprocessp);
8258 defsubr (&Sget_process);
8259 defsubr (&Sdelete_process);
8260 defsubr (&Sprocess_status);
8261 defsubr (&Sprocess_exit_status);
8262 defsubr (&Sprocess_id);
8263 defsubr (&Sprocess_name);
8264 defsubr (&Sprocess_tty_name);
8265 defsubr (&Sprocess_command);
8266 defsubr (&Sset_process_buffer);
8267 defsubr (&Sprocess_buffer);
8268 defsubr (&Sprocess_mark);
8269 defsubr (&Sset_process_filter);
8270 defsubr (&Sprocess_filter);
8271 defsubr (&Sset_process_sentinel);
8272 defsubr (&Sprocess_sentinel);
8273 defsubr (&Sset_process_thread);
8274 defsubr (&Sprocess_thread);
8275 defsubr (&Sset_process_window_size);
8276 defsubr (&Sset_process_inherit_coding_system_flag);
8277 defsubr (&Sset_process_query_on_exit_flag);
8278 defsubr (&Sprocess_query_on_exit_flag);
8279 defsubr (&Sprocess_contact);
8280 defsubr (&Sprocess_plist);
8281 defsubr (&Sset_process_plist);
8282 defsubr (&Sprocess_list);
8283 defsubr (&Smake_process);
8284 defsubr (&Smake_pipe_process);
8285 defsubr (&Sserial_process_configure);
8286 defsubr (&Smake_serial_process);
8287 defsubr (&Sset_network_process_option);
8288 defsubr (&Smake_network_process);
8289 defsubr (&Sformat_network_address);
8290 defsubr (&Snetwork_interface_list);
8291 defsubr (&Snetwork_interface_info);
8292 #ifdef DATAGRAM_SOCKETS
8293 defsubr (&Sprocess_datagram_address);
8294 defsubr (&Sset_process_datagram_address);
8295 #endif
8296 defsubr (&Saccept_process_output);
8297 defsubr (&Sprocess_send_region);
8298 defsubr (&Sprocess_send_string);
8299 defsubr (&Sinternal_default_interrupt_process);
8300 defsubr (&Sinterrupt_process);
8301 defsubr (&Skill_process);
8302 defsubr (&Squit_process);
8303 defsubr (&Sstop_process);
8304 defsubr (&Scontinue_process);
8305 defsubr (&Sprocess_running_child_p);
8306 defsubr (&Sprocess_send_eof);
8307 defsubr (&Ssignal_process);
8308 defsubr (&Swaiting_for_user_input_p);
8309 defsubr (&Sprocess_type);
8310 defsubr (&Sinternal_default_process_sentinel);
8311 defsubr (&Sinternal_default_process_filter);
8312 defsubr (&Sset_process_coding_system);
8313 defsubr (&Sprocess_coding_system);
8314 defsubr (&Sset_process_filter_multibyte);
8315 defsubr (&Sprocess_filter_multibyte_p);
8318 Lisp_Object subfeatures = Qnil;
8319 const struct socket_options *sopt;
8321 #define ADD_SUBFEATURE(key, val) \
8322 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8324 ADD_SUBFEATURE (QCnowait, Qt);
8325 #ifdef DATAGRAM_SOCKETS
8326 ADD_SUBFEATURE (QCtype, Qdatagram);
8327 #endif
8328 #ifdef HAVE_SEQPACKET
8329 ADD_SUBFEATURE (QCtype, Qseqpacket);
8330 #endif
8331 #ifdef HAVE_LOCAL_SOCKETS
8332 ADD_SUBFEATURE (QCfamily, Qlocal);
8333 #endif
8334 ADD_SUBFEATURE (QCfamily, Qipv4);
8335 #ifdef AF_INET6
8336 ADD_SUBFEATURE (QCfamily, Qipv6);
8337 #endif
8338 #ifdef HAVE_GETSOCKNAME
8339 ADD_SUBFEATURE (QCservice, Qt);
8340 #endif
8341 ADD_SUBFEATURE (QCserver, Qt);
8343 for (sopt = socket_options; sopt->name; sopt++)
8344 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8346 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8349 #endif /* subprocesses */
8351 defsubr (&Sget_buffer_process);
8352 defsubr (&Sprocess_inherit_coding_system_flag);
8353 defsubr (&Slist_system_processes);
8354 defsubr (&Sprocess_attributes);