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