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