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