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