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