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