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