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