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