]> code.delx.au - gnu-emacs/blob - src/process.c
Prefer SOCK_NONBLOCK to O_NONBLOCK
[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
2347 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2348
2349 static ptrdiff_t
2350 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2351 {
2352 struct Lisp_Vector *p;
2353
2354 if (VECTORP (address))
2355 {
2356 p = XVECTOR (address);
2357 if (p->header.size == 5)
2358 {
2359 *familyp = AF_INET;
2360 return sizeof (struct sockaddr_in);
2361 }
2362 #ifdef AF_INET6
2363 else if (p->header.size == 9)
2364 {
2365 *familyp = AF_INET6;
2366 return sizeof (struct sockaddr_in6);
2367 }
2368 #endif
2369 }
2370 #ifdef HAVE_LOCAL_SOCKETS
2371 else if (STRINGP (address))
2372 {
2373 *familyp = AF_LOCAL;
2374 return sizeof (struct sockaddr_un);
2375 }
2376 #endif
2377 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2378 && VECTORP (XCDR (address)))
2379 {
2380 struct sockaddr *sa;
2381 p = XVECTOR (XCDR (address));
2382 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2383 return 0;
2384 *familyp = XINT (XCAR (address));
2385 return p->header.size + sizeof (sa->sa_family);
2386 }
2387 return 0;
2388 }
2389
2390 /* Convert an address object (vector or string) to an internal sockaddr.
2391
2392 The address format has been basically validated by
2393 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2394 it could have come from user data. So if FAMILY is not valid,
2395 we return after zeroing *SA. */
2396
2397 static void
2398 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2399 {
2400 register struct Lisp_Vector *p;
2401 register unsigned char *cp = NULL;
2402 register int i;
2403 EMACS_INT hostport;
2404
2405 memset (sa, 0, len);
2406
2407 if (VECTORP (address))
2408 {
2409 p = XVECTOR (address);
2410 if (family == AF_INET)
2411 {
2412 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2413 len = sizeof (sin->sin_addr) + 1;
2414 hostport = XINT (p->contents[--len]);
2415 sin->sin_port = htons (hostport);
2416 cp = (unsigned char *)&sin->sin_addr;
2417 sa->sa_family = family;
2418 }
2419 #ifdef AF_INET6
2420 else if (family == AF_INET6)
2421 {
2422 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2423 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2424 len = sizeof (sin6->sin6_addr) / 2 + 1;
2425 hostport = XINT (p->contents[--len]);
2426 sin6->sin6_port = htons (hostport);
2427 for (i = 0; i < len; i++)
2428 if (INTEGERP (p->contents[i]))
2429 {
2430 int j = XFASTINT (p->contents[i]) & 0xffff;
2431 ip6[i] = ntohs (j);
2432 }
2433 sa->sa_family = family;
2434 return;
2435 }
2436 #endif
2437 else
2438 return;
2439 }
2440 else if (STRINGP (address))
2441 {
2442 #ifdef HAVE_LOCAL_SOCKETS
2443 if (family == AF_LOCAL)
2444 {
2445 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2446 cp = SDATA (address);
2447 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2448 sockun->sun_path[i] = *cp++;
2449 sa->sa_family = family;
2450 }
2451 #endif
2452 return;
2453 }
2454 else
2455 {
2456 p = XVECTOR (XCDR (address));
2457 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2458 }
2459
2460 for (i = 0; i < len; i++)
2461 if (INTEGERP (p->contents[i]))
2462 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2463 }
2464
2465 #ifdef DATAGRAM_SOCKETS
2466 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2467 1, 1, 0,
2468 doc: /* Get the current datagram address associated with PROCESS.
2469 If PROCESS is a non-blocking network process that hasn't been fully
2470 set up yet, this function will block until socket setup has completed. */)
2471 (Lisp_Object process)
2472 {
2473 int channel;
2474
2475 CHECK_PROCESS (process);
2476
2477 if (NETCONN_P (process))
2478 wait_for_socket_fds (process, "process-datagram-address");
2479
2480 if (!DATAGRAM_CONN_P (process))
2481 return Qnil;
2482
2483 channel = XPROCESS (process)->infd;
2484 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2485 datagram_address[channel].len);
2486 }
2487
2488 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2489 2, 2, 0,
2490 doc: /* Set the datagram address for PROCESS to ADDRESS.
2491 Return nil upon error setting address, ADDRESS otherwise.
2492
2493 If PROCESS is a non-blocking network process that hasn't been fully
2494 set up yet, this function will block until socket setup has completed. */)
2495 (Lisp_Object process, Lisp_Object address)
2496 {
2497 int channel;
2498 int family;
2499 ptrdiff_t len;
2500
2501 CHECK_PROCESS (process);
2502
2503 if (NETCONN_P (process))
2504 wait_for_socket_fds (process, "set-process-datagram-address");
2505
2506 if (!DATAGRAM_CONN_P (process))
2507 return Qnil;
2508
2509 channel = XPROCESS (process)->infd;
2510
2511 len = get_lisp_to_sockaddr_size (address, &family);
2512 if (len == 0 || datagram_address[channel].len != len)
2513 return Qnil;
2514 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2515 return address;
2516 }
2517 #endif
2518 \f
2519
2520 static const struct socket_options {
2521 /* The name of this option. Should be lowercase version of option
2522 name without SO_ prefix. */
2523 const char *name;
2524 /* Option level SOL_... */
2525 int optlevel;
2526 /* Option number SO_... */
2527 int optnum;
2528 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2529 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2530 } socket_options[] =
2531 {
2532 #ifdef SO_BINDTODEVICE
2533 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2534 #endif
2535 #ifdef SO_BROADCAST
2536 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2537 #endif
2538 #ifdef SO_DONTROUTE
2539 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2540 #endif
2541 #ifdef SO_KEEPALIVE
2542 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2543 #endif
2544 #ifdef SO_LINGER
2545 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2546 #endif
2547 #ifdef SO_OOBINLINE
2548 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2549 #endif
2550 #ifdef SO_PRIORITY
2551 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2552 #endif
2553 #ifdef SO_REUSEADDR
2554 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2555 #endif
2556 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2557 };
2558
2559 /* Set option OPT to value VAL on socket S.
2560
2561 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2562 Signals an error if setting a known option fails.
2563 */
2564
2565 static int
2566 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2567 {
2568 char *name;
2569 const struct socket_options *sopt;
2570 int ret = 0;
2571
2572 CHECK_SYMBOL (opt);
2573
2574 name = SSDATA (SYMBOL_NAME (opt));
2575 for (sopt = socket_options; sopt->name; sopt++)
2576 if (strcmp (name, sopt->name) == 0)
2577 break;
2578
2579 switch (sopt->opttype)
2580 {
2581 case SOPT_BOOL:
2582 {
2583 int optval;
2584 optval = NILP (val) ? 0 : 1;
2585 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2586 &optval, sizeof (optval));
2587 break;
2588 }
2589
2590 case SOPT_INT:
2591 {
2592 int optval;
2593 if (TYPE_RANGED_INTEGERP (int, val))
2594 optval = XINT (val);
2595 else
2596 error ("Bad option value for %s", name);
2597 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2598 &optval, sizeof (optval));
2599 break;
2600 }
2601
2602 #ifdef SO_BINDTODEVICE
2603 case SOPT_IFNAME:
2604 {
2605 char devname[IFNAMSIZ + 1];
2606
2607 /* This is broken, at least in the Linux 2.4 kernel.
2608 To unbind, the arg must be a zero integer, not the empty string.
2609 This should work on all systems. KFS. 2003-09-23. */
2610 memset (devname, 0, sizeof devname);
2611 if (STRINGP (val))
2612 {
2613 char *arg = SSDATA (val);
2614 int len = min (strlen (arg), IFNAMSIZ);
2615 memcpy (devname, arg, len);
2616 }
2617 else if (!NILP (val))
2618 error ("Bad option value for %s", name);
2619 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2620 devname, IFNAMSIZ);
2621 break;
2622 }
2623 #endif
2624
2625 #ifdef SO_LINGER
2626 case SOPT_LINGER:
2627 {
2628 struct linger linger;
2629
2630 linger.l_onoff = 1;
2631 linger.l_linger = 0;
2632 if (TYPE_RANGED_INTEGERP (int, val))
2633 linger.l_linger = XINT (val);
2634 else
2635 linger.l_onoff = NILP (val) ? 0 : 1;
2636 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2637 &linger, sizeof (linger));
2638 break;
2639 }
2640 #endif
2641
2642 default:
2643 return 0;
2644 }
2645
2646 if (ret < 0)
2647 {
2648 int setsockopt_errno = errno;
2649 report_file_errno ("Cannot set network option", list2 (opt, val),
2650 setsockopt_errno);
2651 }
2652
2653 return (1 << sopt->optbit);
2654 }
2655
2656
2657 DEFUN ("set-network-process-option",
2658 Fset_network_process_option, Sset_network_process_option,
2659 3, 4, 0,
2660 doc: /* For network process PROCESS set option OPTION to value VALUE.
2661 See `make-network-process' for a list of options and values.
2662 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2663 OPTION is not a supported option, return nil instead; otherwise return t.
2664
2665 If PROCESS is a non-blocking network process that hasn't been fully
2666 set up yet, this function will block until socket setup has completed. */)
2667 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2668 {
2669 int s;
2670 struct Lisp_Process *p;
2671
2672 CHECK_PROCESS (process);
2673 p = XPROCESS (process);
2674 if (!NETCONN1_P (p))
2675 error ("Process is not a network process");
2676
2677 wait_for_socket_fds (process, "set-network-process-option");
2678
2679 s = p->infd;
2680 if (s < 0)
2681 error ("Process is not running");
2682
2683 if (set_socket_option (s, option, value))
2684 {
2685 pset_childp (p, Fplist_put (p->childp, option, value));
2686 return Qt;
2687 }
2688
2689 if (NILP (no_error))
2690 error ("Unknown or unsupported option");
2691
2692 return Qnil;
2693 }
2694
2695 \f
2696 DEFUN ("serial-process-configure",
2697 Fserial_process_configure,
2698 Sserial_process_configure,
2699 0, MANY, 0,
2700 doc: /* Configure speed, bytesize, etc. of a serial process.
2701
2702 Arguments are specified as keyword/argument pairs. Attributes that
2703 are not given are re-initialized from the process's current
2704 configuration (available via the function `process-contact') or set to
2705 reasonable default values. The following arguments are defined:
2706
2707 :process PROCESS
2708 :name NAME
2709 :buffer BUFFER
2710 :port PORT
2711 -- Any of these arguments can be given to identify the process that is
2712 to be configured. If none of these arguments is given, the current
2713 buffer's process is used.
2714
2715 :speed SPEED -- SPEED is the speed of the serial port in bits per
2716 second, also called baud rate. Any value can be given for SPEED, but
2717 most serial ports work only at a few defined values between 1200 and
2718 115200, with 9600 being the most common value. If SPEED is nil, the
2719 serial port is not configured any further, i.e., all other arguments
2720 are ignored. This may be useful for special serial ports such as
2721 Bluetooth-to-serial converters which can only be configured through AT
2722 commands. A value of nil for SPEED can be used only when passed
2723 through `make-serial-process' or `serial-term'.
2724
2725 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2726 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2727
2728 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2729 `odd' (use odd parity), or the symbol `even' (use even parity). If
2730 PARITY is not given, no parity is used.
2731
2732 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2733 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2734 is not given or nil, 1 stopbit is used.
2735
2736 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2737 flowcontrol to be used, which is either nil (don't use flowcontrol),
2738 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2739 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2740 flowcontrol is used.
2741
2742 `serial-process-configure' is called by `make-serial-process' for the
2743 initial configuration of the serial port.
2744
2745 Examples:
2746
2747 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2748
2749 \(serial-process-configure
2750 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2751
2752 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2753
2754 usage: (serial-process-configure &rest ARGS) */)
2755 (ptrdiff_t nargs, Lisp_Object *args)
2756 {
2757 struct Lisp_Process *p;
2758 Lisp_Object contact = Qnil;
2759 Lisp_Object proc = Qnil;
2760
2761 contact = Flist (nargs, args);
2762
2763 proc = Fplist_get (contact, QCprocess);
2764 if (NILP (proc))
2765 proc = Fplist_get (contact, QCname);
2766 if (NILP (proc))
2767 proc = Fplist_get (contact, QCbuffer);
2768 if (NILP (proc))
2769 proc = Fplist_get (contact, QCport);
2770 proc = get_process (proc);
2771 p = XPROCESS (proc);
2772 if (!EQ (p->type, Qserial))
2773 error ("Not a serial process");
2774
2775 if (NILP (Fplist_get (p->childp, QCspeed)))
2776 return Qnil;
2777
2778 serial_configure (p, contact);
2779 return Qnil;
2780 }
2781
2782 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2783 0, MANY, 0,
2784 doc: /* Create and return a serial port process.
2785
2786 In Emacs, serial port connections are represented by process objects,
2787 so input and output work as for subprocesses, and `delete-process'
2788 closes a serial port connection. However, a serial process has no
2789 process id, it cannot be signaled, and the status codes are different
2790 from normal processes.
2791
2792 `make-serial-process' creates a process and a buffer, on which you
2793 probably want to use `process-send-string'. Try \\[serial-term] for
2794 an interactive terminal. See below for examples.
2795
2796 Arguments are specified as keyword/argument pairs. The following
2797 arguments are defined:
2798
2799 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2800 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2801 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2802 the backslashes in strings).
2803
2804 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2805 which this function calls.
2806
2807 :name NAME -- NAME is the name of the process. If NAME is not given,
2808 the value of PORT is used.
2809
2810 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2811 with the process. Process output goes at the end of that buffer,
2812 unless you specify an output stream or filter function to handle the
2813 output. If BUFFER is not given, the value of NAME is used.
2814
2815 :coding CODING -- If CODING is a symbol, it specifies the coding
2816 system used for both reading and writing for this process. If CODING
2817 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2818 ENCODING is used for writing.
2819
2820 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2821 the process is running. If BOOL is not given, query before exiting.
2822
2823 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2824 In the stopped state, a serial process does not accept incoming data,
2825 but you can send outgoing data. The stopped state is cleared by
2826 `continue-process' and set by `stop-process'.
2827
2828 :filter FILTER -- Install FILTER as the process filter.
2829
2830 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2831
2832 :plist PLIST -- Install PLIST as the initial plist of the process.
2833
2834 :bytesize
2835 :parity
2836 :stopbits
2837 :flowcontrol
2838 -- This function calls `serial-process-configure' to handle these
2839 arguments.
2840
2841 The original argument list, possibly modified by later configuration,
2842 is available via the function `process-contact'.
2843
2844 Examples:
2845
2846 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2847
2848 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2849
2850 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2851
2852 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2853
2854 usage: (make-serial-process &rest ARGS) */)
2855 (ptrdiff_t nargs, Lisp_Object *args)
2856 {
2857 int fd = -1;
2858 Lisp_Object proc, contact, port;
2859 struct Lisp_Process *p;
2860 Lisp_Object name, buffer;
2861 Lisp_Object tem, val;
2862 ptrdiff_t specpdl_count;
2863
2864 if (nargs == 0)
2865 return Qnil;
2866
2867 contact = Flist (nargs, args);
2868
2869 port = Fplist_get (contact, QCport);
2870 if (NILP (port))
2871 error ("No port specified");
2872 CHECK_STRING (port);
2873
2874 if (NILP (Fplist_member (contact, QCspeed)))
2875 error (":speed not specified");
2876 if (!NILP (Fplist_get (contact, QCspeed)))
2877 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2878
2879 name = Fplist_get (contact, QCname);
2880 if (NILP (name))
2881 name = port;
2882 CHECK_STRING (name);
2883 proc = make_process (name);
2884 specpdl_count = SPECPDL_INDEX ();
2885 record_unwind_protect (remove_process, proc);
2886 p = XPROCESS (proc);
2887
2888 fd = serial_open (port);
2889 p->open_fd[SUBPROCESS_STDIN] = fd;
2890 p->infd = fd;
2891 p->outfd = fd;
2892 if (fd > max_process_desc)
2893 max_process_desc = fd;
2894 chan_process[fd] = proc;
2895
2896 buffer = Fplist_get (contact, QCbuffer);
2897 if (NILP (buffer))
2898 buffer = name;
2899 buffer = Fget_buffer_create (buffer);
2900 pset_buffer (p, buffer);
2901
2902 pset_childp (p, contact);
2903 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2904 pset_type (p, Qserial);
2905 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2906 pset_filter (p, Fplist_get (contact, QCfilter));
2907 pset_log (p, Qnil);
2908 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2909 p->kill_without_query = 1;
2910 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2911 pset_command (p, Qt);
2912 eassert (! p->pty_flag);
2913
2914 if (!EQ (p->command, Qt))
2915 {
2916 FD_SET (fd, &input_wait_mask);
2917 FD_SET (fd, &non_keyboard_wait_mask);
2918 }
2919
2920 if (BUFFERP (buffer))
2921 {
2922 set_marker_both (p->mark, buffer,
2923 BUF_ZV (XBUFFER (buffer)),
2924 BUF_ZV_BYTE (XBUFFER (buffer)));
2925 }
2926
2927 tem = Fplist_member (contact, QCcoding);
2928 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2929 tem = Qnil;
2930
2931 val = Qnil;
2932 if (!NILP (tem))
2933 {
2934 val = XCAR (XCDR (tem));
2935 if (CONSP (val))
2936 val = XCAR (val);
2937 }
2938 else if (!NILP (Vcoding_system_for_read))
2939 val = Vcoding_system_for_read;
2940 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2941 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2942 val = Qnil;
2943 pset_decode_coding_system (p, val);
2944
2945 val = Qnil;
2946 if (!NILP (tem))
2947 {
2948 val = XCAR (XCDR (tem));
2949 if (CONSP (val))
2950 val = XCDR (val);
2951 }
2952 else if (!NILP (Vcoding_system_for_write))
2953 val = Vcoding_system_for_write;
2954 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2955 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2956 val = Qnil;
2957 pset_encode_coding_system (p, val);
2958
2959 setup_process_coding_systems (proc);
2960 pset_decoding_buf (p, empty_unibyte_string);
2961 p->decoding_carryover = 0;
2962 pset_encoding_buf (p, empty_unibyte_string);
2963 p->inherit_coding_system_flag
2964 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2965
2966 Fserial_process_configure (nargs, args);
2967
2968 specpdl_ptr = specpdl + specpdl_count;
2969
2970 return proc;
2971 }
2972
2973 static void
2974 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
2975 Lisp_Object service, Lisp_Object name)
2976 {
2977 Lisp_Object tem;
2978 struct Lisp_Process *p = XPROCESS (proc);
2979 Lisp_Object contact = p->childp;
2980 Lisp_Object coding_systems = Qt;
2981 Lisp_Object val;
2982
2983 tem = Fplist_member (contact, QCcoding);
2984 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2985 tem = Qnil; /* No error message (too late!). */
2986
2987 /* Setup coding systems for communicating with the network stream. */
2988 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2989
2990 if (!NILP (tem))
2991 {
2992 val = XCAR (XCDR (tem));
2993 if (CONSP (val))
2994 val = XCAR (val);
2995 }
2996 else if (!NILP (Vcoding_system_for_read))
2997 val = Vcoding_system_for_read;
2998 else if ((!NILP (p->buffer)
2999 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3000 || (NILP (p->buffer)
3001 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3002 /* We dare not decode end-of-line format by setting VAL to
3003 Qraw_text, because the existing Emacs Lisp libraries
3004 assume that they receive bare code including a sequence of
3005 CR LF. */
3006 val = Qnil;
3007 else
3008 {
3009 if (NILP (host) || NILP (service))
3010 coding_systems = Qnil;
3011 else
3012 coding_systems = CALLN (Ffind_operation_coding_system,
3013 Qopen_network_stream, name, p->buffer,
3014 host, service);
3015 if (CONSP (coding_systems))
3016 val = XCAR (coding_systems);
3017 else if (CONSP (Vdefault_process_coding_system))
3018 val = XCAR (Vdefault_process_coding_system);
3019 else
3020 val = Qnil;
3021 }
3022 pset_decode_coding_system (p, val);
3023
3024 if (!NILP (tem))
3025 {
3026 val = XCAR (XCDR (tem));
3027 if (CONSP (val))
3028 val = XCDR (val);
3029 }
3030 else if (!NILP (Vcoding_system_for_write))
3031 val = Vcoding_system_for_write;
3032 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3033 val = Qnil;
3034 else
3035 {
3036 if (EQ (coding_systems, Qt))
3037 {
3038 if (NILP (host) || NILP (service))
3039 coding_systems = Qnil;
3040 else
3041 coding_systems = CALLN (Ffind_operation_coding_system,
3042 Qopen_network_stream, name, p->buffer,
3043 host, service);
3044 }
3045 if (CONSP (coding_systems))
3046 val = XCDR (coding_systems);
3047 else if (CONSP (Vdefault_process_coding_system))
3048 val = XCDR (Vdefault_process_coding_system);
3049 else
3050 val = Qnil;
3051 }
3052 pset_encode_coding_system (p, val);
3053
3054 pset_decoding_buf (p, empty_unibyte_string);
3055 p->decoding_carryover = 0;
3056 pset_encoding_buf (p, empty_unibyte_string);
3057
3058 p->inherit_coding_system_flag
3059 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3060 }
3061
3062 #ifdef HAVE_GNUTLS
3063 static void
3064 finish_after_tls_connection (Lisp_Object proc)
3065 {
3066 struct Lisp_Process *p = XPROCESS (proc);
3067 Lisp_Object contact = p->childp;
3068 Lisp_Object result = Qt;
3069
3070 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3071 result = call3 (Qnsm_verify_connection,
3072 proc,
3073 Fplist_get (contact, QChost),
3074 Fplist_get (contact, QCservice));
3075
3076 if (NILP (result))
3077 {
3078 pset_status (p, list2 (Qfailed,
3079 build_string ("The Network Security Manager stopped the connections")));
3080 deactivate_process (proc);
3081 }
3082 else
3083 {
3084 /* If we cleared the connection wait mask before we did
3085 the TLS setup, then we have to say that the process
3086 is finally "open" here. */
3087 if (! FD_ISSET (p->outfd, &connect_wait_mask))
3088 {
3089 pset_status (p, Qrun);
3090 /* Execute the sentinel here. If we had relied on
3091 status_notify to do it later, it will read input
3092 from the process before calling the sentinel. */
3093 exec_sentinel (proc, build_string ("open\n"));
3094 }
3095 }
3096 }
3097 #endif
3098
3099 static void
3100 connect_network_socket (Lisp_Object proc, Lisp_Object ip_addresses,
3101 Lisp_Object use_external_socket_p)
3102 {
3103 ptrdiff_t count = SPECPDL_INDEX ();
3104 ptrdiff_t count1;
3105 int s = -1, outch, inch;
3106 int xerrno = 0;
3107 Lisp_Object ip_address;
3108 int family;
3109 struct sockaddr *sa = NULL;
3110 int ret;
3111 ptrdiff_t addrlen;
3112 struct Lisp_Process *p = XPROCESS (proc);
3113 Lisp_Object contact = p->childp;
3114 int optbits = 0;
3115 int socket_to_use = -1;
3116
3117 if (!NILP (use_external_socket_p))
3118 {
3119 socket_to_use = external_sock_fd;
3120
3121 /* Ensure we don't consume the external socket twice. */
3122 external_sock_fd = -1;
3123 }
3124
3125 /* Do this in case we never enter the while-loop below. */
3126 count1 = SPECPDL_INDEX ();
3127 s = -1;
3128
3129 while (!NILP (ip_addresses))
3130 {
3131 ip_address = XCAR (ip_addresses);
3132 ip_addresses = XCDR (ip_addresses);
3133
3134 #ifdef WINDOWSNT
3135 retry_connect:
3136 #endif
3137
3138 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3139 if (sa)
3140 free (sa);
3141 sa = xmalloc (addrlen);
3142 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3143
3144 s = socket_to_use;
3145 if (s < 0)
3146 {
3147 int socktype = p->socktype | SOCK_CLOEXEC;
3148 if (p->is_non_blocking_client)
3149 socktype |= SOCK_NONBLOCK;
3150 s = socket (family, socktype, p->ai_protocol);
3151 if (s < 0)
3152 {
3153 xerrno = errno;
3154 continue;
3155 }
3156 }
3157
3158 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3159 {
3160 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3161 if (ret < 0)
3162 {
3163 xerrno = errno;
3164 emacs_close (s);
3165 s = -1;
3166 continue;
3167 }
3168 }
3169
3170 #ifdef DATAGRAM_SOCKETS
3171 if (!p->is_server && p->socktype == SOCK_DGRAM)
3172 break;
3173 #endif /* DATAGRAM_SOCKETS */
3174
3175 /* Make us close S if quit. */
3176 record_unwind_protect_int (close_file_unwind, s);
3177
3178 /* Parse network options in the arg list. We simply ignore anything
3179 which isn't a known option (including other keywords). An error
3180 is signaled if setting a known option fails. */
3181 {
3182 Lisp_Object params = contact, key, val;
3183
3184 while (!NILP (params))
3185 {
3186 key = XCAR (params);
3187 params = XCDR (params);
3188 val = XCAR (params);
3189 params = XCDR (params);
3190 optbits |= set_socket_option (s, key, val);
3191 }
3192 }
3193
3194 if (p->is_server)
3195 {
3196 /* Configure as a server socket. */
3197
3198 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3199 explicit :reuseaddr key to override this. */
3200 #ifdef HAVE_LOCAL_SOCKETS
3201 if (family != AF_LOCAL)
3202 #endif
3203 if (!(optbits & (1 << OPIX_REUSEADDR)))
3204 {
3205 int optval = 1;
3206 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3207 report_file_error ("Cannot set reuse option on server socket", Qnil);
3208 }
3209
3210 /* If passed a socket descriptor, it should be already bound. */
3211 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3212 report_file_error ("Cannot bind server socket", Qnil);
3213
3214 #ifdef HAVE_GETSOCKNAME
3215 if (p->port == 0)
3216 {
3217 struct sockaddr_in sa1;
3218 socklen_t len1 = sizeof (sa1);
3219 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3220 {
3221 Lisp_Object service;
3222 service = make_number (ntohs (sa1.sin_port));
3223 contact = Fplist_put (contact, QCservice, service);
3224 /* Save the port number so that we can stash it in
3225 the process object later. */
3226 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3227 }
3228 }
3229 #endif
3230
3231 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3232 report_file_error ("Cannot listen on server socket", Qnil);
3233
3234 break;
3235 }
3236
3237 immediate_quit = 1;
3238 QUIT;
3239
3240 ret = connect (s, sa, addrlen);
3241 xerrno = errno;
3242
3243 if (ret == 0 || xerrno == EISCONN)
3244 {
3245 /* The unwind-protect will be discarded afterwards.
3246 Likewise for immediate_quit. */
3247 break;
3248 }
3249
3250 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3251 break;
3252
3253 #ifndef WINDOWSNT
3254 if (xerrno == EINTR)
3255 {
3256 /* Unlike most other syscalls connect() cannot be called
3257 again. (That would return EALREADY.) The proper way to
3258 wait for completion is pselect(). */
3259 int sc;
3260 socklen_t len;
3261 fd_set fdset;
3262 retry_select:
3263 FD_ZERO (&fdset);
3264 FD_SET (s, &fdset);
3265 QUIT;
3266 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3267 if (sc == -1)
3268 {
3269 if (errno == EINTR)
3270 goto retry_select;
3271 else
3272 report_file_error ("Failed select", Qnil);
3273 }
3274 eassert (sc > 0);
3275
3276 len = sizeof xerrno;
3277 eassert (FD_ISSET (s, &fdset));
3278 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3279 report_file_error ("Failed getsockopt", Qnil);
3280 if (xerrno)
3281 report_file_errno ("Failed connect", Qnil, xerrno);
3282 break;
3283 }
3284 #endif /* !WINDOWSNT */
3285
3286 immediate_quit = 0;
3287
3288 /* Discard the unwind protect closing S. */
3289 specpdl_ptr = specpdl + count1;
3290 emacs_close (s);
3291 s = -1;
3292
3293 #ifdef WINDOWSNT
3294 if (xerrno == EINTR)
3295 goto retry_connect;
3296 #endif
3297 }
3298
3299 if (s >= 0)
3300 {
3301 #ifdef DATAGRAM_SOCKETS
3302 if (p->socktype == SOCK_DGRAM)
3303 {
3304 if (datagram_address[s].sa)
3305 emacs_abort ();
3306
3307 datagram_address[s].sa = xmalloc (addrlen);
3308 datagram_address[s].len = addrlen;
3309 if (p->is_server)
3310 {
3311 Lisp_Object remote;
3312 memset (datagram_address[s].sa, 0, addrlen);
3313 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3314 {
3315 int rfamily;
3316 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3317 if (rlen != 0 && rfamily == family
3318 && rlen == addrlen)
3319 conv_lisp_to_sockaddr (rfamily, remote,
3320 datagram_address[s].sa, rlen);
3321 }
3322 }
3323 else
3324 memcpy (datagram_address[s].sa, sa, addrlen);
3325 }
3326 #endif
3327
3328 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3329 conv_sockaddr_to_lisp (sa, addrlen));
3330 #ifdef HAVE_GETSOCKNAME
3331 if (!p->is_server)
3332 {
3333 struct sockaddr_in sa1;
3334 socklen_t len1 = sizeof (sa1);
3335 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3336 contact = Fplist_put (contact, QClocal,
3337 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3338 }
3339 #endif
3340 }
3341
3342 immediate_quit = 0;
3343
3344 if (s < 0)
3345 {
3346 /* If non-blocking got this far - and failed - assume non-blocking is
3347 not supported after all. This is probably a wrong assumption, but
3348 the normal blocking calls to open-network-stream handles this error
3349 better. */
3350 if (p->is_non_blocking_client)
3351 return;
3352
3353 report_file_errno ((p->is_server
3354 ? "make server process failed"
3355 : "make client process failed"),
3356 contact, xerrno);
3357 }
3358
3359 inch = s;
3360 outch = s;
3361
3362 chan_process[inch] = proc;
3363
3364 fcntl (inch, F_SETFL, O_NONBLOCK);
3365
3366 p = XPROCESS (proc);
3367 p->open_fd[SUBPROCESS_STDIN] = inch;
3368 p->infd = inch;
3369 p->outfd = outch;
3370
3371 /* Discard the unwind protect for closing S, if any. */
3372 specpdl_ptr = specpdl + count1;
3373
3374 /* Unwind bind_polling_period and request_sigio. */
3375 unbind_to (count, Qnil);
3376
3377 if (p->is_server && p->socktype != SOCK_DGRAM)
3378 pset_status (p, Qlisten);
3379
3380 /* Make the process marker point into the process buffer (if any). */
3381 if (BUFFERP (p->buffer))
3382 set_marker_both (p->mark, p->buffer,
3383 BUF_ZV (XBUFFER (p->buffer)),
3384 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3385
3386 if (p->is_non_blocking_client)
3387 {
3388 /* We may get here if connect did succeed immediately. However,
3389 in that case, we still need to signal this like a non-blocking
3390 connection. */
3391 pset_status (p, Qconnect);
3392 if (!FD_ISSET (inch, &connect_wait_mask))
3393 {
3394 FD_SET (inch, &connect_wait_mask);
3395 FD_SET (inch, &write_mask);
3396 num_pending_connects++;
3397 }
3398 }
3399 else
3400 /* A server may have a client filter setting of Qt, but it must
3401 still listen for incoming connects unless it is stopped. */
3402 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3403 || (EQ (p->status, Qlisten) && NILP (p->command)))
3404 {
3405 FD_SET (inch, &input_wait_mask);
3406 FD_SET (inch, &non_keyboard_wait_mask);
3407 }
3408
3409 if (inch > max_process_desc)
3410 max_process_desc = inch;
3411
3412 /* Set up the masks based on the process filter. */
3413 set_process_filter_masks (p);
3414
3415 setup_process_coding_systems (proc);
3416
3417 #ifdef HAVE_GNUTLS
3418 /* Continue the asynchronous connection. */
3419 if (!NILP (p->gnutls_boot_parameters))
3420 {
3421 Lisp_Object boot, params = p->gnutls_boot_parameters;
3422
3423 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3424 p->gnutls_boot_parameters = Qnil;
3425
3426 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3427 /* Run sentinels, etc. */
3428 finish_after_tls_connection (proc);
3429 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3430 {
3431 deactivate_process (proc);
3432 if (NILP (boot))
3433 pset_status (p, list2 (Qfailed,
3434 build_string ("TLS negotiation failed")));
3435 else
3436 pset_status (p, list2 (Qfailed, boot));
3437 }
3438 }
3439 #endif
3440
3441 }
3442
3443 /* Create a network stream/datagram client/server process. Treated
3444 exactly like a normal process when reading and writing. Primary
3445 differences are in status display and process deletion. A network
3446 connection has no PID; you cannot signal it. All you can do is
3447 stop/continue it and deactivate/close it via delete-process. */
3448
3449 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3450 0, MANY, 0,
3451 doc: /* Create and return a network server or client process.
3452
3453 In Emacs, network connections are represented by process objects, so
3454 input and output work as for subprocesses and `delete-process' closes
3455 a network connection. However, a network process has no process id,
3456 it cannot be signaled, and the status codes are different from normal
3457 processes.
3458
3459 Arguments are specified as keyword/argument pairs. The following
3460 arguments are defined:
3461
3462 :name NAME -- NAME is name for process. It is modified if necessary
3463 to make it unique.
3464
3465 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3466 with the process. Process output goes at end of that buffer, unless
3467 you specify an output stream or filter function to handle the output.
3468 BUFFER may be also nil, meaning that this process is not associated
3469 with any buffer.
3470
3471 :host HOST -- HOST is name of the host to connect to, or its IP
3472 address. The symbol `local' specifies the local host. If specified
3473 for a server process, it must be a valid name or address for the local
3474 host, and only clients connecting to that address will be accepted.
3475
3476 :service SERVICE -- SERVICE is name of the service desired, or an
3477 integer specifying a port number to connect to. If SERVICE is t,
3478 a random port number is selected for the server. A port number can
3479 be specified as an integer string, e.g., "80", as well as an integer.
3480
3481 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3482 stream type connection, `datagram' creates a datagram type connection,
3483 `seqpacket' creates a reliable datagram connection.
3484
3485 :family FAMILY -- FAMILY is the address (and protocol) family for the
3486 service specified by HOST and SERVICE. The default (nil) is to use
3487 whatever address family (IPv4 or IPv6) that is defined for the host
3488 and port number specified by HOST and SERVICE. Other address families
3489 supported are:
3490 local -- for a local (i.e. UNIX) address specified by SERVICE.
3491 ipv4 -- use IPv4 address family only.
3492 ipv6 -- use IPv6 address family only.
3493
3494 :local ADDRESS -- ADDRESS is the local address used for the connection.
3495 This parameter is ignored when opening a client process. When specified
3496 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3497
3498 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3499 connection. This parameter is ignored when opening a stream server
3500 process. For a datagram server process, it specifies the initial
3501 setting of the remote datagram address. When specified for a client
3502 process, the FAMILY, HOST, and SERVICE args are ignored.
3503
3504 The format of ADDRESS depends on the address family:
3505 - An IPv4 address is represented as an vector of integers [A B C D P]
3506 corresponding to numeric IP address A.B.C.D and port number P.
3507 - A local address is represented as a string with the address in the
3508 local address space.
3509 - An "unsupported family" address is represented by a cons (F . AV)
3510 where F is the family number and AV is a vector containing the socket
3511 address data with one element per address data byte. Do not rely on
3512 this format in portable code, as it may depend on implementation
3513 defined constants, data sizes, and data structure alignment.
3514
3515 :coding CODING -- If CODING is a symbol, it specifies the coding
3516 system used for both reading and writing for this process. If CODING
3517 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3518 ENCODING is used for writing.
3519
3520 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3521 process, return without waiting for the connection to complete;
3522 instead, the sentinel function will be called with second arg matching
3523 "open" (if successful) or "failed" when the connect completes.
3524 Default is to use a blocking connect (i.e. wait) for stream type
3525 connections.
3526
3527 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3528 running when Emacs is exited.
3529
3530 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3531 In the stopped state, a server process does not accept new
3532 connections, and a client process does not handle incoming traffic.
3533 The stopped state is cleared by `continue-process' and set by
3534 `stop-process'.
3535
3536 :filter FILTER -- Install FILTER as the process filter.
3537
3538 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3539 process filter are multibyte, otherwise they are unibyte.
3540 If this keyword is not specified, the strings are multibyte if
3541 the default value of `enable-multibyte-characters' is non-nil.
3542
3543 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3544
3545 :log LOG -- Install LOG as the server process log function. This
3546 function is called when the server accepts a network connection from a
3547 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3548 is the server process, CLIENT is the new process for the connection,
3549 and MESSAGE is a string.
3550
3551 :plist PLIST -- Install PLIST as the new process's initial plist.
3552
3553 :tls-parameters LIST -- is a list that should be supplied if you're
3554 opening a TLS connection. The first element is the TLS type (either
3555 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3556 be a keyword list accepted by gnutls-boot (as returned by
3557 `gnutls-boot-parameters').
3558
3559 :server QLEN -- if QLEN is non-nil, create a server process for the
3560 specified FAMILY, SERVICE, and connection type (stream or datagram).
3561 If QLEN is an integer, it is used as the max. length of the server's
3562 pending connection queue (also known as the backlog); the default
3563 queue length is 5. Default is to create a client process.
3564
3565 The following network options can be specified for this connection:
3566
3567 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3568 :dontroute BOOL -- Only send to directly connected hosts.
3569 :keepalive BOOL -- Send keep-alive messages on network stream.
3570 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3571 :oobinline BOOL -- Place out-of-band data in receive data stream.
3572 :priority INT -- Set protocol defined priority for sent packets.
3573 :reuseaddr BOOL -- Allow reusing a recently used local address
3574 (this is allowed by default for a server process).
3575 :bindtodevice NAME -- bind to interface NAME. Using this may require
3576 special privileges on some systems.
3577 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3578 been passed to Emacs. If Emacs wasn't
3579 passed a socket, this option is silently
3580 ignored.
3581
3582
3583 Consult the relevant system programmer's manual pages for more
3584 information on using these options.
3585
3586
3587 A server process will listen for and accept connections from clients.
3588 When a client connection is accepted, a new network process is created
3589 for the connection with the following parameters:
3590
3591 - The client's process name is constructed by concatenating the server
3592 process's NAME and a client identification string.
3593 - If the FILTER argument is non-nil, the client process will not get a
3594 separate process buffer; otherwise, the client's process buffer is a newly
3595 created buffer named after the server process's BUFFER name or process
3596 NAME concatenated with the client identification string.
3597 - The connection type and the process filter and sentinel parameters are
3598 inherited from the server process's TYPE, FILTER and SENTINEL.
3599 - The client process's contact info is set according to the client's
3600 addressing information (typically an IP address and a port number).
3601 - The client process's plist is initialized from the server's plist.
3602
3603 Notice that the FILTER and SENTINEL args are never used directly by
3604 the server process. Also, the BUFFER argument is not used directly by
3605 the server process, but via the optional :log function, accepted (and
3606 failed) connections may be logged in the server process's buffer.
3607
3608 The original argument list, modified with the actual connection
3609 information, is available via the `process-contact' function.
3610
3611 usage: (make-network-process &rest ARGS) */)
3612 (ptrdiff_t nargs, Lisp_Object *args)
3613 {
3614 Lisp_Object proc;
3615 Lisp_Object contact;
3616 struct Lisp_Process *p;
3617 const char *portstring;
3618 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3619 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3620 #ifdef HAVE_LOCAL_SOCKETS
3621 struct sockaddr_un address_un;
3622 #endif
3623 EMACS_INT port = 0;
3624 Lisp_Object tem;
3625 Lisp_Object name, buffer, host, service, address;
3626 Lisp_Object filter, sentinel, use_external_socket_p;
3627 Lisp_Object ip_addresses = Qnil;
3628 int socktype;
3629 int family = -1;
3630 int ai_protocol = 0;
3631 #ifdef HAVE_GETADDRINFO_A
3632 struct gaicb *dns_request = NULL;
3633 #endif
3634 ptrdiff_t count = SPECPDL_INDEX ();
3635
3636 if (nargs == 0)
3637 return Qnil;
3638
3639 /* Save arguments for process-contact and clone-process. */
3640 contact = Flist (nargs, args);
3641
3642 #ifdef WINDOWSNT
3643 /* Ensure socket support is loaded if available. */
3644 init_winsock (TRUE);
3645 #endif
3646
3647 /* :type TYPE (nil: stream, datagram */
3648 tem = Fplist_get (contact, QCtype);
3649 if (NILP (tem))
3650 socktype = SOCK_STREAM;
3651 #ifdef DATAGRAM_SOCKETS
3652 else if (EQ (tem, Qdatagram))
3653 socktype = SOCK_DGRAM;
3654 #endif
3655 #ifdef HAVE_SEQPACKET
3656 else if (EQ (tem, Qseqpacket))
3657 socktype = SOCK_SEQPACKET;
3658 #endif
3659 else
3660 error ("Unsupported connection type");
3661
3662 name = Fplist_get (contact, QCname);
3663 buffer = Fplist_get (contact, QCbuffer);
3664 filter = Fplist_get (contact, QCfilter);
3665 sentinel = Fplist_get (contact, QCsentinel);
3666 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3667
3668 CHECK_STRING (name);
3669
3670 /* :local ADDRESS or :remote ADDRESS */
3671 tem = Fplist_get (contact, QCserver);
3672 if (NILP (tem))
3673 address = Fplist_get (contact, QCremote);
3674 else
3675 address = Fplist_get (contact, QClocal);
3676 if (!NILP (address))
3677 {
3678 host = service = Qnil;
3679
3680 if (!get_lisp_to_sockaddr_size (address, &family))
3681 error ("Malformed :address");
3682
3683 ip_addresses = list1 (address);
3684 goto open_socket;
3685 }
3686
3687 /* :family FAMILY -- nil (for Inet), local, or integer. */
3688 tem = Fplist_get (contact, QCfamily);
3689 if (NILP (tem))
3690 {
3691 #ifdef AF_INET6
3692 family = AF_UNSPEC;
3693 #else
3694 family = AF_INET;
3695 #endif
3696 }
3697 #ifdef HAVE_LOCAL_SOCKETS
3698 else if (EQ (tem, Qlocal))
3699 family = AF_LOCAL;
3700 #endif
3701 #ifdef AF_INET6
3702 else if (EQ (tem, Qipv6))
3703 family = AF_INET6;
3704 #endif
3705 else if (EQ (tem, Qipv4))
3706 family = AF_INET;
3707 else if (TYPE_RANGED_INTEGERP (int, tem))
3708 family = XINT (tem);
3709 else
3710 error ("Unknown address family");
3711
3712 /* :service SERVICE -- string, integer (port number), or t (random port). */
3713 service = Fplist_get (contact, QCservice);
3714
3715 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3716 host = Fplist_get (contact, QChost);
3717 if (NILP (host))
3718 {
3719 /* The "connection" function gets it bind info from the address we're
3720 given, so use this dummy address if nothing is specified. */
3721 #ifdef HAVE_LOCAL_SOCKETS
3722 if (family != AF_LOCAL)
3723 #endif
3724 host = build_string ("127.0.0.1");
3725 }
3726 else
3727 {
3728 if (EQ (host, Qlocal))
3729 /* Depending on setup, "localhost" may map to different IPv4 and/or
3730 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3731 host = build_string ("127.0.0.1");
3732 CHECK_STRING (host);
3733 }
3734
3735 #ifdef HAVE_LOCAL_SOCKETS
3736 if (family == AF_LOCAL)
3737 {
3738 if (!NILP (host))
3739 {
3740 message (":family local ignores the :host property");
3741 contact = Fplist_put (contact, QChost, Qnil);
3742 host = Qnil;
3743 }
3744 CHECK_STRING (service);
3745 if (sizeof address_un.sun_path <= SBYTES (service))
3746 error ("Service name too long");
3747 ip_addresses = list1 (service);
3748 goto open_socket;
3749 }
3750 #endif
3751
3752 /* Slow down polling to every ten seconds.
3753 Some kernels have a bug which causes retrying connect to fail
3754 after a connect. Polling can interfere with gethostbyname too. */
3755 #ifdef POLL_FOR_INPUT
3756 if (socktype != SOCK_DGRAM)
3757 {
3758 record_unwind_protect_void (run_all_atimers);
3759 bind_polling_period (10);
3760 }
3761 #endif
3762
3763 if (!NILP (host))
3764 {
3765 /* SERVICE can either be a string or int.
3766 Convert to a C string for later use by getaddrinfo. */
3767 if (EQ (service, Qt))
3768 {
3769 portstring = "0";
3770 portstringlen = 1;
3771 }
3772 else if (INTEGERP (service))
3773 {
3774 portstring = portbuf;
3775 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3776 }
3777 else
3778 {
3779 CHECK_STRING (service);
3780 portstring = SSDATA (service);
3781 portstringlen = SBYTES (service);
3782 }
3783 }
3784
3785 #ifdef HAVE_GETADDRINFO_A
3786 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3787 {
3788 ptrdiff_t hostlen = SBYTES (host);
3789 struct req
3790 {
3791 struct gaicb gaicb;
3792 struct addrinfo hints;
3793 char str[FLEXIBLE_ARRAY_MEMBER];
3794 } *req = xmalloc (offsetof (struct req, str)
3795 + hostlen + 1 + portstringlen + 1);
3796 dns_request = &req->gaicb;
3797 dns_request->ar_name = req->str;
3798 dns_request->ar_service = req->str + hostlen + 1;
3799 dns_request->ar_request = &req->hints;
3800 dns_request->ar_result = NULL;
3801 memset (&req->hints, 0, sizeof req->hints);
3802 req->hints.ai_family = family;
3803 req->hints.ai_socktype = socktype;
3804 strcpy (req->str, SSDATA (host));
3805 strcpy (req->str + hostlen + 1, portstring);
3806
3807 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3808 if (ret)
3809 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3810
3811 goto open_socket;
3812 }
3813 #endif /* HAVE_GETADDRINFO_A */
3814
3815 /* If we have a host, use getaddrinfo to resolve both host and service.
3816 Otherwise, use getservbyname to lookup the service. */
3817
3818 if (!NILP (host))
3819 {
3820 struct addrinfo *res, *lres;
3821 int ret;
3822
3823 immediate_quit = 1;
3824 QUIT;
3825
3826 struct addrinfo hints;
3827 memset (&hints, 0, sizeof hints);
3828 hints.ai_family = family;
3829 hints.ai_socktype = socktype;
3830
3831 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3832 if (ret)
3833 #ifdef HAVE_GAI_STRERROR
3834 {
3835 synchronize_system_messages_locale ();
3836 char const *str = gai_strerror (ret);
3837 if (! NILP (Vlocale_coding_system))
3838 str = SSDATA (code_convert_string_norecord
3839 (build_string (str), Vlocale_coding_system, 0));
3840 error ("%s/%s %s", SSDATA (host), portstring, str);
3841 }
3842 #else
3843 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3844 #endif
3845 immediate_quit = 0;
3846
3847 for (lres = res; lres; lres = lres->ai_next)
3848 {
3849 ip_addresses = Fcons (conv_sockaddr_to_lisp
3850 (lres->ai_addr, lres->ai_addrlen),
3851 ip_addresses);
3852 ai_protocol = lres->ai_protocol;
3853 }
3854
3855 ip_addresses = Fnreverse (ip_addresses);
3856
3857 freeaddrinfo (res);
3858
3859 goto open_socket;
3860 }
3861
3862 /* No hostname has been specified (e.g., a local server process). */
3863
3864 if (EQ (service, Qt))
3865 port = 0;
3866 else if (INTEGERP (service))
3867 port = XINT (service);
3868 else
3869 {
3870 CHECK_STRING (service);
3871
3872 port = -1;
3873 if (SBYTES (service) != 0)
3874 {
3875 /* Allow the service to be a string containing the port number,
3876 because that's allowed if you have getaddrbyname. */
3877 char *service_end;
3878 long int lport = strtol (SSDATA (service), &service_end, 10);
3879 if (service_end == SSDATA (service) + SBYTES (service))
3880 port = lport;
3881 else
3882 {
3883 struct servent *svc_info
3884 = getservbyname (SSDATA (service),
3885 socktype == SOCK_DGRAM ? "udp" : "tcp");
3886 if (svc_info)
3887 port = ntohs (svc_info->s_port);
3888 }
3889 }
3890 }
3891
3892 if (! (0 <= port && port < 1 << 16))
3893 {
3894 AUTO_STRING (unknown_service, "Unknown service: %s");
3895 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
3896 }
3897
3898 open_socket:
3899
3900 if (!NILP (buffer))
3901 buffer = Fget_buffer_create (buffer);
3902 proc = make_process (name);
3903 p = XPROCESS (proc);
3904 pset_childp (p, contact);
3905 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3906 pset_type (p, Qnetwork);
3907
3908 pset_buffer (p, buffer);
3909 pset_sentinel (p, sentinel);
3910 pset_filter (p, filter);
3911 pset_log (p, Fplist_get (contact, QClog));
3912 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3913 p->kill_without_query = 1;
3914 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3915 pset_command (p, Qt);
3916 p->pid = 0;
3917 p->backlog = 5;
3918 p->is_non_blocking_client = false;
3919 p->is_server = false;
3920 p->port = port;
3921 p->socktype = socktype;
3922 p->ai_protocol = ai_protocol;
3923 #ifdef HAVE_GETADDRINFO_A
3924 p->dns_request = NULL;
3925 #endif
3926 #ifdef HAVE_GNUTLS
3927 tem = Fplist_get (contact, QCtls_parameters);
3928 CHECK_LIST (tem);
3929 p->gnutls_boot_parameters = tem;
3930 #endif
3931
3932 set_network_socket_coding_system (proc, host, service, name);
3933
3934 unbind_to (count, Qnil);
3935
3936 /* :server BOOL */
3937 tem = Fplist_get (contact, QCserver);
3938 if (!NILP (tem))
3939 {
3940 /* Don't support network sockets when non-blocking mode is
3941 not available, since a blocked Emacs is not useful. */
3942 p->is_server = true;
3943 if (TYPE_RANGED_INTEGERP (int, tem))
3944 p->backlog = XINT (tem);
3945 }
3946
3947 /* :nowait BOOL */
3948 if (!p->is_server && socktype != SOCK_DGRAM
3949 && !NILP (Fplist_get (contact, QCnowait)))
3950 p->is_non_blocking_client = true;
3951
3952 #ifdef HAVE_GETADDRINFO_A
3953 /* With async address resolution, the list of addresses is empty, so
3954 postpone connecting to the server. */
3955 if (!p->is_server && NILP (ip_addresses))
3956 {
3957 p->dns_request = dns_request;
3958 p->status = Qconnect;
3959 return proc;
3960 }
3961 #endif
3962
3963 connect_network_socket (proc, ip_addresses, use_external_socket_p);
3964 return proc;
3965 }
3966
3967 \f
3968 #ifdef HAVE_NET_IF_H
3969
3970 #ifdef SIOCGIFCONF
3971 static Lisp_Object
3972 network_interface_list (void)
3973 {
3974 struct ifconf ifconf;
3975 struct ifreq *ifreq;
3976 void *buf = NULL;
3977 ptrdiff_t buf_size = 512;
3978 int s;
3979 Lisp_Object res;
3980 ptrdiff_t count;
3981
3982 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3983 if (s < 0)
3984 return Qnil;
3985 count = SPECPDL_INDEX ();
3986 record_unwind_protect_int (close_file_unwind, s);
3987
3988 do
3989 {
3990 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3991 ifconf.ifc_buf = buf;
3992 ifconf.ifc_len = buf_size;
3993 if (ioctl (s, SIOCGIFCONF, &ifconf))
3994 {
3995 emacs_close (s);
3996 xfree (buf);
3997 return Qnil;
3998 }
3999 }
4000 while (ifconf.ifc_len == buf_size);
4001
4002 res = unbind_to (count, Qnil);
4003 ifreq = ifconf.ifc_req;
4004 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4005 {
4006 struct ifreq *ifq = ifreq;
4007 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4008 #define SIZEOF_IFREQ(sif) \
4009 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4010 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4011
4012 int len = SIZEOF_IFREQ (ifq);
4013 #else
4014 int len = sizeof (*ifreq);
4015 #endif
4016 char namebuf[sizeof (ifq->ifr_name) + 1];
4017 ifreq = (struct ifreq *) ((char *) ifreq + len);
4018
4019 if (ifq->ifr_addr.sa_family != AF_INET)
4020 continue;
4021
4022 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4023 namebuf[sizeof (ifq->ifr_name)] = 0;
4024 res = Fcons (Fcons (build_string (namebuf),
4025 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4026 sizeof (struct sockaddr))),
4027 res);
4028 }
4029
4030 xfree (buf);
4031 return res;
4032 }
4033 #endif /* SIOCGIFCONF */
4034
4035 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4036
4037 struct ifflag_def {
4038 int flag_bit;
4039 const char *flag_sym;
4040 };
4041
4042 static const struct ifflag_def ifflag_table[] = {
4043 #ifdef IFF_UP
4044 { IFF_UP, "up" },
4045 #endif
4046 #ifdef IFF_BROADCAST
4047 { IFF_BROADCAST, "broadcast" },
4048 #endif
4049 #ifdef IFF_DEBUG
4050 { IFF_DEBUG, "debug" },
4051 #endif
4052 #ifdef IFF_LOOPBACK
4053 { IFF_LOOPBACK, "loopback" },
4054 #endif
4055 #ifdef IFF_POINTOPOINT
4056 { IFF_POINTOPOINT, "pointopoint" },
4057 #endif
4058 #ifdef IFF_RUNNING
4059 { IFF_RUNNING, "running" },
4060 #endif
4061 #ifdef IFF_NOARP
4062 { IFF_NOARP, "noarp" },
4063 #endif
4064 #ifdef IFF_PROMISC
4065 { IFF_PROMISC, "promisc" },
4066 #endif
4067 #ifdef IFF_NOTRAILERS
4068 #ifdef NS_IMPL_COCOA
4069 /* Really means smart, notrailers is obsolete. */
4070 { IFF_NOTRAILERS, "smart" },
4071 #else
4072 { IFF_NOTRAILERS, "notrailers" },
4073 #endif
4074 #endif
4075 #ifdef IFF_ALLMULTI
4076 { IFF_ALLMULTI, "allmulti" },
4077 #endif
4078 #ifdef IFF_MASTER
4079 { IFF_MASTER, "master" },
4080 #endif
4081 #ifdef IFF_SLAVE
4082 { IFF_SLAVE, "slave" },
4083 #endif
4084 #ifdef IFF_MULTICAST
4085 { IFF_MULTICAST, "multicast" },
4086 #endif
4087 #ifdef IFF_PORTSEL
4088 { IFF_PORTSEL, "portsel" },
4089 #endif
4090 #ifdef IFF_AUTOMEDIA
4091 { IFF_AUTOMEDIA, "automedia" },
4092 #endif
4093 #ifdef IFF_DYNAMIC
4094 { IFF_DYNAMIC, "dynamic" },
4095 #endif
4096 #ifdef IFF_OACTIVE
4097 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4098 #endif
4099 #ifdef IFF_SIMPLEX
4100 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4101 #endif
4102 #ifdef IFF_LINK0
4103 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4104 #endif
4105 #ifdef IFF_LINK1
4106 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4107 #endif
4108 #ifdef IFF_LINK2
4109 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4110 #endif
4111 { 0, 0 }
4112 };
4113
4114 static Lisp_Object
4115 network_interface_info (Lisp_Object ifname)
4116 {
4117 struct ifreq rq;
4118 Lisp_Object res = Qnil;
4119 Lisp_Object elt;
4120 int s;
4121 bool any = 0;
4122 ptrdiff_t count;
4123 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4124 && defined HAVE_GETIFADDRS && defined LLADDR)
4125 struct ifaddrs *ifap;
4126 #endif
4127
4128 CHECK_STRING (ifname);
4129
4130 if (sizeof rq.ifr_name <= SBYTES (ifname))
4131 error ("interface name too long");
4132 lispstpcpy (rq.ifr_name, ifname);
4133
4134 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4135 if (s < 0)
4136 return Qnil;
4137 count = SPECPDL_INDEX ();
4138 record_unwind_protect_int (close_file_unwind, s);
4139
4140 elt = Qnil;
4141 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4142 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4143 {
4144 int flags = rq.ifr_flags;
4145 const struct ifflag_def *fp;
4146 int fnum;
4147
4148 /* If flags is smaller than int (i.e. short) it may have the high bit set
4149 due to IFF_MULTICAST. In that case, sign extending it into
4150 an int is wrong. */
4151 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4152 flags = (unsigned short) rq.ifr_flags;
4153
4154 any = 1;
4155 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4156 {
4157 if (flags & fp->flag_bit)
4158 {
4159 elt = Fcons (intern (fp->flag_sym), elt);
4160 flags -= fp->flag_bit;
4161 }
4162 }
4163 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4164 {
4165 if (flags & 1)
4166 {
4167 elt = Fcons (make_number (fnum), elt);
4168 }
4169 }
4170 }
4171 #endif
4172 res = Fcons (elt, res);
4173
4174 elt = Qnil;
4175 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4176 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4177 {
4178 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4179 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4180 int n;
4181
4182 any = 1;
4183 for (n = 0; n < 6; n++)
4184 p->contents[n] = make_number (((unsigned char *)
4185 &rq.ifr_hwaddr.sa_data[0])
4186 [n]);
4187 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4188 }
4189 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4190 if (getifaddrs (&ifap) != -1)
4191 {
4192 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4193 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4194 struct ifaddrs *it;
4195
4196 for (it = ifap; it != NULL; it = it->ifa_next)
4197 {
4198 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4199 unsigned char linkaddr[6];
4200 int n;
4201
4202 if (it->ifa_addr->sa_family != AF_LINK
4203 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4204 || sdl->sdl_alen != 6)
4205 continue;
4206
4207 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4208 for (n = 0; n < 6; n++)
4209 p->contents[n] = make_number (linkaddr[n]);
4210
4211 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4212 break;
4213 }
4214 }
4215 #ifdef HAVE_FREEIFADDRS
4216 freeifaddrs (ifap);
4217 #endif
4218
4219 #endif /* HAVE_GETIFADDRS && LLADDR */
4220
4221 res = Fcons (elt, res);
4222
4223 elt = Qnil;
4224 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4225 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4226 {
4227 any = 1;
4228 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4229 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4230 #else
4231 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4232 #endif
4233 }
4234 #endif
4235 res = Fcons (elt, res);
4236
4237 elt = Qnil;
4238 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4239 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4240 {
4241 any = 1;
4242 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4243 }
4244 #endif
4245 res = Fcons (elt, res);
4246
4247 elt = Qnil;
4248 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4249 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4250 {
4251 any = 1;
4252 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4253 }
4254 #endif
4255 res = Fcons (elt, res);
4256
4257 return unbind_to (count, any ? res : Qnil);
4258 }
4259 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4260 #endif /* defined (HAVE_NET_IF_H) */
4261
4262 DEFUN ("network-interface-list", Fnetwork_interface_list,
4263 Snetwork_interface_list, 0, 0, 0,
4264 doc: /* Return an alist of all network interfaces and their network address.
4265 Each element is a cons, the car of which is a string containing the
4266 interface name, and the cdr is the network address in internal
4267 format; see the description of ADDRESS in `make-network-process'.
4268
4269 If the information is not available, return nil. */)
4270 (void)
4271 {
4272 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4273 return network_interface_list ();
4274 #else
4275 return Qnil;
4276 #endif
4277 }
4278
4279 DEFUN ("network-interface-info", Fnetwork_interface_info,
4280 Snetwork_interface_info, 1, 1, 0,
4281 doc: /* Return information about network interface named IFNAME.
4282 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4283 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4284 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4285 FLAGS is the current flags of the interface.
4286
4287 Data that is unavailable is returned as nil. */)
4288 (Lisp_Object ifname)
4289 {
4290 #if ((defined HAVE_NET_IF_H \
4291 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4292 || defined SIOCGIFFLAGS)) \
4293 || defined WINDOWSNT)
4294 return network_interface_info (ifname);
4295 #else
4296 return Qnil;
4297 #endif
4298 }
4299
4300 /* Turn off input and output for process PROC. */
4301
4302 static void
4303 deactivate_process (Lisp_Object proc)
4304 {
4305 int inchannel;
4306 struct Lisp_Process *p = XPROCESS (proc);
4307 int i;
4308
4309 #ifdef HAVE_GNUTLS
4310 /* Delete GnuTLS structures in PROC, if any. */
4311 emacs_gnutls_deinit (proc);
4312 #endif /* HAVE_GNUTLS */
4313
4314 if (p->read_output_delay > 0)
4315 {
4316 if (--process_output_delay_count < 0)
4317 process_output_delay_count = 0;
4318 p->read_output_delay = 0;
4319 p->read_output_skip = 0;
4320 }
4321
4322 /* Beware SIGCHLD hereabouts. */
4323
4324 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4325 close_process_fd (&p->open_fd[i]);
4326
4327 inchannel = p->infd;
4328 if (inchannel >= 0)
4329 {
4330 p->infd = -1;
4331 p->outfd = -1;
4332 #ifdef DATAGRAM_SOCKETS
4333 if (DATAGRAM_CHAN_P (inchannel))
4334 {
4335 xfree (datagram_address[inchannel].sa);
4336 datagram_address[inchannel].sa = 0;
4337 datagram_address[inchannel].len = 0;
4338 }
4339 #endif
4340 chan_process[inchannel] = Qnil;
4341 FD_CLR (inchannel, &input_wait_mask);
4342 FD_CLR (inchannel, &non_keyboard_wait_mask);
4343 if (FD_ISSET (inchannel, &connect_wait_mask))
4344 {
4345 FD_CLR (inchannel, &connect_wait_mask);
4346 FD_CLR (inchannel, &write_mask);
4347 if (--num_pending_connects < 0)
4348 emacs_abort ();
4349 }
4350 if (inchannel == max_process_desc)
4351 {
4352 /* We just closed the highest-numbered process input descriptor,
4353 so recompute the highest-numbered one now. */
4354 int i = inchannel;
4355 do
4356 i--;
4357 while (0 <= i && NILP (chan_process[i]));
4358
4359 max_process_desc = i;
4360 }
4361 }
4362 }
4363
4364 \f
4365 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4366 0, 4, 0,
4367 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4368 It is given to their filter functions.
4369 Optional argument PROCESS means do not return until output has been
4370 received from PROCESS.
4371
4372 Optional second argument SECONDS and third argument MILLISEC
4373 specify a timeout; return after that much time even if there is
4374 no subprocess output. If SECONDS is a floating point number,
4375 it specifies a fractional number of seconds to wait.
4376 The MILLISEC argument is obsolete and should be avoided.
4377
4378 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4379 from PROCESS only, suspending reading output from other processes.
4380 If JUST-THIS-ONE is an integer, don't run any timers either.
4381 Return non-nil if we received any output from PROCESS (or, if PROCESS
4382 is nil, from any process) before the timeout expired. */)
4383 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4384 {
4385 intmax_t secs;
4386 int nsecs;
4387
4388 if (! NILP (process))
4389 CHECK_PROCESS (process);
4390 else
4391 just_this_one = Qnil;
4392
4393 if (!NILP (millisec))
4394 { /* Obsolete calling convention using integers rather than floats. */
4395 CHECK_NUMBER (millisec);
4396 if (NILP (seconds))
4397 seconds = make_float (XINT (millisec) / 1000.0);
4398 else
4399 {
4400 CHECK_NUMBER (seconds);
4401 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4402 }
4403 }
4404
4405 secs = 0;
4406 nsecs = -1;
4407
4408 if (!NILP (seconds))
4409 {
4410 if (INTEGERP (seconds))
4411 {
4412 if (XINT (seconds) > 0)
4413 {
4414 secs = XINT (seconds);
4415 nsecs = 0;
4416 }
4417 }
4418 else if (FLOATP (seconds))
4419 {
4420 if (XFLOAT_DATA (seconds) > 0)
4421 {
4422 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4423 secs = min (t.tv_sec, WAIT_READING_MAX);
4424 nsecs = t.tv_nsec;
4425 }
4426 }
4427 else
4428 wrong_type_argument (Qnumberp, seconds);
4429 }
4430 else if (! NILP (process))
4431 nsecs = 0;
4432
4433 return
4434 ((wait_reading_process_output (secs, nsecs, 0, 0,
4435 Qnil,
4436 !NILP (process) ? XPROCESS (process) : NULL,
4437 (NILP (just_this_one) ? 0
4438 : !INTEGERP (just_this_one) ? 1 : -1))
4439 <= 0)
4440 ? Qnil : Qt);
4441 }
4442
4443 /* Accept a connection for server process SERVER on CHANNEL. */
4444
4445 static EMACS_INT connect_counter = 0;
4446
4447 static void
4448 server_accept_connection (Lisp_Object server, int channel)
4449 {
4450 Lisp_Object proc, caller, name, buffer;
4451 Lisp_Object contact, host, service;
4452 struct Lisp_Process *ps = XPROCESS (server);
4453 struct Lisp_Process *p;
4454 int s;
4455 union u_sockaddr {
4456 struct sockaddr sa;
4457 struct sockaddr_in in;
4458 #ifdef AF_INET6
4459 struct sockaddr_in6 in6;
4460 #endif
4461 #ifdef HAVE_LOCAL_SOCKETS
4462 struct sockaddr_un un;
4463 #endif
4464 } saddr;
4465 socklen_t len = sizeof saddr;
4466 ptrdiff_t count;
4467
4468 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4469
4470 if (s < 0)
4471 {
4472 int code = errno;
4473 if (!would_block (code) && !NILP (ps->log))
4474 call3 (ps->log, server, Qnil,
4475 concat3 (build_string ("accept failed with code"),
4476 Fnumber_to_string (make_number (code)),
4477 build_string ("\n")));
4478 return;
4479 }
4480
4481 count = SPECPDL_INDEX ();
4482 record_unwind_protect_int (close_file_unwind, s);
4483
4484 connect_counter++;
4485
4486 /* Setup a new process to handle the connection. */
4487
4488 /* Generate a unique identification of the caller, and build contact
4489 information for this process. */
4490 host = Qt;
4491 service = Qnil;
4492 switch (saddr.sa.sa_family)
4493 {
4494 case AF_INET:
4495 {
4496 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4497
4498 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4499 host = CALLN (Fformat, ipv4_format,
4500 make_number (ip[0]), make_number (ip[1]),
4501 make_number (ip[2]), make_number (ip[3]));
4502 service = make_number (ntohs (saddr.in.sin_port));
4503 AUTO_STRING (caller_format, " <%s:%d>");
4504 caller = CALLN (Fformat, caller_format, host, service);
4505 }
4506 break;
4507
4508 #ifdef AF_INET6
4509 case AF_INET6:
4510 {
4511 Lisp_Object args[9];
4512 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4513 int i;
4514
4515 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4516 args[0] = ipv6_format;
4517 for (i = 0; i < 8; i++)
4518 args[i + 1] = make_number (ntohs (ip6[i]));
4519 host = CALLMANY (Fformat, args);
4520 service = make_number (ntohs (saddr.in.sin_port));
4521 AUTO_STRING (caller_format, " <[%s]:%d>");
4522 caller = CALLN (Fformat, caller_format, host, service);
4523 }
4524 break;
4525 #endif
4526
4527 #ifdef HAVE_LOCAL_SOCKETS
4528 case AF_LOCAL:
4529 #endif
4530 default:
4531 caller = Fnumber_to_string (make_number (connect_counter));
4532 AUTO_STRING (space_less_than, " <");
4533 AUTO_STRING (greater_than, ">");
4534 caller = concat3 (space_less_than, caller, greater_than);
4535 break;
4536 }
4537
4538 /* Create a new buffer name for this process if it doesn't have a
4539 filter. The new buffer name is based on the buffer name or
4540 process name of the server process concatenated with the caller
4541 identification. */
4542
4543 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4544 || EQ (ps->filter, Qt)))
4545 buffer = Qnil;
4546 else
4547 {
4548 buffer = ps->buffer;
4549 if (!NILP (buffer))
4550 buffer = Fbuffer_name (buffer);
4551 else
4552 buffer = ps->name;
4553 if (!NILP (buffer))
4554 {
4555 buffer = concat2 (buffer, caller);
4556 buffer = Fget_buffer_create (buffer);
4557 }
4558 }
4559
4560 /* Generate a unique name for the new server process. Combine the
4561 server process name with the caller identification. */
4562
4563 name = concat2 (ps->name, caller);
4564 proc = make_process (name);
4565
4566 chan_process[s] = proc;
4567
4568 fcntl (s, F_SETFL, O_NONBLOCK);
4569
4570 p = XPROCESS (proc);
4571
4572 /* Build new contact information for this setup. */
4573 contact = Fcopy_sequence (ps->childp);
4574 contact = Fplist_put (contact, QCserver, Qnil);
4575 contact = Fplist_put (contact, QChost, host);
4576 if (!NILP (service))
4577 contact = Fplist_put (contact, QCservice, service);
4578 contact = Fplist_put (contact, QCremote,
4579 conv_sockaddr_to_lisp (&saddr.sa, len));
4580 #ifdef HAVE_GETSOCKNAME
4581 len = sizeof saddr;
4582 if (getsockname (s, &saddr.sa, &len) == 0)
4583 contact = Fplist_put (contact, QClocal,
4584 conv_sockaddr_to_lisp (&saddr.sa, len));
4585 #endif
4586
4587 pset_childp (p, contact);
4588 pset_plist (p, Fcopy_sequence (ps->plist));
4589 pset_type (p, Qnetwork);
4590
4591 pset_buffer (p, buffer);
4592 pset_sentinel (p, ps->sentinel);
4593 pset_filter (p, ps->filter);
4594 pset_command (p, Qnil);
4595 p->pid = 0;
4596
4597 /* Discard the unwind protect for closing S. */
4598 specpdl_ptr = specpdl + count;
4599
4600 p->open_fd[SUBPROCESS_STDIN] = s;
4601 p->infd = s;
4602 p->outfd = s;
4603 pset_status (p, Qrun);
4604
4605 /* Client processes for accepted connections are not stopped initially. */
4606 if (!EQ (p->filter, Qt))
4607 {
4608 FD_SET (s, &input_wait_mask);
4609 FD_SET (s, &non_keyboard_wait_mask);
4610 }
4611
4612 if (s > max_process_desc)
4613 max_process_desc = s;
4614
4615 /* Setup coding system for new process based on server process.
4616 This seems to be the proper thing to do, as the coding system
4617 of the new process should reflect the settings at the time the
4618 server socket was opened; not the current settings. */
4619
4620 pset_decode_coding_system (p, ps->decode_coding_system);
4621 pset_encode_coding_system (p, ps->encode_coding_system);
4622 setup_process_coding_systems (proc);
4623
4624 pset_decoding_buf (p, empty_unibyte_string);
4625 p->decoding_carryover = 0;
4626 pset_encoding_buf (p, empty_unibyte_string);
4627
4628 p->inherit_coding_system_flag
4629 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4630
4631 AUTO_STRING (dash, "-");
4632 AUTO_STRING (nl, "\n");
4633 Lisp_Object host_string = STRINGP (host) ? host : dash;
4634
4635 if (!NILP (ps->log))
4636 {
4637 AUTO_STRING (accept_from, "accept from ");
4638 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4639 }
4640
4641 AUTO_STRING (open_from, "open from ");
4642 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4643 }
4644
4645 #ifdef HAVE_GETADDRINFO_A
4646 static Lisp_Object
4647 check_for_dns (Lisp_Object proc)
4648 {
4649 struct Lisp_Process *p = XPROCESS (proc);
4650 Lisp_Object ip_addresses = Qnil;
4651
4652 /* Sanity check. */
4653 if (! p->dns_request)
4654 return Qnil;
4655
4656 int ret = gai_error (p->dns_request);
4657 if (ret == EAI_INPROGRESS)
4658 return Qt;
4659
4660 /* We got a response. */
4661 if (ret == 0)
4662 {
4663 struct addrinfo *res;
4664
4665 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4666 {
4667 ip_addresses = Fcons (conv_sockaddr_to_lisp
4668 (res->ai_addr, res->ai_addrlen),
4669 ip_addresses);
4670 }
4671
4672 ip_addresses = Fnreverse (ip_addresses);
4673 }
4674 /* The DNS lookup failed. */
4675 else if (EQ (p->status, Qconnect))
4676 {
4677 deactivate_process (proc);
4678 pset_status (p, (list2
4679 (Qfailed,
4680 concat3 (build_string ("Name lookup of "),
4681 build_string (p->dns_request->ar_name),
4682 build_string (" failed")))));
4683 }
4684
4685 free_dns_request (proc);
4686
4687 /* This process should not already be connected (or killed). */
4688 if (!EQ (p->status, Qconnect))
4689 return Qnil;
4690
4691 return ip_addresses;
4692 }
4693
4694 #endif /* HAVE_GETADDRINFO_A */
4695
4696 static void
4697 wait_for_socket_fds (Lisp_Object process, char const *name)
4698 {
4699 while (XPROCESS (process)->infd < 0
4700 && EQ (XPROCESS (process)->status, Qconnect))
4701 {
4702 add_to_log ("Waiting for socket from %s...", build_string (name));
4703 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4704 }
4705 }
4706
4707 static void
4708 wait_while_connecting (Lisp_Object process)
4709 {
4710 while (EQ (XPROCESS (process)->status, Qconnect))
4711 {
4712 add_to_log ("Waiting for connection...");
4713 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4714 }
4715 }
4716
4717 static void
4718 wait_for_tls_negotiation (Lisp_Object process)
4719 {
4720 #ifdef HAVE_GNUTLS
4721 while (XPROCESS (process)->gnutls_p
4722 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4723 {
4724 add_to_log ("Waiting for TLS...");
4725 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4726 }
4727 #endif
4728 }
4729
4730 /* This variable is different from waiting_for_input in keyboard.c.
4731 It is used to communicate to a lisp process-filter/sentinel (via the
4732 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4733 for user-input when that process-filter was called.
4734 waiting_for_input cannot be used as that is by definition 0 when
4735 lisp code is being evalled.
4736 This is also used in record_asynch_buffer_change.
4737 For that purpose, this must be 0
4738 when not inside wait_reading_process_output. */
4739 static int waiting_for_user_input_p;
4740
4741 static void
4742 wait_reading_process_output_unwind (int data)
4743 {
4744 waiting_for_user_input_p = data;
4745 }
4746
4747 /* This is here so breakpoints can be put on it. */
4748 static void
4749 wait_reading_process_output_1 (void)
4750 {
4751 }
4752
4753 /* Read and dispose of subprocess output while waiting for timeout to
4754 elapse and/or keyboard input to be available.
4755
4756 TIME_LIMIT is:
4757 timeout in seconds
4758 If negative, gobble data immediately available but don't wait for any.
4759
4760 NSECS is:
4761 an additional duration to wait, measured in nanoseconds
4762 If TIME_LIMIT is zero, then:
4763 If NSECS == 0, there is no limit.
4764 If NSECS > 0, the timeout consists of NSECS only.
4765 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4766
4767 READ_KBD is:
4768 0 to ignore keyboard input, or
4769 1 to return when input is available, or
4770 -1 meaning caller will actually read the input, so don't throw to
4771 the quit handler, or
4772
4773 DO_DISPLAY means redisplay should be done to show subprocess
4774 output that arrives.
4775
4776 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4777 (and gobble terminal input into the buffer if any arrives).
4778
4779 If WAIT_PROC is specified, wait until something arrives from that
4780 process.
4781
4782 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4783 (suspending output from other processes). A negative value
4784 means don't run any timers either.
4785
4786 Return positive if we received input from WAIT_PROC (or from any
4787 process if WAIT_PROC is null), zero if we attempted to receive
4788 input but got none, and negative if we didn't even try. */
4789
4790 int
4791 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4792 bool do_display,
4793 Lisp_Object wait_for_cell,
4794 struct Lisp_Process *wait_proc, int just_wait_proc)
4795 {
4796 int channel, nfds;
4797 fd_set Available;
4798 fd_set Writeok;
4799 bool check_write;
4800 int check_delay;
4801 bool no_avail;
4802 int xerrno;
4803 Lisp_Object proc;
4804 struct timespec timeout, end_time, timer_delay;
4805 struct timespec got_output_end_time = invalid_timespec ();
4806 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4807 int got_some_output = -1;
4808 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4809 bool retry_for_async;
4810 #endif
4811 ptrdiff_t count = SPECPDL_INDEX ();
4812
4813 /* Close to the current time if known, an invalid timespec otherwise. */
4814 struct timespec now = invalid_timespec ();
4815
4816 FD_ZERO (&Available);
4817 FD_ZERO (&Writeok);
4818
4819 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4820 && !(CONSP (wait_proc->status)
4821 && EQ (XCAR (wait_proc->status), Qexit)))
4822 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4823
4824 record_unwind_protect_int (wait_reading_process_output_unwind,
4825 waiting_for_user_input_p);
4826 waiting_for_user_input_p = read_kbd;
4827
4828 if (TYPE_MAXIMUM (time_t) < time_limit)
4829 time_limit = TYPE_MAXIMUM (time_t);
4830
4831 if (time_limit < 0 || nsecs < 0)
4832 wait = MINIMUM;
4833 else if (time_limit > 0 || nsecs > 0)
4834 {
4835 wait = TIMEOUT;
4836 now = current_timespec ();
4837 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4838 }
4839 else
4840 wait = INFINITY;
4841
4842 while (1)
4843 {
4844 bool process_skipped = false;
4845
4846 /* If calling from keyboard input, do not quit
4847 since we want to return C-g as an input character.
4848 Otherwise, do pending quit if requested. */
4849 if (read_kbd >= 0)
4850 QUIT;
4851 else if (pending_signals)
4852 process_pending_signals ();
4853
4854 /* Exit now if the cell we're waiting for became non-nil. */
4855 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4856 break;
4857
4858 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4859 {
4860 Lisp_Object process_list_head, aproc;
4861 struct Lisp_Process *p;
4862
4863 retry_for_async = false;
4864 FOR_EACH_PROCESS(process_list_head, aproc)
4865 {
4866 p = XPROCESS (aproc);
4867
4868 if (! wait_proc || p == wait_proc)
4869 {
4870 #ifdef HAVE_GETADDRINFO_A
4871 /* Check for pending DNS requests. */
4872 if (p->dns_request)
4873 {
4874 Lisp_Object ip_addresses = check_for_dns (aproc);
4875 if (!NILP (ip_addresses) && !EQ (ip_addresses, Qt))
4876 connect_network_socket (aproc, ip_addresses, Qnil);
4877 else
4878 retry_for_async = true;
4879 }
4880 #endif
4881 #ifdef HAVE_GNUTLS
4882 /* Continue TLS negotiation. */
4883 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
4884 && p->is_non_blocking_client)
4885 {
4886 gnutls_try_handshake (p);
4887 p->gnutls_handshakes_tried++;
4888
4889 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
4890 {
4891 gnutls_verify_boot (aproc, Qnil);
4892 finish_after_tls_connection (aproc);
4893 }
4894 else
4895 {
4896 retry_for_async = true;
4897 if (p->gnutls_handshakes_tried
4898 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
4899 {
4900 deactivate_process (aproc);
4901 pset_status (p, list2 (Qfailed,
4902 build_string ("TLS negotiation failed")));
4903 }
4904 }
4905 }
4906 #endif
4907 }
4908 }
4909 }
4910 #endif /* GETADDRINFO_A or GNUTLS */
4911
4912 /* Compute time from now till when time limit is up. */
4913 /* Exit if already run out. */
4914 if (wait == TIMEOUT)
4915 {
4916 if (!timespec_valid_p (now))
4917 now = current_timespec ();
4918 if (timespec_cmp (end_time, now) <= 0)
4919 break;
4920 timeout = timespec_sub (end_time, now);
4921 }
4922 else
4923 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4924
4925 /* Normally we run timers here.
4926 But not if wait_for_cell; in those cases,
4927 the wait is supposed to be short,
4928 and those callers cannot handle running arbitrary Lisp code here. */
4929 if (NILP (wait_for_cell)
4930 && just_wait_proc >= 0)
4931 {
4932 do
4933 {
4934 unsigned old_timers_run = timers_run;
4935 struct buffer *old_buffer = current_buffer;
4936 Lisp_Object old_window = selected_window;
4937
4938 timer_delay = timer_check ();
4939
4940 /* If a timer has run, this might have changed buffers
4941 an alike. Make read_key_sequence aware of that. */
4942 if (timers_run != old_timers_run
4943 && (old_buffer != current_buffer
4944 || !EQ (old_window, selected_window))
4945 && waiting_for_user_input_p == -1)
4946 record_asynch_buffer_change ();
4947
4948 if (timers_run != old_timers_run && do_display)
4949 /* We must retry, since a timer may have requeued itself
4950 and that could alter the time_delay. */
4951 redisplay_preserve_echo_area (9);
4952 else
4953 break;
4954 }
4955 while (!detect_input_pending ());
4956
4957 /* If there is unread keyboard input, also return. */
4958 if (read_kbd != 0
4959 && requeued_events_pending_p ())
4960 break;
4961
4962 /* This is so a breakpoint can be put here. */
4963 if (!timespec_valid_p (timer_delay))
4964 wait_reading_process_output_1 ();
4965 }
4966
4967 /* Cause C-g and alarm signals to take immediate action,
4968 and cause input available signals to zero out timeout.
4969
4970 It is important that we do this before checking for process
4971 activity. If we get a SIGCHLD after the explicit checks for
4972 process activity, timeout is the only way we will know. */
4973 if (read_kbd < 0)
4974 set_waiting_for_input (&timeout);
4975
4976 /* If status of something has changed, and no input is
4977 available, notify the user of the change right away. After
4978 this explicit check, we'll let the SIGCHLD handler zap
4979 timeout to get our attention. */
4980 if (update_tick != process_tick)
4981 {
4982 fd_set Atemp;
4983 fd_set Ctemp;
4984
4985 if (kbd_on_hold_p ())
4986 FD_ZERO (&Atemp);
4987 else
4988 Atemp = input_wait_mask;
4989 Ctemp = write_mask;
4990
4991 timeout = make_timespec (0, 0);
4992 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4993 &Atemp,
4994 (num_pending_connects > 0 ? &Ctemp : NULL),
4995 NULL, &timeout, NULL)
4996 <= 0))
4997 {
4998 /* It's okay for us to do this and then continue with
4999 the loop, since timeout has already been zeroed out. */
5000 clear_waiting_for_input ();
5001 got_some_output = status_notify (NULL, wait_proc);
5002 if (do_display) redisplay_preserve_echo_area (13);
5003 }
5004 }
5005
5006 /* Don't wait for output from a non-running process. Just
5007 read whatever data has already been received. */
5008 if (wait_proc && wait_proc->raw_status_new)
5009 update_status (wait_proc);
5010 if (wait_proc
5011 && ! EQ (wait_proc->status, Qrun)
5012 && ! EQ (wait_proc->status, Qconnect))
5013 {
5014 bool read_some_bytes = false;
5015
5016 clear_waiting_for_input ();
5017
5018 /* If data can be read from the process, do so until exhausted. */
5019 if (wait_proc->infd >= 0)
5020 {
5021 XSETPROCESS (proc, wait_proc);
5022
5023 while (true)
5024 {
5025 int nread = read_process_output (proc, wait_proc->infd);
5026 if (nread < 0)
5027 {
5028 if (errno == EIO || would_block (errno))
5029 break;
5030 }
5031 else
5032 {
5033 if (got_some_output < nread)
5034 got_some_output = nread;
5035 if (nread == 0)
5036 break;
5037 read_some_bytes = true;
5038 }
5039 }
5040 }
5041
5042 if (read_some_bytes && do_display)
5043 redisplay_preserve_echo_area (10);
5044
5045 break;
5046 }
5047
5048 /* Wait till there is something to do. */
5049
5050 if (wait_proc && just_wait_proc)
5051 {
5052 if (wait_proc->infd < 0) /* Terminated. */
5053 break;
5054 FD_SET (wait_proc->infd, &Available);
5055 check_delay = 0;
5056 check_write = 0;
5057 }
5058 else if (!NILP (wait_for_cell))
5059 {
5060 Available = non_process_wait_mask;
5061 check_delay = 0;
5062 check_write = 0;
5063 }
5064 else
5065 {
5066 if (! read_kbd)
5067 Available = non_keyboard_wait_mask;
5068 else
5069 Available = input_wait_mask;
5070 Writeok = write_mask;
5071 check_delay = wait_proc ? 0 : process_output_delay_count;
5072 check_write = true;
5073 }
5074
5075 /* If frame size has changed or the window is newly mapped,
5076 redisplay now, before we start to wait. There is a race
5077 condition here; if a SIGIO arrives between now and the select
5078 and indicates that a frame is trashed, the select may block
5079 displaying a trashed screen. */
5080 if (frame_garbaged && do_display)
5081 {
5082 clear_waiting_for_input ();
5083 redisplay_preserve_echo_area (11);
5084 if (read_kbd < 0)
5085 set_waiting_for_input (&timeout);
5086 }
5087
5088 /* Skip the `select' call if input is available and we're
5089 waiting for keyboard input or a cell change (which can be
5090 triggered by processing X events). In the latter case, set
5091 nfds to 1 to avoid breaking the loop. */
5092 no_avail = 0;
5093 if ((read_kbd || !NILP (wait_for_cell))
5094 && detect_input_pending ())
5095 {
5096 nfds = read_kbd ? 0 : 1;
5097 no_avail = 1;
5098 FD_ZERO (&Available);
5099 }
5100 else
5101 {
5102 /* Set the timeout for adaptive read buffering if any
5103 process has non-zero read_output_skip and non-zero
5104 read_output_delay, and we are not reading output for a
5105 specific process. It is not executed if
5106 Vprocess_adaptive_read_buffering is nil. */
5107 if (process_output_skip && check_delay > 0)
5108 {
5109 int adaptive_nsecs = timeout.tv_nsec;
5110 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5111 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5112 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
5113 {
5114 proc = chan_process[channel];
5115 if (NILP (proc))
5116 continue;
5117 /* Find minimum non-zero read_output_delay among the
5118 processes with non-zero read_output_skip. */
5119 if (XPROCESS (proc)->read_output_delay > 0)
5120 {
5121 check_delay--;
5122 if (!XPROCESS (proc)->read_output_skip)
5123 continue;
5124 FD_CLR (channel, &Available);
5125 process_skipped = true;
5126 XPROCESS (proc)->read_output_skip = 0;
5127 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5128 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5129 }
5130 }
5131 timeout = make_timespec (0, adaptive_nsecs);
5132 process_output_skip = 0;
5133 }
5134
5135 /* If we've got some output and haven't limited our timeout
5136 with adaptive read buffering, limit it. */
5137 if (got_some_output > 0 && !process_skipped
5138 && (timeout.tv_sec
5139 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5140 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5141
5142
5143 if (NILP (wait_for_cell) && just_wait_proc >= 0
5144 && timespec_valid_p (timer_delay)
5145 && timespec_cmp (timer_delay, timeout) < 0)
5146 {
5147 if (!timespec_valid_p (now))
5148 now = current_timespec ();
5149 struct timespec timeout_abs = timespec_add (now, timeout);
5150 if (!timespec_valid_p (got_output_end_time)
5151 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5152 got_output_end_time = timeout_abs;
5153 timeout = timer_delay;
5154 }
5155 else
5156 got_output_end_time = invalid_timespec ();
5157
5158 /* NOW can become inaccurate if time can pass during pselect. */
5159 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5160 now = invalid_timespec ();
5161
5162 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5163 if (retry_for_async
5164 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5165 {
5166 timeout.tv_sec = 0;
5167 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5168 }
5169 #endif
5170
5171 #if defined (HAVE_NS)
5172 nfds = ns_select
5173 #elif defined (HAVE_GLIB)
5174 nfds = xg_select
5175 #else
5176 nfds = pselect
5177 #endif
5178 (max (max_process_desc, max_input_desc) + 1,
5179 &Available,
5180 (check_write ? &Writeok : 0),
5181 NULL, &timeout, NULL);
5182
5183 #ifdef HAVE_GNUTLS
5184 /* GnuTLS buffers data internally. In lowat mode it leaves
5185 some data in the TCP buffers so that select works, but
5186 with custom pull/push functions we need to check if some
5187 data is available in the buffers manually. */
5188 if (nfds == 0)
5189 {
5190 fd_set tls_available;
5191 int set = 0;
5192
5193 FD_ZERO (&tls_available);
5194 if (! wait_proc)
5195 {
5196 /* We're not waiting on a specific process, so loop
5197 through all the channels and check for data.
5198 This is a workaround needed for some versions of
5199 the gnutls library -- 2.12.14 has been confirmed
5200 to need it. See
5201 http://comments.gmane.org/gmane.emacs.devel/145074 */
5202 for (channel = 0; channel < FD_SETSIZE; ++channel)
5203 if (! NILP (chan_process[channel]))
5204 {
5205 struct Lisp_Process *p =
5206 XPROCESS (chan_process[channel]);
5207 if (p && p->gnutls_p && p->gnutls_state
5208 && ((emacs_gnutls_record_check_pending
5209 (p->gnutls_state))
5210 > 0))
5211 {
5212 nfds++;
5213 eassert (p->infd == channel);
5214 FD_SET (p->infd, &tls_available);
5215 set++;
5216 }
5217 }
5218 }
5219 else
5220 {
5221 /* Check this specific channel. */
5222 if (wait_proc->gnutls_p /* Check for valid process. */
5223 && wait_proc->gnutls_state
5224 /* Do we have pending data? */
5225 && ((emacs_gnutls_record_check_pending
5226 (wait_proc->gnutls_state))
5227 > 0))
5228 {
5229 nfds = 1;
5230 eassert (0 <= wait_proc->infd);
5231 /* Set to Available. */
5232 FD_SET (wait_proc->infd, &tls_available);
5233 set++;
5234 }
5235 }
5236 if (set)
5237 Available = tls_available;
5238 }
5239 #endif
5240 }
5241
5242 xerrno = errno;
5243
5244 /* Make C-g and alarm signals set flags again. */
5245 clear_waiting_for_input ();
5246
5247 /* If we woke up due to SIGWINCH, actually change size now. */
5248 do_pending_window_change (0);
5249
5250 if (nfds == 0)
5251 {
5252 /* Exit the main loop if we've passed the requested timeout,
5253 or aren't skipping processes and got some output and
5254 haven't lowered our timeout due to timers or SIGIO and
5255 have waited a long amount of time due to repeated
5256 timers. */
5257 if (wait < TIMEOUT)
5258 break;
5259 struct timespec cmp_time
5260 = (wait == TIMEOUT
5261 ? end_time
5262 : (!process_skipped && got_some_output > 0
5263 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5264 ? got_output_end_time
5265 : invalid_timespec ());
5266 if (timespec_valid_p (cmp_time))
5267 {
5268 now = current_timespec ();
5269 if (timespec_cmp (cmp_time, now) <= 0)
5270 break;
5271 }
5272 }
5273
5274 if (nfds < 0)
5275 {
5276 if (xerrno == EINTR)
5277 no_avail = 1;
5278 else if (xerrno == EBADF)
5279 emacs_abort ();
5280 else
5281 report_file_errno ("Failed select", Qnil, xerrno);
5282 }
5283
5284 /* Check for keyboard input. */
5285 /* If there is any, return immediately
5286 to give it higher priority than subprocesses. */
5287
5288 if (read_kbd != 0)
5289 {
5290 unsigned old_timers_run = timers_run;
5291 struct buffer *old_buffer = current_buffer;
5292 Lisp_Object old_window = selected_window;
5293 bool leave = false;
5294
5295 if (detect_input_pending_run_timers (do_display))
5296 {
5297 swallow_events (do_display);
5298 if (detect_input_pending_run_timers (do_display))
5299 leave = true;
5300 }
5301
5302 /* If a timer has run, this might have changed buffers
5303 an alike. Make read_key_sequence aware of that. */
5304 if (timers_run != old_timers_run
5305 && waiting_for_user_input_p == -1
5306 && (old_buffer != current_buffer
5307 || !EQ (old_window, selected_window)))
5308 record_asynch_buffer_change ();
5309
5310 if (leave)
5311 break;
5312 }
5313
5314 /* If there is unread keyboard input, also return. */
5315 if (read_kbd != 0
5316 && requeued_events_pending_p ())
5317 break;
5318
5319 /* If we are not checking for keyboard input now,
5320 do process events (but don't run any timers).
5321 This is so that X events will be processed.
5322 Otherwise they may have to wait until polling takes place.
5323 That would causes delays in pasting selections, for example.
5324
5325 (We used to do this only if wait_for_cell.) */
5326 if (read_kbd == 0 && detect_input_pending ())
5327 {
5328 swallow_events (do_display);
5329 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5330 if (detect_input_pending ())
5331 break;
5332 #endif
5333 }
5334
5335 /* Exit now if the cell we're waiting for became non-nil. */
5336 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5337 break;
5338
5339 #ifdef USABLE_SIGIO
5340 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5341 go read it. This can happen with X on BSD after logging out.
5342 In that case, there really is no input and no SIGIO,
5343 but select says there is input. */
5344
5345 if (read_kbd && interrupt_input
5346 && keyboard_bit_set (&Available) && ! noninteractive)
5347 handle_input_available_signal (SIGIO);
5348 #endif
5349
5350 /* If checking input just got us a size-change event from X,
5351 obey it now if we should. */
5352 if (read_kbd || ! NILP (wait_for_cell))
5353 do_pending_window_change (0);
5354
5355 /* Check for data from a process. */
5356 if (no_avail || nfds == 0)
5357 continue;
5358
5359 for (channel = 0; channel <= max_input_desc; ++channel)
5360 {
5361 struct fd_callback_data *d = &fd_callback_info[channel];
5362 if (d->func
5363 && ((d->condition & FOR_READ
5364 && FD_ISSET (channel, &Available))
5365 || (d->condition & FOR_WRITE
5366 && FD_ISSET (channel, &write_mask))))
5367 d->func (channel, d->data);
5368 }
5369
5370 for (channel = 0; channel <= max_process_desc; channel++)
5371 {
5372 if (FD_ISSET (channel, &Available)
5373 && FD_ISSET (channel, &non_keyboard_wait_mask)
5374 && !FD_ISSET (channel, &non_process_wait_mask))
5375 {
5376 int nread;
5377
5378 /* If waiting for this channel, arrange to return as
5379 soon as no more input to be processed. No more
5380 waiting. */
5381 proc = chan_process[channel];
5382 if (NILP (proc))
5383 continue;
5384
5385 /* If this is a server stream socket, accept connection. */
5386 if (EQ (XPROCESS (proc)->status, Qlisten))
5387 {
5388 server_accept_connection (proc, channel);
5389 continue;
5390 }
5391
5392 /* Read data from the process, starting with our
5393 buffered-ahead character if we have one. */
5394
5395 nread = read_process_output (proc, channel);
5396 if ((!wait_proc || wait_proc == XPROCESS (proc))
5397 && got_some_output < nread)
5398 got_some_output = nread;
5399 if (nread > 0)
5400 {
5401 /* Vacuum up any leftovers without waiting. */
5402 if (wait_proc == XPROCESS (proc))
5403 wait = MINIMUM;
5404 /* Since read_process_output can run a filter,
5405 which can call accept-process-output,
5406 don't try to read from any other processes
5407 before doing the select again. */
5408 FD_ZERO (&Available);
5409
5410 if (do_display)
5411 redisplay_preserve_echo_area (12);
5412 }
5413 else if (nread == -1 && would_block (errno))
5414 ;
5415 #ifdef WINDOWSNT
5416 /* FIXME: Is this special case still needed? */
5417 /* Note that we cannot distinguish between no input
5418 available now and a closed pipe.
5419 With luck, a closed pipe will be accompanied by
5420 subprocess termination and SIGCHLD. */
5421 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5422 && !PIPECONN_P (proc))
5423 ;
5424 #endif
5425 #ifdef HAVE_PTYS
5426 /* On some OSs with ptys, when the process on one end of
5427 a pty exits, the other end gets an error reading with
5428 errno = EIO instead of getting an EOF (0 bytes read).
5429 Therefore, if we get an error reading and errno =
5430 EIO, just continue, because the child process has
5431 exited and should clean itself up soon (e.g. when we
5432 get a SIGCHLD). */
5433 else if (nread == -1 && errno == EIO)
5434 {
5435 struct Lisp_Process *p = XPROCESS (proc);
5436
5437 /* Clear the descriptor now, so we only raise the
5438 signal once. */
5439 FD_CLR (channel, &input_wait_mask);
5440 FD_CLR (channel, &non_keyboard_wait_mask);
5441
5442 if (p->pid == -2)
5443 {
5444 /* If the EIO occurs on a pty, the SIGCHLD handler's
5445 waitpid call will not find the process object to
5446 delete. Do it here. */
5447 p->tick = ++process_tick;
5448 pset_status (p, Qfailed);
5449 }
5450 }
5451 #endif /* HAVE_PTYS */
5452 /* If we can detect process termination, don't consider the
5453 process gone just because its pipe is closed. */
5454 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5455 && !PIPECONN_P (proc))
5456 ;
5457 else if (nread == 0 && PIPECONN_P (proc))
5458 {
5459 /* Preserve status of processes already terminated. */
5460 XPROCESS (proc)->tick = ++process_tick;
5461 deactivate_process (proc);
5462 if (EQ (XPROCESS (proc)->status, Qrun))
5463 pset_status (XPROCESS (proc),
5464 list2 (Qexit, make_number (0)));
5465 }
5466 else
5467 {
5468 /* Preserve status of processes already terminated. */
5469 XPROCESS (proc)->tick = ++process_tick;
5470 deactivate_process (proc);
5471 if (XPROCESS (proc)->raw_status_new)
5472 update_status (XPROCESS (proc));
5473 if (EQ (XPROCESS (proc)->status, Qrun))
5474 pset_status (XPROCESS (proc),
5475 list2 (Qexit, make_number (256)));
5476 }
5477 }
5478 if (FD_ISSET (channel, &Writeok)
5479 && FD_ISSET (channel, &connect_wait_mask))
5480 {
5481 struct Lisp_Process *p;
5482
5483 FD_CLR (channel, &connect_wait_mask);
5484 FD_CLR (channel, &write_mask);
5485 if (--num_pending_connects < 0)
5486 emacs_abort ();
5487
5488 proc = chan_process[channel];
5489 if (NILP (proc))
5490 continue;
5491
5492 p = XPROCESS (proc);
5493
5494 #ifdef GNU_LINUX
5495 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5496 So only use it on systems where it is known to work. */
5497 {
5498 socklen_t xlen = sizeof (xerrno);
5499 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5500 xerrno = errno;
5501 }
5502 #else
5503 {
5504 struct sockaddr pname;
5505 socklen_t pnamelen = sizeof (pname);
5506
5507 /* If connection failed, getpeername will fail. */
5508 xerrno = 0;
5509 if (getpeername (channel, &pname, &pnamelen) < 0)
5510 {
5511 /* Obtain connect failure code through error slippage. */
5512 char dummy;
5513 xerrno = errno;
5514 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5515 xerrno = errno;
5516 }
5517 }
5518 #endif
5519 if (xerrno)
5520 {
5521 p->tick = ++process_tick;
5522 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5523 deactivate_process (proc);
5524 }
5525 else
5526 {
5527 #ifdef HAVE_GNUTLS
5528 /* If we have an incompletely set up TLS connection,
5529 then defer the sentinel signaling until
5530 later. */
5531 if (NILP (p->gnutls_boot_parameters)
5532 && !p->gnutls_p)
5533 #endif
5534 {
5535 pset_status (p, Qrun);
5536 /* Execute the sentinel here. If we had relied on
5537 status_notify to do it later, it will read input
5538 from the process before calling the sentinel. */
5539 exec_sentinel (proc, build_string ("open\n"));
5540 }
5541
5542 if (0 <= p->infd && !EQ (p->filter, Qt)
5543 && !EQ (p->command, Qt))
5544 {
5545 FD_SET (p->infd, &input_wait_mask);
5546 FD_SET (p->infd, &non_keyboard_wait_mask);
5547 }
5548 }
5549 }
5550 } /* End for each file descriptor. */
5551 } /* End while exit conditions not met. */
5552
5553 unbind_to (count, Qnil);
5554
5555 /* If calling from keyboard input, do not quit
5556 since we want to return C-g as an input character.
5557 Otherwise, do pending quit if requested. */
5558 if (read_kbd >= 0)
5559 {
5560 /* Prevent input_pending from remaining set if we quit. */
5561 clear_input_pending ();
5562 QUIT;
5563 }
5564
5565 return got_some_output;
5566 }
5567 \f
5568 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5569
5570 static Lisp_Object
5571 read_process_output_call (Lisp_Object fun_and_args)
5572 {
5573 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5574 }
5575
5576 static Lisp_Object
5577 read_process_output_error_handler (Lisp_Object error_val)
5578 {
5579 cmd_error_internal (error_val, "error in process filter: ");
5580 Vinhibit_quit = Qt;
5581 update_echo_area ();
5582 Fsleep_for (make_number (2), Qnil);
5583 return Qt;
5584 }
5585
5586 static void
5587 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5588 ssize_t nbytes,
5589 struct coding_system *coding);
5590
5591 /* Read pending output from the process channel,
5592 starting with our buffered-ahead character if we have one.
5593 Yield number of decoded characters read.
5594
5595 This function reads at most 4096 characters.
5596 If you want to read all available subprocess output,
5597 you must call it repeatedly until it returns zero.
5598
5599 The characters read are decoded according to PROC's coding-system
5600 for decoding. */
5601
5602 static int
5603 read_process_output (Lisp_Object proc, int channel)
5604 {
5605 ssize_t nbytes;
5606 struct Lisp_Process *p = XPROCESS (proc);
5607 struct coding_system *coding = proc_decode_coding_system[channel];
5608 int carryover = p->decoding_carryover;
5609 enum { readmax = 4096 };
5610 ptrdiff_t count = SPECPDL_INDEX ();
5611 Lisp_Object odeactivate;
5612 char chars[sizeof coding->carryover + readmax];
5613
5614 if (carryover)
5615 /* See the comment above. */
5616 memcpy (chars, SDATA (p->decoding_buf), carryover);
5617
5618 #ifdef DATAGRAM_SOCKETS
5619 /* We have a working select, so proc_buffered_char is always -1. */
5620 if (DATAGRAM_CHAN_P (channel))
5621 {
5622 socklen_t len = datagram_address[channel].len;
5623 nbytes = recvfrom (channel, chars + carryover, readmax,
5624 0, datagram_address[channel].sa, &len);
5625 }
5626 else
5627 #endif
5628 {
5629 bool buffered = proc_buffered_char[channel] >= 0;
5630 if (buffered)
5631 {
5632 chars[carryover] = proc_buffered_char[channel];
5633 proc_buffered_char[channel] = -1;
5634 }
5635 #ifdef HAVE_GNUTLS
5636 if (p->gnutls_p && p->gnutls_state)
5637 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5638 readmax - buffered);
5639 else
5640 #endif
5641 nbytes = emacs_read (channel, chars + carryover + buffered,
5642 readmax - buffered);
5643 if (nbytes > 0 && p->adaptive_read_buffering)
5644 {
5645 int delay = p->read_output_delay;
5646 if (nbytes < 256)
5647 {
5648 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5649 {
5650 if (delay == 0)
5651 process_output_delay_count++;
5652 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5653 }
5654 }
5655 else if (delay > 0 && nbytes == readmax - buffered)
5656 {
5657 delay -= READ_OUTPUT_DELAY_INCREMENT;
5658 if (delay == 0)
5659 process_output_delay_count--;
5660 }
5661 p->read_output_delay = delay;
5662 if (delay)
5663 {
5664 p->read_output_skip = 1;
5665 process_output_skip = 1;
5666 }
5667 }
5668 nbytes += buffered;
5669 nbytes += buffered && nbytes <= 0;
5670 }
5671
5672 p->decoding_carryover = 0;
5673
5674 /* At this point, NBYTES holds number of bytes just received
5675 (including the one in proc_buffered_char[channel]). */
5676 if (nbytes <= 0)
5677 {
5678 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5679 return nbytes;
5680 coding->mode |= CODING_MODE_LAST_BLOCK;
5681 }
5682
5683 /* Now set NBYTES how many bytes we must decode. */
5684 nbytes += carryover;
5685
5686 odeactivate = Vdeactivate_mark;
5687 /* There's no good reason to let process filters change the current
5688 buffer, and many callers of accept-process-output, sit-for, and
5689 friends don't expect current-buffer to be changed from under them. */
5690 record_unwind_current_buffer ();
5691
5692 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5693
5694 /* Handling the process output should not deactivate the mark. */
5695 Vdeactivate_mark = odeactivate;
5696
5697 unbind_to (count, Qnil);
5698 return nbytes;
5699 }
5700
5701 static void
5702 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5703 ssize_t nbytes,
5704 struct coding_system *coding)
5705 {
5706 Lisp_Object outstream = p->filter;
5707 Lisp_Object text;
5708 bool outer_running_asynch_code = running_asynch_code;
5709 int waiting = waiting_for_user_input_p;
5710
5711 #if 0
5712 Lisp_Object obuffer, okeymap;
5713 XSETBUFFER (obuffer, current_buffer);
5714 okeymap = BVAR (current_buffer, keymap);
5715 #endif
5716
5717 /* We inhibit quit here instead of just catching it so that
5718 hitting ^G when a filter happens to be running won't screw
5719 it up. */
5720 specbind (Qinhibit_quit, Qt);
5721 specbind (Qlast_nonmenu_event, Qt);
5722
5723 /* In case we get recursively called,
5724 and we already saved the match data nonrecursively,
5725 save the same match data in safely recursive fashion. */
5726 if (outer_running_asynch_code)
5727 {
5728 Lisp_Object tem;
5729 /* Don't clobber the CURRENT match data, either! */
5730 tem = Fmatch_data (Qnil, Qnil, Qnil);
5731 restore_search_regs ();
5732 record_unwind_save_match_data ();
5733 Fset_match_data (tem, Qt);
5734 }
5735
5736 /* For speed, if a search happens within this code,
5737 save the match data in a special nonrecursive fashion. */
5738 running_asynch_code = 1;
5739
5740 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5741 text = coding->dst_object;
5742 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5743 /* A new coding system might be found. */
5744 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5745 {
5746 pset_decode_coding_system (p, Vlast_coding_system_used);
5747
5748 /* Don't call setup_coding_system for
5749 proc_decode_coding_system[channel] here. It is done in
5750 detect_coding called via decode_coding above. */
5751
5752 /* If a coding system for encoding is not yet decided, we set
5753 it as the same as coding-system for decoding.
5754
5755 But, before doing that we must check if
5756 proc_encode_coding_system[p->outfd] surely points to a
5757 valid memory because p->outfd will be changed once EOF is
5758 sent to the process. */
5759 if (NILP (p->encode_coding_system) && p->outfd >= 0
5760 && proc_encode_coding_system[p->outfd])
5761 {
5762 pset_encode_coding_system
5763 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5764 setup_coding_system (p->encode_coding_system,
5765 proc_encode_coding_system[p->outfd]);
5766 }
5767 }
5768
5769 if (coding->carryover_bytes > 0)
5770 {
5771 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5772 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5773 memcpy (SDATA (p->decoding_buf), coding->carryover,
5774 coding->carryover_bytes);
5775 p->decoding_carryover = coding->carryover_bytes;
5776 }
5777 if (SBYTES (text) > 0)
5778 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5779 sometimes it's simply wrong to wrap (e.g. when called from
5780 accept-process-output). */
5781 internal_condition_case_1 (read_process_output_call,
5782 list3 (outstream, make_lisp_proc (p), text),
5783 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5784 read_process_output_error_handler);
5785
5786 /* If we saved the match data nonrecursively, restore it now. */
5787 restore_search_regs ();
5788 running_asynch_code = outer_running_asynch_code;
5789
5790 /* Restore waiting_for_user_input_p as it was
5791 when we were called, in case the filter clobbered it. */
5792 waiting_for_user_input_p = waiting;
5793
5794 #if 0 /* Call record_asynch_buffer_change unconditionally,
5795 because we might have changed minor modes or other things
5796 that affect key bindings. */
5797 if (! EQ (Fcurrent_buffer (), obuffer)
5798 || ! EQ (current_buffer->keymap, okeymap))
5799 #endif
5800 /* But do it only if the caller is actually going to read events.
5801 Otherwise there's no need to make him wake up, and it could
5802 cause trouble (for example it would make sit_for return). */
5803 if (waiting_for_user_input_p == -1)
5804 record_asynch_buffer_change ();
5805 }
5806
5807 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5808 Sinternal_default_process_filter, 2, 2, 0,
5809 doc: /* Function used as default process filter.
5810 This inserts the process's output into its buffer, if there is one.
5811 Otherwise it discards the output. */)
5812 (Lisp_Object proc, Lisp_Object text)
5813 {
5814 struct Lisp_Process *p;
5815 ptrdiff_t opoint;
5816
5817 CHECK_PROCESS (proc);
5818 p = XPROCESS (proc);
5819 CHECK_STRING (text);
5820
5821 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5822 {
5823 Lisp_Object old_read_only;
5824 ptrdiff_t old_begv, old_zv;
5825 ptrdiff_t old_begv_byte, old_zv_byte;
5826 ptrdiff_t before, before_byte;
5827 ptrdiff_t opoint_byte;
5828 struct buffer *b;
5829
5830 Fset_buffer (p->buffer);
5831 opoint = PT;
5832 opoint_byte = PT_BYTE;
5833 old_read_only = BVAR (current_buffer, read_only);
5834 old_begv = BEGV;
5835 old_zv = ZV;
5836 old_begv_byte = BEGV_BYTE;
5837 old_zv_byte = ZV_BYTE;
5838
5839 bset_read_only (current_buffer, Qnil);
5840
5841 /* Insert new output into buffer at the current end-of-output
5842 marker, thus preserving logical ordering of input and output. */
5843 if (XMARKER (p->mark)->buffer)
5844 set_point_from_marker (p->mark);
5845 else
5846 SET_PT_BOTH (ZV, ZV_BYTE);
5847 before = PT;
5848 before_byte = PT_BYTE;
5849
5850 /* If the output marker is outside of the visible region, save
5851 the restriction and widen. */
5852 if (! (BEGV <= PT && PT <= ZV))
5853 Fwiden ();
5854
5855 /* Adjust the multibyteness of TEXT to that of the buffer. */
5856 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5857 != ! STRING_MULTIBYTE (text))
5858 text = (STRING_MULTIBYTE (text)
5859 ? Fstring_as_unibyte (text)
5860 : Fstring_to_multibyte (text));
5861 /* Insert before markers in case we are inserting where
5862 the buffer's mark is, and the user's next command is Meta-y. */
5863 insert_from_string_before_markers (text, 0, 0,
5864 SCHARS (text), SBYTES (text), 0);
5865
5866 /* Make sure the process marker's position is valid when the
5867 process buffer is changed in the signal_after_change above.
5868 W3 is known to do that. */
5869 if (BUFFERP (p->buffer)
5870 && (b = XBUFFER (p->buffer), b != current_buffer))
5871 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5872 else
5873 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5874
5875 update_mode_lines = 23;
5876
5877 /* Make sure opoint and the old restrictions
5878 float ahead of any new text just as point would. */
5879 if (opoint >= before)
5880 {
5881 opoint += PT - before;
5882 opoint_byte += PT_BYTE - before_byte;
5883 }
5884 if (old_begv > before)
5885 {
5886 old_begv += PT - before;
5887 old_begv_byte += PT_BYTE - before_byte;
5888 }
5889 if (old_zv >= before)
5890 {
5891 old_zv += PT - before;
5892 old_zv_byte += PT_BYTE - before_byte;
5893 }
5894
5895 /* If the restriction isn't what it should be, set it. */
5896 if (old_begv != BEGV || old_zv != ZV)
5897 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5898
5899 bset_read_only (current_buffer, old_read_only);
5900 SET_PT_BOTH (opoint, opoint_byte);
5901 }
5902 return Qnil;
5903 }
5904 \f
5905 /* Sending data to subprocess. */
5906
5907 /* In send_process, when a write fails temporarily,
5908 wait_reading_process_output is called. It may execute user code,
5909 e.g. timers, that attempts to write new data to the same process.
5910 We must ensure that data is sent in the right order, and not
5911 interspersed half-completed with other writes (Bug#10815). This is
5912 handled by the write_queue element of struct process. It is a list
5913 with each entry having the form
5914
5915 (string . (offset . length))
5916
5917 where STRING is a lisp string, OFFSET is the offset into the
5918 string's byte sequence from which we should begin to send, and
5919 LENGTH is the number of bytes left to send. */
5920
5921 /* Create a new entry in write_queue.
5922 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5923 BUF is a pointer to the string sequence of the input_obj or a C
5924 string in case of Qt or Qnil. */
5925
5926 static void
5927 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5928 const char *buf, ptrdiff_t len, bool front)
5929 {
5930 ptrdiff_t offset;
5931 Lisp_Object entry, obj;
5932
5933 if (STRINGP (input_obj))
5934 {
5935 offset = buf - SSDATA (input_obj);
5936 obj = input_obj;
5937 }
5938 else
5939 {
5940 offset = 0;
5941 obj = make_unibyte_string (buf, len);
5942 }
5943
5944 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5945
5946 if (front)
5947 pset_write_queue (p, Fcons (entry, p->write_queue));
5948 else
5949 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5950 }
5951
5952 /* Remove the first element in the write_queue of process P, put its
5953 contents in OBJ, BUF and LEN, and return true. If the
5954 write_queue is empty, return false. */
5955
5956 static bool
5957 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5958 const char **buf, ptrdiff_t *len)
5959 {
5960 Lisp_Object entry, offset_length;
5961 ptrdiff_t offset;
5962
5963 if (NILP (p->write_queue))
5964 return 0;
5965
5966 entry = XCAR (p->write_queue);
5967 pset_write_queue (p, XCDR (p->write_queue));
5968
5969 *obj = XCAR (entry);
5970 offset_length = XCDR (entry);
5971
5972 *len = XINT (XCDR (offset_length));
5973 offset = XINT (XCAR (offset_length));
5974 *buf = SSDATA (*obj) + offset;
5975
5976 return 1;
5977 }
5978
5979 /* Send some data to process PROC.
5980 BUF is the beginning of the data; LEN is the number of characters.
5981 OBJECT is the Lisp object that the data comes from. If OBJECT is
5982 nil or t, it means that the data comes from C string.
5983
5984 If OBJECT is not nil, the data is encoded by PROC's coding-system
5985 for encoding before it is sent.
5986
5987 This function can evaluate Lisp code and can garbage collect. */
5988
5989 static void
5990 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5991 Lisp_Object object)
5992 {
5993 struct Lisp_Process *p = XPROCESS (proc);
5994 ssize_t rv;
5995 struct coding_system *coding;
5996
5997 if (NETCONN_P (proc))
5998 {
5999 wait_while_connecting (proc);
6000 wait_for_tls_negotiation (proc);
6001 }
6002
6003 if (p->raw_status_new)
6004 update_status (p);
6005 if (! EQ (p->status, Qrun))
6006 error ("Process %s not running", SDATA (p->name));
6007 if (p->outfd < 0)
6008 error ("Output file descriptor of %s is closed", SDATA (p->name));
6009
6010 coding = proc_encode_coding_system[p->outfd];
6011 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6012
6013 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6014 || (BUFFERP (object)
6015 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6016 || EQ (object, Qt))
6017 {
6018 pset_encode_coding_system
6019 (p, complement_process_encoding_system (p->encode_coding_system));
6020 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6021 {
6022 /* The coding system for encoding was changed to raw-text
6023 because we sent a unibyte text previously. Now we are
6024 sending a multibyte text, thus we must encode it by the
6025 original coding system specified for the current process.
6026
6027 Another reason we come here is that the coding system
6028 was just complemented and a new one was returned by
6029 complement_process_encoding_system. */
6030 setup_coding_system (p->encode_coding_system, coding);
6031 Vlast_coding_system_used = p->encode_coding_system;
6032 }
6033 coding->src_multibyte = 1;
6034 }
6035 else
6036 {
6037 coding->src_multibyte = 0;
6038 /* For sending a unibyte text, character code conversion should
6039 not take place but EOL conversion should. So, setup raw-text
6040 or one of the subsidiary if we have not yet done it. */
6041 if (CODING_REQUIRE_ENCODING (coding))
6042 {
6043 if (CODING_REQUIRE_FLUSHING (coding))
6044 {
6045 /* But, before changing the coding, we must flush out data. */
6046 coding->mode |= CODING_MODE_LAST_BLOCK;
6047 send_process (proc, "", 0, Qt);
6048 coding->mode &= CODING_MODE_LAST_BLOCK;
6049 }
6050 setup_coding_system (raw_text_coding_system
6051 (Vlast_coding_system_used),
6052 coding);
6053 coding->src_multibyte = 0;
6054 }
6055 }
6056 coding->dst_multibyte = 0;
6057
6058 if (CODING_REQUIRE_ENCODING (coding))
6059 {
6060 coding->dst_object = Qt;
6061 if (BUFFERP (object))
6062 {
6063 ptrdiff_t from_byte, from, to;
6064 ptrdiff_t save_pt, save_pt_byte;
6065 struct buffer *cur = current_buffer;
6066
6067 set_buffer_internal (XBUFFER (object));
6068 save_pt = PT, save_pt_byte = PT_BYTE;
6069
6070 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6071 from = BYTE_TO_CHAR (from_byte);
6072 to = BYTE_TO_CHAR (from_byte + len);
6073 TEMP_SET_PT_BOTH (from, from_byte);
6074 encode_coding_object (coding, object, from, from_byte,
6075 to, from_byte + len, Qt);
6076 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6077 set_buffer_internal (cur);
6078 }
6079 else if (STRINGP (object))
6080 {
6081 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6082 SBYTES (object), Qt);
6083 }
6084 else
6085 {
6086 coding->dst_object = make_unibyte_string (buf, len);
6087 coding->produced = len;
6088 }
6089
6090 len = coding->produced;
6091 object = coding->dst_object;
6092 buf = SSDATA (object);
6093 }
6094
6095 /* If there is already data in the write_queue, put the new data
6096 in the back of queue. Otherwise, ignore it. */
6097 if (!NILP (p->write_queue))
6098 write_queue_push (p, object, buf, len, 0);
6099
6100 do /* while !NILP (p->write_queue) */
6101 {
6102 ptrdiff_t cur_len = -1;
6103 const char *cur_buf;
6104 Lisp_Object cur_object;
6105
6106 /* If write_queue is empty, ignore it. */
6107 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6108 {
6109 cur_len = len;
6110 cur_buf = buf;
6111 cur_object = object;
6112 }
6113
6114 while (cur_len > 0)
6115 {
6116 /* Send this batch, using one or more write calls. */
6117 ptrdiff_t written = 0;
6118 int outfd = p->outfd;
6119 #ifdef DATAGRAM_SOCKETS
6120 if (DATAGRAM_CHAN_P (outfd))
6121 {
6122 rv = sendto (outfd, cur_buf, cur_len,
6123 0, datagram_address[outfd].sa,
6124 datagram_address[outfd].len);
6125 if (rv >= 0)
6126 written = rv;
6127 else if (errno == EMSGSIZE)
6128 report_file_error ("Sending datagram", proc);
6129 }
6130 else
6131 #endif
6132 {
6133 #ifdef HAVE_GNUTLS
6134 if (p->gnutls_p && p->gnutls_state)
6135 written = emacs_gnutls_write (p, cur_buf, cur_len);
6136 else
6137 #endif
6138 written = emacs_write_sig (outfd, cur_buf, cur_len);
6139 rv = (written ? 0 : -1);
6140 if (p->read_output_delay > 0
6141 && p->adaptive_read_buffering == 1)
6142 {
6143 p->read_output_delay = 0;
6144 process_output_delay_count--;
6145 p->read_output_skip = 0;
6146 }
6147 }
6148
6149 if (rv < 0)
6150 {
6151 if (would_block (errno))
6152 /* Buffer is full. Wait, accepting input;
6153 that may allow the program
6154 to finish doing output and read more. */
6155 {
6156 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6157 /* A gross hack to work around a bug in FreeBSD.
6158 In the following sequence, read(2) returns
6159 bogus data:
6160
6161 write(2) 1022 bytes
6162 write(2) 954 bytes, get EAGAIN
6163 read(2) 1024 bytes in process_read_output
6164 read(2) 11 bytes in process_read_output
6165
6166 That is, read(2) returns more bytes than have
6167 ever been written successfully. The 1033 bytes
6168 read are the 1022 bytes written successfully
6169 after processing (for example with CRs added if
6170 the terminal is set up that way which it is
6171 here). The same bytes will be seen again in a
6172 later read(2), without the CRs. */
6173
6174 if (errno == EAGAIN)
6175 {
6176 int flags = FWRITE;
6177 ioctl (p->outfd, TIOCFLUSH, &flags);
6178 }
6179 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6180
6181 /* Put what we should have written in wait_queue. */
6182 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6183 wait_reading_process_output (0, 20 * 1000 * 1000,
6184 0, 0, Qnil, NULL, 0);
6185 /* Reread queue, to see what is left. */
6186 break;
6187 }
6188 else if (errno == EPIPE)
6189 {
6190 p->raw_status_new = 0;
6191 pset_status (p, list2 (Qexit, make_number (256)));
6192 p->tick = ++process_tick;
6193 deactivate_process (proc);
6194 error ("process %s no longer connected to pipe; closed it",
6195 SDATA (p->name));
6196 }
6197 else
6198 /* This is a real error. */
6199 report_file_error ("Writing to process", proc);
6200 }
6201 cur_buf += written;
6202 cur_len -= written;
6203 }
6204 }
6205 while (!NILP (p->write_queue));
6206 }
6207
6208 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6209 3, 3, 0,
6210 doc: /* Send current contents of region as input to PROCESS.
6211 PROCESS may be a process, a buffer, the name of a process or buffer, or
6212 nil, indicating the current buffer's process.
6213 Called from program, takes three arguments, PROCESS, START and END.
6214 If the region is more than 500 characters long,
6215 it is sent in several bunches. This may happen even for shorter regions.
6216 Output from processes can arrive in between bunches.
6217
6218 If PROCESS is a non-blocking network process that hasn't been fully
6219 set up yet, this function will block until socket setup has completed. */)
6220 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6221 {
6222 Lisp_Object proc = get_process (process);
6223 ptrdiff_t start_byte, end_byte;
6224
6225 validate_region (&start, &end);
6226
6227 start_byte = CHAR_TO_BYTE (XINT (start));
6228 end_byte = CHAR_TO_BYTE (XINT (end));
6229
6230 if (XINT (start) < GPT && XINT (end) > GPT)
6231 move_gap_both (XINT (start), start_byte);
6232
6233 if (NETCONN_P (proc))
6234 wait_while_connecting (proc);
6235
6236 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6237 end_byte - start_byte, Fcurrent_buffer ());
6238
6239 return Qnil;
6240 }
6241
6242 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6243 2, 2, 0,
6244 doc: /* Send PROCESS the contents of STRING as input.
6245 PROCESS may be a process, a buffer, the name of a process or buffer, or
6246 nil, indicating the current buffer's process.
6247 If STRING is more than 500 characters long,
6248 it is sent in several bunches. This may happen even for shorter strings.
6249 Output from processes can arrive in between bunches.
6250
6251 If PROCESS is a non-blocking network process that hasn't been fully
6252 set up yet, this function will block until socket setup has completed. */)
6253 (Lisp_Object process, Lisp_Object string)
6254 {
6255 CHECK_STRING (string);
6256 Lisp_Object proc = get_process (process);
6257 send_process (proc, SSDATA (string),
6258 SBYTES (string), string);
6259 return Qnil;
6260 }
6261 \f
6262 /* Return the foreground process group for the tty/pty that
6263 the process P uses. */
6264 static pid_t
6265 emacs_get_tty_pgrp (struct Lisp_Process *p)
6266 {
6267 pid_t gid = -1;
6268
6269 #ifdef TIOCGPGRP
6270 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6271 {
6272 int fd;
6273 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6274 master side. Try the slave side. */
6275 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6276
6277 if (fd != -1)
6278 {
6279 ioctl (fd, TIOCGPGRP, &gid);
6280 emacs_close (fd);
6281 }
6282 }
6283 #endif /* defined (TIOCGPGRP ) */
6284
6285 return gid;
6286 }
6287
6288 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6289 Sprocess_running_child_p, 0, 1, 0,
6290 doc: /* Return non-nil if PROCESS has given the terminal to a
6291 child. If the operating system does not make it possible to find out,
6292 return t. If we can find out, return the numeric ID of the foreground
6293 process group. */)
6294 (Lisp_Object process)
6295 {
6296 /* Initialize in case ioctl doesn't exist or gives an error,
6297 in a way that will cause returning t. */
6298 Lisp_Object proc = get_process (process);
6299 struct Lisp_Process *p = XPROCESS (proc);
6300
6301 if (!EQ (p->type, Qreal))
6302 error ("Process %s is not a subprocess",
6303 SDATA (p->name));
6304 if (p->infd < 0)
6305 error ("Process %s is not active",
6306 SDATA (p->name));
6307
6308 pid_t gid = emacs_get_tty_pgrp (p);
6309
6310 if (gid == p->pid)
6311 return Qnil;
6312 if (gid != -1)
6313 return make_number (gid);
6314 return Qt;
6315 }
6316 \f
6317 /* Send a signal number SIGNO to PROCESS.
6318 If CURRENT_GROUP is t, that means send to the process group
6319 that currently owns the terminal being used to communicate with PROCESS.
6320 This is used for various commands in shell mode.
6321 If CURRENT_GROUP is lambda, that means send to the process group
6322 that currently owns the terminal, but only if it is NOT the shell itself.
6323
6324 If NOMSG is false, insert signal-announcements into process's buffers
6325 right away.
6326
6327 If we can, we try to signal PROCESS by sending control characters
6328 down the pty. This allows us to signal inferiors who have changed
6329 their uid, for which kill would return an EPERM error. */
6330
6331 static void
6332 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6333 bool nomsg)
6334 {
6335 Lisp_Object proc;
6336 struct Lisp_Process *p;
6337 pid_t gid;
6338 bool no_pgrp = 0;
6339
6340 proc = get_process (process);
6341 p = XPROCESS (proc);
6342
6343 if (!EQ (p->type, Qreal))
6344 error ("Process %s is not a subprocess",
6345 SDATA (p->name));
6346 if (p->infd < 0)
6347 error ("Process %s is not active",
6348 SDATA (p->name));
6349
6350 if (!p->pty_flag)
6351 current_group = Qnil;
6352
6353 /* If we are using pgrps, get a pgrp number and make it negative. */
6354 if (NILP (current_group))
6355 /* Send the signal to the shell's process group. */
6356 gid = p->pid;
6357 else
6358 {
6359 #ifdef SIGNALS_VIA_CHARACTERS
6360 /* If possible, send signals to the entire pgrp
6361 by sending an input character to it. */
6362
6363 struct termios t;
6364 cc_t *sig_char = NULL;
6365
6366 tcgetattr (p->infd, &t);
6367
6368 switch (signo)
6369 {
6370 case SIGINT:
6371 sig_char = &t.c_cc[VINTR];
6372 break;
6373
6374 case SIGQUIT:
6375 sig_char = &t.c_cc[VQUIT];
6376 break;
6377
6378 case SIGTSTP:
6379 #ifdef VSWTCH
6380 sig_char = &t.c_cc[VSWTCH];
6381 #else
6382 sig_char = &t.c_cc[VSUSP];
6383 #endif
6384 break;
6385 }
6386
6387 if (sig_char && *sig_char != CDISABLE)
6388 {
6389 send_process (proc, (char *) sig_char, 1, Qnil);
6390 return;
6391 }
6392 /* If we can't send the signal with a character,
6393 fall through and send it another way. */
6394
6395 /* The code above may fall through if it can't
6396 handle the signal. */
6397 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6398
6399 #ifdef TIOCGPGRP
6400 /* Get the current pgrp using the tty itself, if we have that.
6401 Otherwise, use the pty to get the pgrp.
6402 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6403 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6404 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6405 His patch indicates that if TIOCGPGRP returns an error, then
6406 we should just assume that p->pid is also the process group id. */
6407
6408 gid = emacs_get_tty_pgrp (p);
6409
6410 if (gid == -1)
6411 /* If we can't get the information, assume
6412 the shell owns the tty. */
6413 gid = p->pid;
6414
6415 /* It is not clear whether anything really can set GID to -1.
6416 Perhaps on some system one of those ioctls can or could do so.
6417 Or perhaps this is vestigial. */
6418 if (gid == -1)
6419 no_pgrp = 1;
6420 #else /* ! defined (TIOCGPGRP) */
6421 /* Can't select pgrps on this system, so we know that
6422 the child itself heads the pgrp. */
6423 gid = p->pid;
6424 #endif /* ! defined (TIOCGPGRP) */
6425
6426 /* If current_group is lambda, and the shell owns the terminal,
6427 don't send any signal. */
6428 if (EQ (current_group, Qlambda) && gid == p->pid)
6429 return;
6430 }
6431
6432 #ifdef SIGCONT
6433 if (signo == SIGCONT)
6434 {
6435 p->raw_status_new = 0;
6436 pset_status (p, Qrun);
6437 p->tick = ++process_tick;
6438 if (!nomsg)
6439 {
6440 status_notify (NULL, NULL);
6441 redisplay_preserve_echo_area (13);
6442 }
6443 }
6444 #endif
6445
6446 #ifdef TIOCSIGSEND
6447 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6448 We don't know whether the bug is fixed in later HP-UX versions. */
6449 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6450 return;
6451 #endif
6452
6453 /* If we don't have process groups, send the signal to the immediate
6454 subprocess. That isn't really right, but it's better than any
6455 obvious alternative. */
6456 pid_t pid = no_pgrp ? gid : - gid;
6457
6458 /* Do not kill an already-reaped process, as that could kill an
6459 innocent bystander that happens to have the same process ID. */
6460 sigset_t oldset;
6461 block_child_signal (&oldset);
6462 if (p->alive)
6463 kill (pid, signo);
6464 unblock_child_signal (&oldset);
6465 }
6466
6467 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6468 doc: /* Interrupt process PROCESS.
6469 PROCESS may be a process, a buffer, or the name of a process or buffer.
6470 No arg or nil means current buffer's process.
6471 Second arg CURRENT-GROUP non-nil means send signal to
6472 the current process-group of the process's controlling terminal
6473 rather than to the process's own process group.
6474 If the process is a shell, this means interrupt current subjob
6475 rather than the shell.
6476
6477 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6478 don't send the signal. */)
6479 (Lisp_Object process, Lisp_Object current_group)
6480 {
6481 process_send_signal (process, SIGINT, current_group, 0);
6482 return process;
6483 }
6484
6485 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6486 doc: /* Kill process PROCESS. May be process or name of one.
6487 See function `interrupt-process' for more details on usage. */)
6488 (Lisp_Object process, Lisp_Object current_group)
6489 {
6490 process_send_signal (process, SIGKILL, current_group, 0);
6491 return process;
6492 }
6493
6494 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6495 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6496 See function `interrupt-process' for more details on usage. */)
6497 (Lisp_Object process, Lisp_Object current_group)
6498 {
6499 process_send_signal (process, SIGQUIT, current_group, 0);
6500 return process;
6501 }
6502
6503 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6504 doc: /* Stop process PROCESS. May be process or name of one.
6505 See function `interrupt-process' for more details on usage.
6506 If PROCESS is a network or serial process, inhibit handling of incoming
6507 traffic. */)
6508 (Lisp_Object process, Lisp_Object current_group)
6509 {
6510 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6511 || PIPECONN_P (process)))
6512 {
6513 struct Lisp_Process *p;
6514
6515 p = XPROCESS (process);
6516 if (NILP (p->command)
6517 && p->infd >= 0)
6518 {
6519 FD_CLR (p->infd, &input_wait_mask);
6520 FD_CLR (p->infd, &non_keyboard_wait_mask);
6521 }
6522 pset_command (p, Qt);
6523 return process;
6524 }
6525 #ifndef SIGTSTP
6526 error ("No SIGTSTP support");
6527 #else
6528 process_send_signal (process, SIGTSTP, current_group, 0);
6529 #endif
6530 return process;
6531 }
6532
6533 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6534 doc: /* Continue process PROCESS. May be process or name of one.
6535 See function `interrupt-process' for more details on usage.
6536 If PROCESS is a network or serial process, resume handling of incoming
6537 traffic. */)
6538 (Lisp_Object process, Lisp_Object current_group)
6539 {
6540 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6541 || PIPECONN_P (process)))
6542 {
6543 struct Lisp_Process *p;
6544
6545 p = XPROCESS (process);
6546 if (EQ (p->command, Qt)
6547 && p->infd >= 0
6548 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6549 {
6550 FD_SET (p->infd, &input_wait_mask);
6551 FD_SET (p->infd, &non_keyboard_wait_mask);
6552 #ifdef WINDOWSNT
6553 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6554 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6555 #else /* not WINDOWSNT */
6556 tcflush (p->infd, TCIFLUSH);
6557 #endif /* not WINDOWSNT */
6558 }
6559 pset_command (p, Qnil);
6560 return process;
6561 }
6562 #ifdef SIGCONT
6563 process_send_signal (process, SIGCONT, current_group, 0);
6564 #else
6565 error ("No SIGCONT support");
6566 #endif
6567 return process;
6568 }
6569
6570 /* Return the integer value of the signal whose abbreviation is ABBR,
6571 or a negative number if there is no such signal. */
6572 static int
6573 abbr_to_signal (char const *name)
6574 {
6575 int i, signo;
6576 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6577
6578 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6579 name += 3;
6580
6581 for (i = 0; i < sizeof sigbuf; i++)
6582 {
6583 sigbuf[i] = c_toupper (name[i]);
6584 if (! sigbuf[i])
6585 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6586 }
6587
6588 return -1;
6589 }
6590
6591 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6592 2, 2, "sProcess (name or number): \nnSignal code: ",
6593 doc: /* Send PROCESS the signal with code SIGCODE.
6594 PROCESS may also be a number specifying the process id of the
6595 process to signal; in this case, the process need not be a child of
6596 this Emacs.
6597 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6598 (Lisp_Object process, Lisp_Object sigcode)
6599 {
6600 pid_t pid;
6601 int signo;
6602
6603 if (STRINGP (process))
6604 {
6605 Lisp_Object tem = Fget_process (process);
6606 if (NILP (tem))
6607 {
6608 Lisp_Object process_number
6609 = string_to_number (SSDATA (process), 10, 1);
6610 if (NUMBERP (process_number))
6611 tem = process_number;
6612 }
6613 process = tem;
6614 }
6615 else if (!NUMBERP (process))
6616 process = get_process (process);
6617
6618 if (NILP (process))
6619 return process;
6620
6621 if (NUMBERP (process))
6622 CONS_TO_INTEGER (process, pid_t, pid);
6623 else
6624 {
6625 CHECK_PROCESS (process);
6626 pid = XPROCESS (process)->pid;
6627 if (pid <= 0)
6628 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6629 }
6630
6631 if (INTEGERP (sigcode))
6632 {
6633 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6634 signo = XINT (sigcode);
6635 }
6636 else
6637 {
6638 char *name;
6639
6640 CHECK_SYMBOL (sigcode);
6641 name = SSDATA (SYMBOL_NAME (sigcode));
6642
6643 signo = abbr_to_signal (name);
6644 if (signo < 0)
6645 error ("Undefined signal name %s", name);
6646 }
6647
6648 return make_number (kill (pid, signo));
6649 }
6650
6651 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6652 doc: /* Make PROCESS see end-of-file in its input.
6653 EOF comes after any text already sent to it.
6654 PROCESS may be a process, a buffer, the name of a process or buffer, or
6655 nil, indicating the current buffer's process.
6656 If PROCESS is a network connection, or is a process communicating
6657 through a pipe (as opposed to a pty), then you cannot send any more
6658 text to PROCESS after you call this function.
6659 If PROCESS is a serial process, wait until all output written to the
6660 process has been transmitted to the serial port. */)
6661 (Lisp_Object process)
6662 {
6663 Lisp_Object proc;
6664 struct coding_system *coding = NULL;
6665 int outfd;
6666
6667 proc = get_process (process);
6668
6669 if (NETCONN_P (proc))
6670 wait_while_connecting (proc);
6671
6672 if (DATAGRAM_CONN_P (proc))
6673 return process;
6674
6675
6676 outfd = XPROCESS (proc)->outfd;
6677 if (outfd >= 0)
6678 coding = proc_encode_coding_system[outfd];
6679
6680 /* Make sure the process is really alive. */
6681 if (XPROCESS (proc)->raw_status_new)
6682 update_status (XPROCESS (proc));
6683 if (! EQ (XPROCESS (proc)->status, Qrun))
6684 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6685
6686 if (coding && CODING_REQUIRE_FLUSHING (coding))
6687 {
6688 coding->mode |= CODING_MODE_LAST_BLOCK;
6689 send_process (proc, "", 0, Qnil);
6690 }
6691
6692 if (XPROCESS (proc)->pty_flag)
6693 send_process (proc, "\004", 1, Qnil);
6694 else if (EQ (XPROCESS (proc)->type, Qserial))
6695 {
6696 #ifndef WINDOWSNT
6697 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6698 report_file_error ("Failed tcdrain", Qnil);
6699 #endif /* not WINDOWSNT */
6700 /* Do nothing on Windows because writes are blocking. */
6701 }
6702 else
6703 {
6704 struct Lisp_Process *p = XPROCESS (proc);
6705 int old_outfd = p->outfd;
6706 int new_outfd;
6707
6708 #ifdef HAVE_SHUTDOWN
6709 /* If this is a network connection, or socketpair is used
6710 for communication with the subprocess, call shutdown to cause EOF.
6711 (In some old system, shutdown to socketpair doesn't work.
6712 Then we just can't win.) */
6713 if (0 <= old_outfd
6714 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6715 shutdown (old_outfd, 1);
6716 #endif
6717 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6718 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6719 if (new_outfd < 0)
6720 report_file_error ("Opening null device", Qnil);
6721 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6722 p->outfd = new_outfd;
6723
6724 if (!proc_encode_coding_system[new_outfd])
6725 proc_encode_coding_system[new_outfd]
6726 = xmalloc (sizeof (struct coding_system));
6727 if (old_outfd >= 0)
6728 {
6729 *proc_encode_coding_system[new_outfd]
6730 = *proc_encode_coding_system[old_outfd];
6731 memset (proc_encode_coding_system[old_outfd], 0,
6732 sizeof (struct coding_system));
6733 }
6734 else
6735 setup_coding_system (p->encode_coding_system,
6736 proc_encode_coding_system[new_outfd]);
6737 }
6738 return process;
6739 }
6740 \f
6741 /* The main Emacs thread records child processes in three places:
6742
6743 - Vprocess_alist, for asynchronous subprocesses, which are child
6744 processes visible to Lisp.
6745
6746 - deleted_pid_list, for child processes invisible to Lisp,
6747 typically because of delete-process. These are recorded so that
6748 the processes can be reaped when they exit, so that the operating
6749 system's process table is not cluttered by zombies.
6750
6751 - the local variable PID in Fcall_process, call_process_cleanup and
6752 call_process_kill, for synchronous subprocesses.
6753 record_unwind_protect is used to make sure this process is not
6754 forgotten: if the user interrupts call-process and the child
6755 process refuses to exit immediately even with two C-g's,
6756 call_process_kill adds PID's contents to deleted_pid_list before
6757 returning.
6758
6759 The main Emacs thread invokes waitpid only on child processes that
6760 it creates and that have not been reaped. This avoid races on
6761 platforms such as GTK, where other threads create their own
6762 subprocesses which the main thread should not reap. For example,
6763 if the main thread attempted to reap an already-reaped child, it
6764 might inadvertently reap a GTK-created process that happened to
6765 have the same process ID. */
6766
6767 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6768 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6769 keep track of its own children. GNUstep is similar. */
6770
6771 static void dummy_handler (int sig) {}
6772 static signal_handler_t volatile lib_child_handler;
6773
6774 /* Handle a SIGCHLD signal by looking for known child processes of
6775 Emacs whose status have changed. For each one found, record its
6776 new status.
6777
6778 All we do is change the status; we do not run sentinels or print
6779 notifications. That is saved for the next time keyboard input is
6780 done, in order to avoid timing errors.
6781
6782 ** WARNING: this can be called during garbage collection.
6783 Therefore, it must not be fooled by the presence of mark bits in
6784 Lisp objects.
6785
6786 ** USG WARNING: Although it is not obvious from the documentation
6787 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6788 signal() before executing at least one wait(), otherwise the
6789 handler will be called again, resulting in an infinite loop. The
6790 relevant portion of the documentation reads "SIGCLD signals will be
6791 queued and the signal-catching function will be continually
6792 reentered until the queue is empty". Invoking signal() causes the
6793 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6794 Inc.
6795
6796 ** Malloc WARNING: This should never call malloc either directly or
6797 indirectly; if it does, that is a bug. */
6798
6799 static void
6800 handle_child_signal (int sig)
6801 {
6802 Lisp_Object tail, proc;
6803
6804 /* Find the process that signaled us, and record its status. */
6805
6806 /* The process can have been deleted by Fdelete_process, or have
6807 been started asynchronously by Fcall_process. */
6808 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6809 {
6810 bool all_pids_are_fixnums
6811 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6812 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6813 Lisp_Object head = XCAR (tail);
6814 Lisp_Object xpid;
6815 if (! CONSP (head))
6816 continue;
6817 xpid = XCAR (head);
6818 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6819 {
6820 pid_t deleted_pid;
6821 if (INTEGERP (xpid))
6822 deleted_pid = XINT (xpid);
6823 else
6824 deleted_pid = XFLOAT_DATA (xpid);
6825 if (child_status_changed (deleted_pid, 0, 0))
6826 {
6827 if (STRINGP (XCDR (head)))
6828 unlink (SSDATA (XCDR (head)));
6829 XSETCAR (tail, Qnil);
6830 }
6831 }
6832 }
6833
6834 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6835 FOR_EACH_PROCESS (tail, proc)
6836 {
6837 struct Lisp_Process *p = XPROCESS (proc);
6838 int status;
6839
6840 if (p->alive
6841 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6842 {
6843 /* Change the status of the process that was found. */
6844 p->tick = ++process_tick;
6845 p->raw_status = status;
6846 p->raw_status_new = 1;
6847
6848 /* If process has terminated, stop waiting for its output. */
6849 if (WIFSIGNALED (status) || WIFEXITED (status))
6850 {
6851 bool clear_desc_flag = 0;
6852 p->alive = 0;
6853 if (p->infd >= 0)
6854 clear_desc_flag = 1;
6855
6856 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6857 if (clear_desc_flag)
6858 {
6859 FD_CLR (p->infd, &input_wait_mask);
6860 FD_CLR (p->infd, &non_keyboard_wait_mask);
6861 }
6862 }
6863 }
6864 }
6865
6866 lib_child_handler (sig);
6867 #ifdef NS_IMPL_GNUSTEP
6868 /* NSTask in GNUstep sets its child handler each time it is called.
6869 So we must re-set ours. */
6870 catch_child_signal ();
6871 #endif
6872 }
6873
6874 static void
6875 deliver_child_signal (int sig)
6876 {
6877 deliver_process_signal (sig, handle_child_signal);
6878 }
6879 \f
6880
6881 static Lisp_Object
6882 exec_sentinel_error_handler (Lisp_Object error_val)
6883 {
6884 cmd_error_internal (error_val, "error in process sentinel: ");
6885 Vinhibit_quit = Qt;
6886 update_echo_area ();
6887 Fsleep_for (make_number (2), Qnil);
6888 return Qt;
6889 }
6890
6891 static void
6892 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6893 {
6894 Lisp_Object sentinel, odeactivate;
6895 struct Lisp_Process *p = XPROCESS (proc);
6896 ptrdiff_t count = SPECPDL_INDEX ();
6897 bool outer_running_asynch_code = running_asynch_code;
6898 int waiting = waiting_for_user_input_p;
6899
6900 if (inhibit_sentinels)
6901 return;
6902
6903 odeactivate = Vdeactivate_mark;
6904 #if 0
6905 Lisp_Object obuffer, okeymap;
6906 XSETBUFFER (obuffer, current_buffer);
6907 okeymap = BVAR (current_buffer, keymap);
6908 #endif
6909
6910 /* There's no good reason to let sentinels change the current
6911 buffer, and many callers of accept-process-output, sit-for, and
6912 friends don't expect current-buffer to be changed from under them. */
6913 record_unwind_current_buffer ();
6914
6915 sentinel = p->sentinel;
6916
6917 /* Inhibit quit so that random quits don't screw up a running filter. */
6918 specbind (Qinhibit_quit, Qt);
6919 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6920
6921 /* In case we get recursively called,
6922 and we already saved the match data nonrecursively,
6923 save the same match data in safely recursive fashion. */
6924 if (outer_running_asynch_code)
6925 {
6926 Lisp_Object tem;
6927 tem = Fmatch_data (Qnil, Qnil, Qnil);
6928 restore_search_regs ();
6929 record_unwind_save_match_data ();
6930 Fset_match_data (tem, Qt);
6931 }
6932
6933 /* For speed, if a search happens within this code,
6934 save the match data in a special nonrecursive fashion. */
6935 running_asynch_code = 1;
6936
6937 internal_condition_case_1 (read_process_output_call,
6938 list3 (sentinel, proc, reason),
6939 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6940 exec_sentinel_error_handler);
6941
6942 /* If we saved the match data nonrecursively, restore it now. */
6943 restore_search_regs ();
6944 running_asynch_code = outer_running_asynch_code;
6945
6946 Vdeactivate_mark = odeactivate;
6947
6948 /* Restore waiting_for_user_input_p as it was
6949 when we were called, in case the filter clobbered it. */
6950 waiting_for_user_input_p = waiting;
6951
6952 #if 0
6953 if (! EQ (Fcurrent_buffer (), obuffer)
6954 || ! EQ (current_buffer->keymap, okeymap))
6955 #endif
6956 /* But do it only if the caller is actually going to read events.
6957 Otherwise there's no need to make him wake up, and it could
6958 cause trouble (for example it would make sit_for return). */
6959 if (waiting_for_user_input_p == -1)
6960 record_asynch_buffer_change ();
6961
6962 unbind_to (count, Qnil);
6963 }
6964
6965 /* Report all recent events of a change in process status
6966 (either run the sentinel or output a message).
6967 This is usually done while Emacs is waiting for keyboard input
6968 but can be done at other times.
6969
6970 Return positive if any input was received from WAIT_PROC (or from
6971 any process if WAIT_PROC is null), zero if input was attempted but
6972 none received, and negative if we didn't even try. */
6973
6974 static int
6975 status_notify (struct Lisp_Process *deleting_process,
6976 struct Lisp_Process *wait_proc)
6977 {
6978 Lisp_Object proc;
6979 Lisp_Object tail, msg;
6980 int got_some_output = -1;
6981
6982 tail = Qnil;
6983 msg = Qnil;
6984
6985 /* Set this now, so that if new processes are created by sentinels
6986 that we run, we get called again to handle their status changes. */
6987 update_tick = process_tick;
6988
6989 FOR_EACH_PROCESS (tail, proc)
6990 {
6991 Lisp_Object symbol;
6992 register struct Lisp_Process *p = XPROCESS (proc);
6993
6994 if (p->tick != p->update_tick)
6995 {
6996 p->update_tick = p->tick;
6997
6998 /* If process is still active, read any output that remains. */
6999 while (! EQ (p->filter, Qt)
7000 && ! EQ (p->status, Qconnect)
7001 && ! EQ (p->status, Qlisten)
7002 /* Network or serial process not stopped: */
7003 && ! EQ (p->command, Qt)
7004 && p->infd >= 0
7005 && p != deleting_process)
7006 {
7007 int nread = read_process_output (proc, p->infd);
7008 if ((!wait_proc || wait_proc == XPROCESS (proc))
7009 && got_some_output < nread)
7010 got_some_output = nread;
7011 if (nread <= 0)
7012 break;
7013 }
7014
7015 /* Get the text to use for the message. */
7016 if (p->raw_status_new)
7017 update_status (p);
7018 msg = status_message (p);
7019
7020 /* If process is terminated, deactivate it or delete it. */
7021 symbol = p->status;
7022 if (CONSP (p->status))
7023 symbol = XCAR (p->status);
7024
7025 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7026 || EQ (symbol, Qclosed))
7027 {
7028 if (delete_exited_processes)
7029 remove_process (proc);
7030 else
7031 deactivate_process (proc);
7032 }
7033
7034 /* The actions above may have further incremented p->tick.
7035 So set p->update_tick again so that an error in the sentinel will
7036 not cause this code to be run again. */
7037 p->update_tick = p->tick;
7038 /* Now output the message suitably. */
7039 exec_sentinel (proc, msg);
7040 if (BUFFERP (p->buffer))
7041 /* In case it uses %s in mode-line-format. */
7042 bset_update_mode_line (XBUFFER (p->buffer));
7043 }
7044 } /* end for */
7045
7046 return got_some_output;
7047 }
7048
7049 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7050 Sinternal_default_process_sentinel, 2, 2, 0,
7051 doc: /* Function used as default sentinel for processes.
7052 This inserts a status message into the process's buffer, if there is one. */)
7053 (Lisp_Object proc, Lisp_Object msg)
7054 {
7055 Lisp_Object buffer, symbol;
7056 struct Lisp_Process *p;
7057 CHECK_PROCESS (proc);
7058 p = XPROCESS (proc);
7059 buffer = p->buffer;
7060 symbol = p->status;
7061 if (CONSP (symbol))
7062 symbol = XCAR (symbol);
7063
7064 if (!EQ (symbol, Qrun) && !NILP (buffer))
7065 {
7066 Lisp_Object tem;
7067 struct buffer *old = current_buffer;
7068 ptrdiff_t opoint, opoint_byte;
7069 ptrdiff_t before, before_byte;
7070
7071 /* Avoid error if buffer is deleted
7072 (probably that's why the process is dead, too). */
7073 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7074 return Qnil;
7075 Fset_buffer (buffer);
7076
7077 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7078 msg = (code_convert_string_norecord
7079 (msg, Vlocale_coding_system, 1));
7080
7081 opoint = PT;
7082 opoint_byte = PT_BYTE;
7083 /* Insert new output into buffer
7084 at the current end-of-output marker,
7085 thus preserving logical ordering of input and output. */
7086 if (XMARKER (p->mark)->buffer)
7087 Fgoto_char (p->mark);
7088 else
7089 SET_PT_BOTH (ZV, ZV_BYTE);
7090
7091 before = PT;
7092 before_byte = PT_BYTE;
7093
7094 tem = BVAR (current_buffer, read_only);
7095 bset_read_only (current_buffer, Qnil);
7096 insert_string ("\nProcess ");
7097 { /* FIXME: temporary kludge. */
7098 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7099 insert_string (" ");
7100 Finsert (1, &msg);
7101 bset_read_only (current_buffer, tem);
7102 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7103
7104 if (opoint >= before)
7105 SET_PT_BOTH (opoint + (PT - before),
7106 opoint_byte + (PT_BYTE - before_byte));
7107 else
7108 SET_PT_BOTH (opoint, opoint_byte);
7109
7110 set_buffer_internal (old);
7111 }
7112 return Qnil;
7113 }
7114
7115 \f
7116 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7117 Sset_process_coding_system, 1, 3, 0,
7118 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7119 DECODING will be used to decode subprocess output and ENCODING to
7120 encode subprocess input. */)
7121 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7122 {
7123 CHECK_PROCESS (process);
7124
7125 struct Lisp_Process *p = XPROCESS (process);
7126
7127 Fcheck_coding_system (decoding);
7128 Fcheck_coding_system (encoding);
7129 encoding = coding_inherit_eol_type (encoding, Qnil);
7130 pset_decode_coding_system (p, decoding);
7131 pset_encode_coding_system (p, encoding);
7132
7133 /* If the sockets haven't been set up yet, the final setup part of
7134 this will be called asynchronously. */
7135 if (p->infd < 0 || p->outfd < 0)
7136 return Qnil;
7137
7138 setup_process_coding_systems (process);
7139
7140 return Qnil;
7141 }
7142
7143 DEFUN ("process-coding-system",
7144 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7145 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7146 (register Lisp_Object process)
7147 {
7148 CHECK_PROCESS (process);
7149 return Fcons (XPROCESS (process)->decode_coding_system,
7150 XPROCESS (process)->encode_coding_system);
7151 }
7152
7153 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7154 Sset_process_filter_multibyte, 2, 2, 0,
7155 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7156 If FLAG is non-nil, the filter is given multibyte strings.
7157 If FLAG is nil, the filter is given unibyte strings. In this case,
7158 all character code conversion except for end-of-line conversion is
7159 suppressed. */)
7160 (Lisp_Object process, Lisp_Object flag)
7161 {
7162 CHECK_PROCESS (process);
7163
7164 struct Lisp_Process *p = XPROCESS (process);
7165 if (NILP (flag))
7166 pset_decode_coding_system
7167 (p, raw_text_coding_system (p->decode_coding_system));
7168
7169 /* If the sockets haven't been set up yet, the final setup part of
7170 this will be called asynchronously. */
7171 if (p->infd < 0 || p->outfd < 0)
7172 return Qnil;
7173
7174 setup_process_coding_systems (process);
7175
7176 return Qnil;
7177 }
7178
7179 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7180 Sprocess_filter_multibyte_p, 1, 1, 0,
7181 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7182 (Lisp_Object process)
7183 {
7184 CHECK_PROCESS (process);
7185 struct Lisp_Process *p = XPROCESS (process);
7186 if (p->infd < 0)
7187 return Qnil;
7188 struct coding_system *coding = proc_decode_coding_system[p->infd];
7189 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7190 }
7191
7192
7193 \f
7194
7195 # ifdef HAVE_GPM
7196
7197 void
7198 add_gpm_wait_descriptor (int desc)
7199 {
7200 add_keyboard_wait_descriptor (desc);
7201 }
7202
7203 void
7204 delete_gpm_wait_descriptor (int desc)
7205 {
7206 delete_keyboard_wait_descriptor (desc);
7207 }
7208
7209 # endif
7210
7211 # ifdef USABLE_SIGIO
7212
7213 /* Return true if *MASK has a bit set
7214 that corresponds to one of the keyboard input descriptors. */
7215
7216 static bool
7217 keyboard_bit_set (fd_set *mask)
7218 {
7219 int fd;
7220
7221 for (fd = 0; fd <= max_input_desc; fd++)
7222 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7223 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7224 return 1;
7225
7226 return 0;
7227 }
7228 # endif
7229
7230 #else /* not subprocesses */
7231
7232 /* Defined in msdos.c. */
7233 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7234 struct timespec *, void *);
7235
7236 /* Implementation of wait_reading_process_output, assuming that there
7237 are no subprocesses. Used only by the MS-DOS build.
7238
7239 Wait for timeout to elapse and/or keyboard input to be available.
7240
7241 TIME_LIMIT is:
7242 timeout in seconds
7243 If negative, gobble data immediately available but don't wait for any.
7244
7245 NSECS is:
7246 an additional duration to wait, measured in nanoseconds
7247 If TIME_LIMIT is zero, then:
7248 If NSECS == 0, there is no limit.
7249 If NSECS > 0, the timeout consists of NSECS only.
7250 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7251
7252 READ_KBD is:
7253 0 to ignore keyboard input, or
7254 1 to return when input is available, or
7255 -1 means caller will actually read the input, so don't throw to
7256 the quit handler.
7257
7258 see full version for other parameters. We know that wait_proc will
7259 always be NULL, since `subprocesses' isn't defined.
7260
7261 DO_DISPLAY means redisplay should be done to show subprocess
7262 output that arrives.
7263
7264 Return -1 signifying we got no output and did not try. */
7265
7266 int
7267 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7268 bool do_display,
7269 Lisp_Object wait_for_cell,
7270 struct Lisp_Process *wait_proc, int just_wait_proc)
7271 {
7272 register int nfds;
7273 struct timespec end_time, timeout;
7274 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7275
7276 if (TYPE_MAXIMUM (time_t) < time_limit)
7277 time_limit = TYPE_MAXIMUM (time_t);
7278
7279 if (time_limit < 0 || nsecs < 0)
7280 wait = MINIMUM;
7281 else if (time_limit > 0 || nsecs > 0)
7282 {
7283 wait = TIMEOUT;
7284 end_time = timespec_add (current_timespec (),
7285 make_timespec (time_limit, nsecs));
7286 }
7287 else
7288 wait = INFINITY;
7289
7290 /* Turn off periodic alarms (in case they are in use)
7291 and then turn off any other atimers,
7292 because the select emulator uses alarms. */
7293 stop_polling ();
7294 turn_on_atimers (0);
7295
7296 while (1)
7297 {
7298 bool timeout_reduced_for_timers = false;
7299 fd_set waitchannels;
7300 int xerrno;
7301
7302 /* If calling from keyboard input, do not quit
7303 since we want to return C-g as an input character.
7304 Otherwise, do pending quit if requested. */
7305 if (read_kbd >= 0)
7306 QUIT;
7307
7308 /* Exit now if the cell we're waiting for became non-nil. */
7309 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7310 break;
7311
7312 /* Compute time from now till when time limit is up. */
7313 /* Exit if already run out. */
7314 if (wait == TIMEOUT)
7315 {
7316 struct timespec now = current_timespec ();
7317 if (timespec_cmp (end_time, now) <= 0)
7318 break;
7319 timeout = timespec_sub (end_time, now);
7320 }
7321 else
7322 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7323
7324 /* If our caller will not immediately handle keyboard events,
7325 run timer events directly.
7326 (Callers that will immediately read keyboard events
7327 call timer_delay on their own.) */
7328 if (NILP (wait_for_cell))
7329 {
7330 struct timespec timer_delay;
7331
7332 do
7333 {
7334 unsigned old_timers_run = timers_run;
7335 timer_delay = timer_check ();
7336 if (timers_run != old_timers_run && do_display)
7337 /* We must retry, since a timer may have requeued itself
7338 and that could alter the time delay. */
7339 redisplay_preserve_echo_area (14);
7340 else
7341 break;
7342 }
7343 while (!detect_input_pending ());
7344
7345 /* If there is unread keyboard input, also return. */
7346 if (read_kbd != 0
7347 && requeued_events_pending_p ())
7348 break;
7349
7350 if (timespec_valid_p (timer_delay))
7351 {
7352 if (timespec_cmp (timer_delay, timeout) < 0)
7353 {
7354 timeout = timer_delay;
7355 timeout_reduced_for_timers = true;
7356 }
7357 }
7358 }
7359
7360 /* Cause C-g and alarm signals to take immediate action,
7361 and cause input available signals to zero out timeout. */
7362 if (read_kbd < 0)
7363 set_waiting_for_input (&timeout);
7364
7365 /* If a frame has been newly mapped and needs updating,
7366 reprocess its display stuff. */
7367 if (frame_garbaged && do_display)
7368 {
7369 clear_waiting_for_input ();
7370 redisplay_preserve_echo_area (15);
7371 if (read_kbd < 0)
7372 set_waiting_for_input (&timeout);
7373 }
7374
7375 /* Wait till there is something to do. */
7376 FD_ZERO (&waitchannels);
7377 if (read_kbd && detect_input_pending ())
7378 nfds = 0;
7379 else
7380 {
7381 if (read_kbd || !NILP (wait_for_cell))
7382 FD_SET (0, &waitchannels);
7383 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7384 }
7385
7386 xerrno = errno;
7387
7388 /* Make C-g and alarm signals set flags again. */
7389 clear_waiting_for_input ();
7390
7391 /* If we woke up due to SIGWINCH, actually change size now. */
7392 do_pending_window_change (0);
7393
7394 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7395 /* We waited the full specified time, so return now. */
7396 break;
7397
7398 if (nfds == -1)
7399 {
7400 /* If the system call was interrupted, then go around the
7401 loop again. */
7402 if (xerrno == EINTR)
7403 FD_ZERO (&waitchannels);
7404 else
7405 report_file_errno ("Failed select", Qnil, xerrno);
7406 }
7407
7408 /* Check for keyboard input. */
7409
7410 if (read_kbd
7411 && detect_input_pending_run_timers (do_display))
7412 {
7413 swallow_events (do_display);
7414 if (detect_input_pending_run_timers (do_display))
7415 break;
7416 }
7417
7418 /* If there is unread keyboard input, also return. */
7419 if (read_kbd
7420 && requeued_events_pending_p ())
7421 break;
7422
7423 /* If wait_for_cell. check for keyboard input
7424 but don't run any timers.
7425 ??? (It seems wrong to me to check for keyboard
7426 input at all when wait_for_cell, but the code
7427 has been this way since July 1994.
7428 Try changing this after version 19.31.) */
7429 if (! NILP (wait_for_cell)
7430 && detect_input_pending ())
7431 {
7432 swallow_events (do_display);
7433 if (detect_input_pending ())
7434 break;
7435 }
7436
7437 /* Exit now if the cell we're waiting for became non-nil. */
7438 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7439 break;
7440 }
7441
7442 start_polling ();
7443
7444 return -1;
7445 }
7446
7447 #endif /* not subprocesses */
7448
7449 /* The following functions are needed even if async subprocesses are
7450 not supported. Some of them are no-op stubs in that case. */
7451
7452 #ifdef HAVE_TIMERFD
7453
7454 /* Add FD, which is a descriptor returned by timerfd_create,
7455 to the set of non-keyboard input descriptors. */
7456
7457 void
7458 add_timer_wait_descriptor (int fd)
7459 {
7460 FD_SET (fd, &input_wait_mask);
7461 FD_SET (fd, &non_keyboard_wait_mask);
7462 FD_SET (fd, &non_process_wait_mask);
7463 fd_callback_info[fd].func = timerfd_callback;
7464 fd_callback_info[fd].data = NULL;
7465 fd_callback_info[fd].condition |= FOR_READ;
7466 if (fd > max_input_desc)
7467 max_input_desc = fd;
7468 }
7469
7470 #endif /* HAVE_TIMERFD */
7471
7472 /* If program file NAME starts with /: for quoting a magic
7473 name, remove that, preserving the multibyteness of NAME. */
7474
7475 Lisp_Object
7476 remove_slash_colon (Lisp_Object name)
7477 {
7478 return
7479 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7480 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7481 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7482 : name);
7483 }
7484
7485 /* Add DESC to the set of keyboard input descriptors. */
7486
7487 void
7488 add_keyboard_wait_descriptor (int desc)
7489 {
7490 #ifdef subprocesses /* Actually means "not MSDOS". */
7491 FD_SET (desc, &input_wait_mask);
7492 FD_SET (desc, &non_process_wait_mask);
7493 if (desc > max_input_desc)
7494 max_input_desc = desc;
7495 #endif
7496 }
7497
7498 /* From now on, do not expect DESC to give keyboard input. */
7499
7500 void
7501 delete_keyboard_wait_descriptor (int desc)
7502 {
7503 #ifdef subprocesses
7504 FD_CLR (desc, &input_wait_mask);
7505 FD_CLR (desc, &non_process_wait_mask);
7506 delete_input_desc (desc);
7507 #endif
7508 }
7509
7510 /* Setup coding systems of PROCESS. */
7511
7512 void
7513 setup_process_coding_systems (Lisp_Object process)
7514 {
7515 #ifdef subprocesses
7516 struct Lisp_Process *p = XPROCESS (process);
7517 int inch = p->infd;
7518 int outch = p->outfd;
7519 Lisp_Object coding_system;
7520
7521 if (inch < 0 || outch < 0)
7522 return;
7523
7524 if (!proc_decode_coding_system[inch])
7525 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7526 coding_system = p->decode_coding_system;
7527 if (EQ (p->filter, Qinternal_default_process_filter)
7528 && BUFFERP (p->buffer))
7529 {
7530 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7531 coding_system = raw_text_coding_system (coding_system);
7532 }
7533 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7534
7535 if (!proc_encode_coding_system[outch])
7536 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7537 setup_coding_system (p->encode_coding_system,
7538 proc_encode_coding_system[outch]);
7539 #endif
7540 }
7541
7542 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7543 doc: /* Return the (or a) live process associated with BUFFER.
7544 BUFFER may be a buffer or the name of one.
7545 Return nil if all processes associated with BUFFER have been
7546 deleted or killed. */)
7547 (register Lisp_Object buffer)
7548 {
7549 #ifdef subprocesses
7550 register Lisp_Object buf, tail, proc;
7551
7552 if (NILP (buffer)) return Qnil;
7553 buf = Fget_buffer (buffer);
7554 if (NILP (buf)) return Qnil;
7555
7556 FOR_EACH_PROCESS (tail, proc)
7557 if (EQ (XPROCESS (proc)->buffer, buf))
7558 return proc;
7559 #endif /* subprocesses */
7560 return Qnil;
7561 }
7562
7563 DEFUN ("process-inherit-coding-system-flag",
7564 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7565 1, 1, 0,
7566 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7567 If this flag is t, `buffer-file-coding-system' of the buffer
7568 associated with PROCESS will inherit the coding system used to decode
7569 the process output. */)
7570 (register Lisp_Object process)
7571 {
7572 #ifdef subprocesses
7573 CHECK_PROCESS (process);
7574 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7575 #else
7576 /* Ignore the argument and return the value of
7577 inherit-process-coding-system. */
7578 return inherit_process_coding_system ? Qt : Qnil;
7579 #endif
7580 }
7581
7582 /* Kill all processes associated with `buffer'.
7583 If `buffer' is nil, kill all processes. */
7584
7585 void
7586 kill_buffer_processes (Lisp_Object buffer)
7587 {
7588 #ifdef subprocesses
7589 Lisp_Object tail, proc;
7590
7591 FOR_EACH_PROCESS (tail, proc)
7592 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7593 {
7594 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7595 Fdelete_process (proc);
7596 else if (XPROCESS (proc)->infd >= 0)
7597 process_send_signal (proc, SIGHUP, Qnil, 1);
7598 }
7599 #else /* subprocesses */
7600 /* Since we have no subprocesses, this does nothing. */
7601 #endif /* subprocesses */
7602 }
7603
7604 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7605 Swaiting_for_user_input_p, 0, 0, 0,
7606 doc: /* Return non-nil if Emacs is waiting for input from the user.
7607 This is intended for use by asynchronous process output filters and sentinels. */)
7608 (void)
7609 {
7610 #ifdef subprocesses
7611 return (waiting_for_user_input_p ? Qt : Qnil);
7612 #else
7613 return Qnil;
7614 #endif
7615 }
7616
7617 /* Stop reading input from keyboard sources. */
7618
7619 void
7620 hold_keyboard_input (void)
7621 {
7622 kbd_is_on_hold = 1;
7623 }
7624
7625 /* Resume reading input from keyboard sources. */
7626
7627 void
7628 unhold_keyboard_input (void)
7629 {
7630 kbd_is_on_hold = 0;
7631 }
7632
7633 /* Return true if keyboard input is on hold, zero otherwise. */
7634
7635 bool
7636 kbd_on_hold_p (void)
7637 {
7638 return kbd_is_on_hold;
7639 }
7640
7641 \f
7642 /* Enumeration of and access to system processes a-la ps(1). */
7643
7644 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7645 0, 0, 0,
7646 doc: /* Return a list of numerical process IDs of all running processes.
7647 If this functionality is unsupported, return nil.
7648
7649 See `process-attributes' for getting attributes of a process given its ID. */)
7650 (void)
7651 {
7652 return list_system_processes ();
7653 }
7654
7655 DEFUN ("process-attributes", Fprocess_attributes,
7656 Sprocess_attributes, 1, 1, 0,
7657 doc: /* Return attributes of the process given by its PID, a number.
7658
7659 Value is an alist where each element is a cons cell of the form
7660
7661 (KEY . VALUE)
7662
7663 If this functionality is unsupported, the value is nil.
7664
7665 See `list-system-processes' for getting a list of all process IDs.
7666
7667 The KEYs of the attributes that this function may return are listed
7668 below, together with the type of the associated VALUE (in parentheses).
7669 Not all platforms support all of these attributes; unsupported
7670 attributes will not appear in the returned alist.
7671 Unless explicitly indicated otherwise, numbers can have either
7672 integer or floating point values.
7673
7674 euid -- Effective user User ID of the process (number)
7675 user -- User name corresponding to euid (string)
7676 egid -- Effective user Group ID of the process (number)
7677 group -- Group name corresponding to egid (string)
7678 comm -- Command name (executable name only) (string)
7679 state -- Process state code, such as "S", "R", or "T" (string)
7680 ppid -- Parent process ID (number)
7681 pgrp -- Process group ID (number)
7682 sess -- Session ID, i.e. process ID of session leader (number)
7683 ttname -- Controlling tty name (string)
7684 tpgid -- ID of foreground process group on the process's tty (number)
7685 minflt -- number of minor page faults (number)
7686 majflt -- number of major page faults (number)
7687 cminflt -- cumulative number of minor page faults (number)
7688 cmajflt -- cumulative number of major page faults (number)
7689 utime -- user time used by the process, in (current-time) format,
7690 which is a list of integers (HIGH LOW USEC PSEC)
7691 stime -- system time used by the process (current-time)
7692 time -- sum of utime and stime (current-time)
7693 cutime -- user time used by the process and its children (current-time)
7694 cstime -- system time used by the process and its children (current-time)
7695 ctime -- sum of cutime and cstime (current-time)
7696 pri -- priority of the process (number)
7697 nice -- nice value of the process (number)
7698 thcount -- process thread count (number)
7699 start -- time the process started (current-time)
7700 vsize -- virtual memory size of the process in KB's (number)
7701 rss -- resident set size of the process in KB's (number)
7702 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7703 pcpu -- percents of CPU time used by the process (floating-point number)
7704 pmem -- percents of total physical memory used by process's resident set
7705 (floating-point number)
7706 args -- command line which invoked the process (string). */)
7707 ( Lisp_Object pid)
7708 {
7709 return system_process_attributes (pid);
7710 }
7711
7712 #ifdef subprocesses
7713 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7714 Invoke this after init_process_emacs, and after glib and/or GNUstep
7715 futz with the SIGCHLD handler, but before Emacs forks any children.
7716 This function's caller should block SIGCHLD. */
7717
7718 void
7719 catch_child_signal (void)
7720 {
7721 struct sigaction action, old_action;
7722 sigset_t oldset;
7723 emacs_sigaction_init (&action, deliver_child_signal);
7724 block_child_signal (&oldset);
7725 sigaction (SIGCHLD, &action, &old_action);
7726 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7727 || ! (old_action.sa_flags & SA_SIGINFO));
7728
7729 if (old_action.sa_handler != deliver_child_signal)
7730 lib_child_handler
7731 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7732 ? dummy_handler
7733 : old_action.sa_handler);
7734 unblock_child_signal (&oldset);
7735 }
7736 #endif /* subprocesses */
7737
7738 \f
7739 /* This is not called "init_process" because that is the name of a
7740 Mach system call, so it would cause problems on Darwin systems. */
7741 void
7742 init_process_emacs (int sockfd)
7743 {
7744 #ifdef subprocesses
7745 int i;
7746
7747 inhibit_sentinels = 0;
7748
7749 #ifndef CANNOT_DUMP
7750 if (! noninteractive || initialized)
7751 #endif
7752 {
7753 #if defined HAVE_GLIB && !defined WINDOWSNT
7754 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7755 this should always fail, but is enough to initialize glib's
7756 private SIGCHLD handler, allowing catch_child_signal to copy
7757 it into lib_child_handler. */
7758 g_source_unref (g_child_watch_source_new (getpid ()));
7759 #endif
7760 catch_child_signal ();
7761 }
7762
7763 FD_ZERO (&input_wait_mask);
7764 FD_ZERO (&non_keyboard_wait_mask);
7765 FD_ZERO (&non_process_wait_mask);
7766 FD_ZERO (&write_mask);
7767 max_process_desc = max_input_desc = -1;
7768 external_sock_fd = sockfd;
7769 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7770
7771 FD_ZERO (&connect_wait_mask);
7772 num_pending_connects = 0;
7773
7774 process_output_delay_count = 0;
7775 process_output_skip = 0;
7776
7777 /* Don't do this, it caused infinite select loops. The display
7778 method should call add_keyboard_wait_descriptor on stdin if it
7779 needs that. */
7780 #if 0
7781 FD_SET (0, &input_wait_mask);
7782 #endif
7783
7784 Vprocess_alist = Qnil;
7785 deleted_pid_list = Qnil;
7786 for (i = 0; i < FD_SETSIZE; i++)
7787 {
7788 chan_process[i] = Qnil;
7789 proc_buffered_char[i] = -1;
7790 }
7791 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7792 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7793 #ifdef DATAGRAM_SOCKETS
7794 memset (datagram_address, 0, sizeof datagram_address);
7795 #endif
7796
7797 #if defined (DARWIN_OS)
7798 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7799 processes. As such, we only change the default value. */
7800 if (initialized)
7801 {
7802 char const *release = (STRINGP (Voperating_system_release)
7803 ? SSDATA (Voperating_system_release)
7804 : 0);
7805 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7806 Vprocess_connection_type = Qnil;
7807 }
7808 }
7809 #endif
7810 #endif /* subprocesses */
7811 kbd_is_on_hold = 0;
7812 }
7813
7814 void
7815 syms_of_process (void)
7816 {
7817 #ifdef subprocesses
7818
7819 DEFSYM (Qprocessp, "processp");
7820 DEFSYM (Qrun, "run");
7821 DEFSYM (Qstop, "stop");
7822 DEFSYM (Qsignal, "signal");
7823
7824 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7825 here again. */
7826
7827 DEFSYM (Qopen, "open");
7828 DEFSYM (Qclosed, "closed");
7829 DEFSYM (Qconnect, "connect");
7830 DEFSYM (Qfailed, "failed");
7831 DEFSYM (Qlisten, "listen");
7832 DEFSYM (Qlocal, "local");
7833 DEFSYM (Qipv4, "ipv4");
7834 #ifdef AF_INET6
7835 DEFSYM (Qipv6, "ipv6");
7836 #endif
7837 DEFSYM (Qdatagram, "datagram");
7838 DEFSYM (Qseqpacket, "seqpacket");
7839
7840 DEFSYM (QCport, ":port");
7841 DEFSYM (QCspeed, ":speed");
7842 DEFSYM (QCprocess, ":process");
7843
7844 DEFSYM (QCbytesize, ":bytesize");
7845 DEFSYM (QCstopbits, ":stopbits");
7846 DEFSYM (QCparity, ":parity");
7847 DEFSYM (Qodd, "odd");
7848 DEFSYM (Qeven, "even");
7849 DEFSYM (QCflowcontrol, ":flowcontrol");
7850 DEFSYM (Qhw, "hw");
7851 DEFSYM (Qsw, "sw");
7852 DEFSYM (QCsummary, ":summary");
7853
7854 DEFSYM (Qreal, "real");
7855 DEFSYM (Qnetwork, "network");
7856 DEFSYM (Qserial, "serial");
7857 DEFSYM (Qpipe, "pipe");
7858 DEFSYM (QCbuffer, ":buffer");
7859 DEFSYM (QChost, ":host");
7860 DEFSYM (QCservice, ":service");
7861 DEFSYM (QClocal, ":local");
7862 DEFSYM (QCremote, ":remote");
7863 DEFSYM (QCcoding, ":coding");
7864 DEFSYM (QCserver, ":server");
7865 DEFSYM (QCnowait, ":nowait");
7866 DEFSYM (QCsentinel, ":sentinel");
7867 DEFSYM (QCuse_external_socket, ":use-external-socket");
7868 DEFSYM (QCtls_parameters, ":tls-parameters");
7869 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
7870 DEFSYM (QClog, ":log");
7871 DEFSYM (QCnoquery, ":noquery");
7872 DEFSYM (QCstop, ":stop");
7873 DEFSYM (QCplist, ":plist");
7874 DEFSYM (QCcommand, ":command");
7875 DEFSYM (QCconnection_type, ":connection-type");
7876 DEFSYM (QCstderr, ":stderr");
7877 DEFSYM (Qpty, "pty");
7878 DEFSYM (Qpipe, "pipe");
7879
7880 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7881
7882 staticpro (&Vprocess_alist);
7883 staticpro (&deleted_pid_list);
7884
7885 #endif /* subprocesses */
7886
7887 DEFSYM (QCname, ":name");
7888 DEFSYM (QCtype, ":type");
7889
7890 DEFSYM (Qeuid, "euid");
7891 DEFSYM (Qegid, "egid");
7892 DEFSYM (Quser, "user");
7893 DEFSYM (Qgroup, "group");
7894 DEFSYM (Qcomm, "comm");
7895 DEFSYM (Qstate, "state");
7896 DEFSYM (Qppid, "ppid");
7897 DEFSYM (Qpgrp, "pgrp");
7898 DEFSYM (Qsess, "sess");
7899 DEFSYM (Qttname, "ttname");
7900 DEFSYM (Qtpgid, "tpgid");
7901 DEFSYM (Qminflt, "minflt");
7902 DEFSYM (Qmajflt, "majflt");
7903 DEFSYM (Qcminflt, "cminflt");
7904 DEFSYM (Qcmajflt, "cmajflt");
7905 DEFSYM (Qutime, "utime");
7906 DEFSYM (Qstime, "stime");
7907 DEFSYM (Qtime, "time");
7908 DEFSYM (Qcutime, "cutime");
7909 DEFSYM (Qcstime, "cstime");
7910 DEFSYM (Qctime, "ctime");
7911 #ifdef subprocesses
7912 DEFSYM (Qinternal_default_process_sentinel,
7913 "internal-default-process-sentinel");
7914 DEFSYM (Qinternal_default_process_filter,
7915 "internal-default-process-filter");
7916 #endif
7917 DEFSYM (Qpri, "pri");
7918 DEFSYM (Qnice, "nice");
7919 DEFSYM (Qthcount, "thcount");
7920 DEFSYM (Qstart, "start");
7921 DEFSYM (Qvsize, "vsize");
7922 DEFSYM (Qrss, "rss");
7923 DEFSYM (Qetime, "etime");
7924 DEFSYM (Qpcpu, "pcpu");
7925 DEFSYM (Qpmem, "pmem");
7926 DEFSYM (Qargs, "args");
7927
7928 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7929 doc: /* Non-nil means delete processes immediately when they exit.
7930 A value of nil means don't delete them until `list-processes' is run. */);
7931
7932 delete_exited_processes = 1;
7933
7934 #ifdef subprocesses
7935 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7936 doc: /* Control type of device used to communicate with subprocesses.
7937 Values are nil to use a pipe, or t or `pty' to use a pty.
7938 The value has no effect if the system has no ptys or if all ptys are busy:
7939 then a pipe is used in any case.
7940 The value takes effect when `start-process' is called. */);
7941 Vprocess_connection_type = Qt;
7942
7943 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7944 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7945 On some systems, when Emacs reads the output from a subprocess, the output data
7946 is read in very small blocks, potentially resulting in very poor performance.
7947 This behavior can be remedied to some extent by setting this variable to a
7948 non-nil value, as it will automatically delay reading from such processes, to
7949 allow them to produce more output before Emacs tries to read it.
7950 If the value is t, the delay is reset after each write to the process; any other
7951 non-nil value means that the delay is not reset on write.
7952 The variable takes effect when `start-process' is called. */);
7953 Vprocess_adaptive_read_buffering = Qt;
7954
7955 defsubr (&Sprocessp);
7956 defsubr (&Sget_process);
7957 defsubr (&Sdelete_process);
7958 defsubr (&Sprocess_status);
7959 defsubr (&Sprocess_exit_status);
7960 defsubr (&Sprocess_id);
7961 defsubr (&Sprocess_name);
7962 defsubr (&Sprocess_tty_name);
7963 defsubr (&Sprocess_command);
7964 defsubr (&Sset_process_buffer);
7965 defsubr (&Sprocess_buffer);
7966 defsubr (&Sprocess_mark);
7967 defsubr (&Sset_process_filter);
7968 defsubr (&Sprocess_filter);
7969 defsubr (&Sset_process_sentinel);
7970 defsubr (&Sprocess_sentinel);
7971 defsubr (&Sset_process_window_size);
7972 defsubr (&Sset_process_inherit_coding_system_flag);
7973 defsubr (&Sset_process_query_on_exit_flag);
7974 defsubr (&Sprocess_query_on_exit_flag);
7975 defsubr (&Sprocess_contact);
7976 defsubr (&Sprocess_plist);
7977 defsubr (&Sset_process_plist);
7978 defsubr (&Sprocess_list);
7979 defsubr (&Smake_process);
7980 defsubr (&Smake_pipe_process);
7981 defsubr (&Sserial_process_configure);
7982 defsubr (&Smake_serial_process);
7983 defsubr (&Sset_network_process_option);
7984 defsubr (&Smake_network_process);
7985 defsubr (&Sformat_network_address);
7986 defsubr (&Snetwork_interface_list);
7987 defsubr (&Snetwork_interface_info);
7988 #ifdef DATAGRAM_SOCKETS
7989 defsubr (&Sprocess_datagram_address);
7990 defsubr (&Sset_process_datagram_address);
7991 #endif
7992 defsubr (&Saccept_process_output);
7993 defsubr (&Sprocess_send_region);
7994 defsubr (&Sprocess_send_string);
7995 defsubr (&Sinterrupt_process);
7996 defsubr (&Skill_process);
7997 defsubr (&Squit_process);
7998 defsubr (&Sstop_process);
7999 defsubr (&Scontinue_process);
8000 defsubr (&Sprocess_running_child_p);
8001 defsubr (&Sprocess_send_eof);
8002 defsubr (&Ssignal_process);
8003 defsubr (&Swaiting_for_user_input_p);
8004 defsubr (&Sprocess_type);
8005 defsubr (&Sinternal_default_process_sentinel);
8006 defsubr (&Sinternal_default_process_filter);
8007 defsubr (&Sset_process_coding_system);
8008 defsubr (&Sprocess_coding_system);
8009 defsubr (&Sset_process_filter_multibyte);
8010 defsubr (&Sprocess_filter_multibyte_p);
8011
8012 {
8013 Lisp_Object subfeatures = Qnil;
8014 const struct socket_options *sopt;
8015
8016 #define ADD_SUBFEATURE(key, val) \
8017 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8018
8019 ADD_SUBFEATURE (QCnowait, Qt);
8020 #ifdef DATAGRAM_SOCKETS
8021 ADD_SUBFEATURE (QCtype, Qdatagram);
8022 #endif
8023 #ifdef HAVE_SEQPACKET
8024 ADD_SUBFEATURE (QCtype, Qseqpacket);
8025 #endif
8026 #ifdef HAVE_LOCAL_SOCKETS
8027 ADD_SUBFEATURE (QCfamily, Qlocal);
8028 #endif
8029 ADD_SUBFEATURE (QCfamily, Qipv4);
8030 #ifdef AF_INET6
8031 ADD_SUBFEATURE (QCfamily, Qipv6);
8032 #endif
8033 #ifdef HAVE_GETSOCKNAME
8034 ADD_SUBFEATURE (QCservice, Qt);
8035 #endif
8036 ADD_SUBFEATURE (QCserver, Qt);
8037
8038 for (sopt = socket_options; sopt->name; sopt++)
8039 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8040
8041 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8042 }
8043
8044 #endif /* subprocesses */
8045
8046 defsubr (&Sget_buffer_process);
8047 defsubr (&Sprocess_inherit_coding_system_flag);
8048 defsubr (&Slist_system_processes);
8049 defsubr (&Sprocess_attributes);
8050 }