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