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