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