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