]> code.delx.au - gnu-emacs/blob - src/process.c
Omit unnecessary \ before paren in C docstrings
[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 && ((d->condition & FOR_READ
5036 && FD_ISSET (channel, &Available))
5037 || (d->condition & FOR_WRITE
5038 && FD_ISSET (channel, &write_mask))))
5039 d->func (channel, d->data);
5040 }
5041
5042 for (channel = 0; channel <= max_process_desc; channel++)
5043 {
5044 if (FD_ISSET (channel, &Available)
5045 && FD_ISSET (channel, &non_keyboard_wait_mask)
5046 && !FD_ISSET (channel, &non_process_wait_mask))
5047 {
5048 int nread;
5049
5050 /* If waiting for this channel, arrange to return as
5051 soon as no more input to be processed. No more
5052 waiting. */
5053 proc = chan_process[channel];
5054 if (NILP (proc))
5055 continue;
5056
5057 /* If this is a server stream socket, accept connection. */
5058 if (EQ (XPROCESS (proc)->status, Qlisten))
5059 {
5060 server_accept_connection (proc, channel);
5061 continue;
5062 }
5063
5064 /* Read data from the process, starting with our
5065 buffered-ahead character if we have one. */
5066
5067 nread = read_process_output (proc, channel);
5068 if ((!wait_proc || wait_proc == XPROCESS (proc))
5069 && got_some_output < nread)
5070 got_some_output = nread;
5071 if (nread > 0)
5072 {
5073 /* Vacuum up any leftovers without waiting. */
5074 if (wait_proc == XPROCESS (proc))
5075 wait = MINIMUM;
5076 /* Since read_process_output can run a filter,
5077 which can call accept-process-output,
5078 don't try to read from any other processes
5079 before doing the select again. */
5080 FD_ZERO (&Available);
5081
5082 if (do_display)
5083 redisplay_preserve_echo_area (12);
5084 }
5085 #ifdef EWOULDBLOCK
5086 else if (nread == -1 && errno == EWOULDBLOCK)
5087 ;
5088 #endif
5089 else if (nread == -1 && errno == EAGAIN)
5090 ;
5091 #ifdef WINDOWSNT
5092 /* FIXME: Is this special case still needed? */
5093 /* Note that we cannot distinguish between no input
5094 available now and a closed pipe.
5095 With luck, a closed pipe will be accompanied by
5096 subprocess termination and SIGCHLD. */
5097 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5098 && !PIPECONN_P (proc))
5099 ;
5100 #endif
5101 #ifdef HAVE_PTYS
5102 /* On some OSs with ptys, when the process on one end of
5103 a pty exits, the other end gets an error reading with
5104 errno = EIO instead of getting an EOF (0 bytes read).
5105 Therefore, if we get an error reading and errno =
5106 EIO, just continue, because the child process has
5107 exited and should clean itself up soon (e.g. when we
5108 get a SIGCHLD). */
5109 else if (nread == -1 && errno == EIO)
5110 {
5111 struct Lisp_Process *p = XPROCESS (proc);
5112
5113 /* Clear the descriptor now, so we only raise the
5114 signal once. */
5115 FD_CLR (channel, &input_wait_mask);
5116 FD_CLR (channel, &non_keyboard_wait_mask);
5117
5118 if (p->pid == -2)
5119 {
5120 /* If the EIO occurs on a pty, the SIGCHLD handler's
5121 waitpid call will not find the process object to
5122 delete. Do it here. */
5123 p->tick = ++process_tick;
5124 pset_status (p, Qfailed);
5125 }
5126 }
5127 #endif /* HAVE_PTYS */
5128 /* If we can detect process termination, don't consider the
5129 process gone just because its pipe is closed. */
5130 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5131 && !PIPECONN_P (proc))
5132 ;
5133 else if (nread == 0 && PIPECONN_P (proc))
5134 {
5135 /* Preserve status of processes already terminated. */
5136 XPROCESS (proc)->tick = ++process_tick;
5137 deactivate_process (proc);
5138 if (EQ (XPROCESS (proc)->status, Qrun))
5139 pset_status (XPROCESS (proc),
5140 list2 (Qexit, make_number (0)));
5141 }
5142 else
5143 {
5144 /* Preserve status of processes already terminated. */
5145 XPROCESS (proc)->tick = ++process_tick;
5146 deactivate_process (proc);
5147 if (XPROCESS (proc)->raw_status_new)
5148 update_status (XPROCESS (proc));
5149 if (EQ (XPROCESS (proc)->status, Qrun))
5150 pset_status (XPROCESS (proc),
5151 list2 (Qexit, make_number (256)));
5152 }
5153 }
5154 #ifdef NON_BLOCKING_CONNECT
5155 if (FD_ISSET (channel, &Writeok)
5156 && FD_ISSET (channel, &connect_wait_mask))
5157 {
5158 struct Lisp_Process *p;
5159
5160 FD_CLR (channel, &connect_wait_mask);
5161 FD_CLR (channel, &write_mask);
5162 if (--num_pending_connects < 0)
5163 emacs_abort ();
5164
5165 proc = chan_process[channel];
5166 if (NILP (proc))
5167 continue;
5168
5169 p = XPROCESS (proc);
5170
5171 #ifdef GNU_LINUX
5172 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5173 So only use it on systems where it is known to work. */
5174 {
5175 socklen_t xlen = sizeof (xerrno);
5176 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5177 xerrno = errno;
5178 }
5179 #else
5180 {
5181 struct sockaddr pname;
5182 socklen_t pnamelen = sizeof (pname);
5183
5184 /* If connection failed, getpeername will fail. */
5185 xerrno = 0;
5186 if (getpeername (channel, &pname, &pnamelen) < 0)
5187 {
5188 /* Obtain connect failure code through error slippage. */
5189 char dummy;
5190 xerrno = errno;
5191 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5192 xerrno = errno;
5193 }
5194 }
5195 #endif
5196 if (xerrno)
5197 {
5198 p->tick = ++process_tick;
5199 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5200 deactivate_process (proc);
5201 }
5202 else
5203 {
5204 pset_status (p, Qrun);
5205 /* Execute the sentinel here. If we had relied on
5206 status_notify to do it later, it will read input
5207 from the process before calling the sentinel. */
5208 exec_sentinel (proc, build_string ("open\n"));
5209 if (0 <= p->infd && !EQ (p->filter, Qt)
5210 && !EQ (p->command, Qt))
5211 {
5212 FD_SET (p->infd, &input_wait_mask);
5213 FD_SET (p->infd, &non_keyboard_wait_mask);
5214 }
5215 }
5216 }
5217 #endif /* NON_BLOCKING_CONNECT */
5218 } /* End for each file descriptor. */
5219 } /* End while exit conditions not met. */
5220
5221 unbind_to (count, Qnil);
5222
5223 /* If calling from keyboard input, do not quit
5224 since we want to return C-g as an input character.
5225 Otherwise, do pending quit if requested. */
5226 if (read_kbd >= 0)
5227 {
5228 /* Prevent input_pending from remaining set if we quit. */
5229 clear_input_pending ();
5230 QUIT;
5231 }
5232
5233 return got_some_output;
5234 }
5235 \f
5236 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5237
5238 static Lisp_Object
5239 read_process_output_call (Lisp_Object fun_and_args)
5240 {
5241 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5242 }
5243
5244 static Lisp_Object
5245 read_process_output_error_handler (Lisp_Object error_val)
5246 {
5247 cmd_error_internal (error_val, "error in process filter: ");
5248 Vinhibit_quit = Qt;
5249 update_echo_area ();
5250 Fsleep_for (make_number (2), Qnil);
5251 return Qt;
5252 }
5253
5254 static void
5255 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5256 ssize_t nbytes,
5257 struct coding_system *coding);
5258
5259 /* Read pending output from the process channel,
5260 starting with our buffered-ahead character if we have one.
5261 Yield number of decoded characters read.
5262
5263 This function reads at most 4096 characters.
5264 If you want to read all available subprocess output,
5265 you must call it repeatedly until it returns zero.
5266
5267 The characters read are decoded according to PROC's coding-system
5268 for decoding. */
5269
5270 static int
5271 read_process_output (Lisp_Object proc, int channel)
5272 {
5273 ssize_t nbytes;
5274 struct Lisp_Process *p = XPROCESS (proc);
5275 struct coding_system *coding = proc_decode_coding_system[channel];
5276 int carryover = p->decoding_carryover;
5277 enum { readmax = 4096 };
5278 ptrdiff_t count = SPECPDL_INDEX ();
5279 Lisp_Object odeactivate;
5280 char chars[sizeof coding->carryover + readmax];
5281
5282 if (carryover)
5283 /* See the comment above. */
5284 memcpy (chars, SDATA (p->decoding_buf), carryover);
5285
5286 #ifdef DATAGRAM_SOCKETS
5287 /* We have a working select, so proc_buffered_char is always -1. */
5288 if (DATAGRAM_CHAN_P (channel))
5289 {
5290 socklen_t len = datagram_address[channel].len;
5291 nbytes = recvfrom (channel, chars + carryover, readmax,
5292 0, datagram_address[channel].sa, &len);
5293 }
5294 else
5295 #endif
5296 {
5297 bool buffered = proc_buffered_char[channel] >= 0;
5298 if (buffered)
5299 {
5300 chars[carryover] = proc_buffered_char[channel];
5301 proc_buffered_char[channel] = -1;
5302 }
5303 #ifdef HAVE_GNUTLS
5304 if (p->gnutls_p && p->gnutls_state)
5305 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5306 readmax - buffered);
5307 else
5308 #endif
5309 nbytes = emacs_read (channel, chars + carryover + buffered,
5310 readmax - buffered);
5311 if (nbytes > 0 && p->adaptive_read_buffering)
5312 {
5313 int delay = p->read_output_delay;
5314 if (nbytes < 256)
5315 {
5316 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5317 {
5318 if (delay == 0)
5319 process_output_delay_count++;
5320 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5321 }
5322 }
5323 else if (delay > 0 && nbytes == readmax - buffered)
5324 {
5325 delay -= READ_OUTPUT_DELAY_INCREMENT;
5326 if (delay == 0)
5327 process_output_delay_count--;
5328 }
5329 p->read_output_delay = delay;
5330 if (delay)
5331 {
5332 p->read_output_skip = 1;
5333 process_output_skip = 1;
5334 }
5335 }
5336 nbytes += buffered;
5337 nbytes += buffered && nbytes <= 0;
5338 }
5339
5340 p->decoding_carryover = 0;
5341
5342 /* At this point, NBYTES holds number of bytes just received
5343 (including the one in proc_buffered_char[channel]). */
5344 if (nbytes <= 0)
5345 {
5346 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5347 return nbytes;
5348 coding->mode |= CODING_MODE_LAST_BLOCK;
5349 }
5350
5351 /* Now set NBYTES how many bytes we must decode. */
5352 nbytes += carryover;
5353
5354 odeactivate = Vdeactivate_mark;
5355 /* There's no good reason to let process filters change the current
5356 buffer, and many callers of accept-process-output, sit-for, and
5357 friends don't expect current-buffer to be changed from under them. */
5358 record_unwind_current_buffer ();
5359
5360 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5361
5362 /* Handling the process output should not deactivate the mark. */
5363 Vdeactivate_mark = odeactivate;
5364
5365 unbind_to (count, Qnil);
5366 return nbytes;
5367 }
5368
5369 static void
5370 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5371 ssize_t nbytes,
5372 struct coding_system *coding)
5373 {
5374 Lisp_Object outstream = p->filter;
5375 Lisp_Object text;
5376 bool outer_running_asynch_code = running_asynch_code;
5377 int waiting = waiting_for_user_input_p;
5378
5379 #if 0
5380 Lisp_Object obuffer, okeymap;
5381 XSETBUFFER (obuffer, current_buffer);
5382 okeymap = BVAR (current_buffer, keymap);
5383 #endif
5384
5385 /* We inhibit quit here instead of just catching it so that
5386 hitting ^G when a filter happens to be running won't screw
5387 it up. */
5388 specbind (Qinhibit_quit, Qt);
5389 specbind (Qlast_nonmenu_event, Qt);
5390
5391 /* In case we get recursively called,
5392 and we already saved the match data nonrecursively,
5393 save the same match data in safely recursive fashion. */
5394 if (outer_running_asynch_code)
5395 {
5396 Lisp_Object tem;
5397 /* Don't clobber the CURRENT match data, either! */
5398 tem = Fmatch_data (Qnil, Qnil, Qnil);
5399 restore_search_regs ();
5400 record_unwind_save_match_data ();
5401 Fset_match_data (tem, Qt);
5402 }
5403
5404 /* For speed, if a search happens within this code,
5405 save the match data in a special nonrecursive fashion. */
5406 running_asynch_code = 1;
5407
5408 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5409 text = coding->dst_object;
5410 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5411 /* A new coding system might be found. */
5412 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5413 {
5414 pset_decode_coding_system (p, Vlast_coding_system_used);
5415
5416 /* Don't call setup_coding_system for
5417 proc_decode_coding_system[channel] here. It is done in
5418 detect_coding called via decode_coding above. */
5419
5420 /* If a coding system for encoding is not yet decided, we set
5421 it as the same as coding-system for decoding.
5422
5423 But, before doing that we must check if
5424 proc_encode_coding_system[p->outfd] surely points to a
5425 valid memory because p->outfd will be changed once EOF is
5426 sent to the process. */
5427 if (NILP (p->encode_coding_system) && p->outfd >= 0
5428 && proc_encode_coding_system[p->outfd])
5429 {
5430 pset_encode_coding_system
5431 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5432 setup_coding_system (p->encode_coding_system,
5433 proc_encode_coding_system[p->outfd]);
5434 }
5435 }
5436
5437 if (coding->carryover_bytes > 0)
5438 {
5439 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5440 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5441 memcpy (SDATA (p->decoding_buf), coding->carryover,
5442 coding->carryover_bytes);
5443 p->decoding_carryover = coding->carryover_bytes;
5444 }
5445 if (SBYTES (text) > 0)
5446 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5447 sometimes it's simply wrong to wrap (e.g. when called from
5448 accept-process-output). */
5449 internal_condition_case_1 (read_process_output_call,
5450 list3 (outstream, make_lisp_proc (p), text),
5451 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5452 read_process_output_error_handler);
5453
5454 /* If we saved the match data nonrecursively, restore it now. */
5455 restore_search_regs ();
5456 running_asynch_code = outer_running_asynch_code;
5457
5458 /* Restore waiting_for_user_input_p as it was
5459 when we were called, in case the filter clobbered it. */
5460 waiting_for_user_input_p = waiting;
5461
5462 #if 0 /* Call record_asynch_buffer_change unconditionally,
5463 because we might have changed minor modes or other things
5464 that affect key bindings. */
5465 if (! EQ (Fcurrent_buffer (), obuffer)
5466 || ! EQ (current_buffer->keymap, okeymap))
5467 #endif
5468 /* But do it only if the caller is actually going to read events.
5469 Otherwise there's no need to make him wake up, and it could
5470 cause trouble (for example it would make sit_for return). */
5471 if (waiting_for_user_input_p == -1)
5472 record_asynch_buffer_change ();
5473 }
5474
5475 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5476 Sinternal_default_process_filter, 2, 2, 0,
5477 doc: /* Function used as default process filter.
5478 This inserts the process's output into its buffer, if there is one.
5479 Otherwise it discards the output. */)
5480 (Lisp_Object proc, Lisp_Object text)
5481 {
5482 struct Lisp_Process *p;
5483 ptrdiff_t opoint;
5484
5485 CHECK_PROCESS (proc);
5486 p = XPROCESS (proc);
5487 CHECK_STRING (text);
5488
5489 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5490 {
5491 Lisp_Object old_read_only;
5492 ptrdiff_t old_begv, old_zv;
5493 ptrdiff_t old_begv_byte, old_zv_byte;
5494 ptrdiff_t before, before_byte;
5495 ptrdiff_t opoint_byte;
5496 struct buffer *b;
5497
5498 Fset_buffer (p->buffer);
5499 opoint = PT;
5500 opoint_byte = PT_BYTE;
5501 old_read_only = BVAR (current_buffer, read_only);
5502 old_begv = BEGV;
5503 old_zv = ZV;
5504 old_begv_byte = BEGV_BYTE;
5505 old_zv_byte = ZV_BYTE;
5506
5507 bset_read_only (current_buffer, Qnil);
5508
5509 /* Insert new output into buffer at the current end-of-output
5510 marker, thus preserving logical ordering of input and output. */
5511 if (XMARKER (p->mark)->buffer)
5512 set_point_from_marker (p->mark);
5513 else
5514 SET_PT_BOTH (ZV, ZV_BYTE);
5515 before = PT;
5516 before_byte = PT_BYTE;
5517
5518 /* If the output marker is outside of the visible region, save
5519 the restriction and widen. */
5520 if (! (BEGV <= PT && PT <= ZV))
5521 Fwiden ();
5522
5523 /* Adjust the multibyteness of TEXT to that of the buffer. */
5524 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5525 != ! STRING_MULTIBYTE (text))
5526 text = (STRING_MULTIBYTE (text)
5527 ? Fstring_as_unibyte (text)
5528 : Fstring_to_multibyte (text));
5529 /* Insert before markers in case we are inserting where
5530 the buffer's mark is, and the user's next command is Meta-y. */
5531 insert_from_string_before_markers (text, 0, 0,
5532 SCHARS (text), SBYTES (text), 0);
5533
5534 /* Make sure the process marker's position is valid when the
5535 process buffer is changed in the signal_after_change above.
5536 W3 is known to do that. */
5537 if (BUFFERP (p->buffer)
5538 && (b = XBUFFER (p->buffer), b != current_buffer))
5539 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5540 else
5541 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5542
5543 update_mode_lines = 23;
5544
5545 /* Make sure opoint and the old restrictions
5546 float ahead of any new text just as point would. */
5547 if (opoint >= before)
5548 {
5549 opoint += PT - before;
5550 opoint_byte += PT_BYTE - before_byte;
5551 }
5552 if (old_begv > before)
5553 {
5554 old_begv += PT - before;
5555 old_begv_byte += PT_BYTE - before_byte;
5556 }
5557 if (old_zv >= before)
5558 {
5559 old_zv += PT - before;
5560 old_zv_byte += PT_BYTE - before_byte;
5561 }
5562
5563 /* If the restriction isn't what it should be, set it. */
5564 if (old_begv != BEGV || old_zv != ZV)
5565 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5566
5567 bset_read_only (current_buffer, old_read_only);
5568 SET_PT_BOTH (opoint, opoint_byte);
5569 }
5570 return Qnil;
5571 }
5572 \f
5573 /* Sending data to subprocess. */
5574
5575 /* In send_process, when a write fails temporarily,
5576 wait_reading_process_output is called. It may execute user code,
5577 e.g. timers, that attempts to write new data to the same process.
5578 We must ensure that data is sent in the right order, and not
5579 interspersed half-completed with other writes (Bug#10815). This is
5580 handled by the write_queue element of struct process. It is a list
5581 with each entry having the form
5582
5583 (string . (offset . length))
5584
5585 where STRING is a lisp string, OFFSET is the offset into the
5586 string's byte sequence from which we should begin to send, and
5587 LENGTH is the number of bytes left to send. */
5588
5589 /* Create a new entry in write_queue.
5590 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5591 BUF is a pointer to the string sequence of the input_obj or a C
5592 string in case of Qt or Qnil. */
5593
5594 static void
5595 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5596 const char *buf, ptrdiff_t len, bool front)
5597 {
5598 ptrdiff_t offset;
5599 Lisp_Object entry, obj;
5600
5601 if (STRINGP (input_obj))
5602 {
5603 offset = buf - SSDATA (input_obj);
5604 obj = input_obj;
5605 }
5606 else
5607 {
5608 offset = 0;
5609 obj = make_unibyte_string (buf, len);
5610 }
5611
5612 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5613
5614 if (front)
5615 pset_write_queue (p, Fcons (entry, p->write_queue));
5616 else
5617 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5618 }
5619
5620 /* Remove the first element in the write_queue of process P, put its
5621 contents in OBJ, BUF and LEN, and return true. If the
5622 write_queue is empty, return false. */
5623
5624 static bool
5625 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5626 const char **buf, ptrdiff_t *len)
5627 {
5628 Lisp_Object entry, offset_length;
5629 ptrdiff_t offset;
5630
5631 if (NILP (p->write_queue))
5632 return 0;
5633
5634 entry = XCAR (p->write_queue);
5635 pset_write_queue (p, XCDR (p->write_queue));
5636
5637 *obj = XCAR (entry);
5638 offset_length = XCDR (entry);
5639
5640 *len = XINT (XCDR (offset_length));
5641 offset = XINT (XCAR (offset_length));
5642 *buf = SSDATA (*obj) + offset;
5643
5644 return 1;
5645 }
5646
5647 /* Send some data to process PROC.
5648 BUF is the beginning of the data; LEN is the number of characters.
5649 OBJECT is the Lisp object that the data comes from. If OBJECT is
5650 nil or t, it means that the data comes from C string.
5651
5652 If OBJECT is not nil, the data is encoded by PROC's coding-system
5653 for encoding before it is sent.
5654
5655 This function can evaluate Lisp code and can garbage collect. */
5656
5657 static void
5658 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5659 Lisp_Object object)
5660 {
5661 struct Lisp_Process *p = XPROCESS (proc);
5662 ssize_t rv;
5663 struct coding_system *coding;
5664
5665 if (p->raw_status_new)
5666 update_status (p);
5667 if (! EQ (p->status, Qrun))
5668 error ("Process %s not running", SDATA (p->name));
5669 if (p->outfd < 0)
5670 error ("Output file descriptor of %s is closed", SDATA (p->name));
5671
5672 coding = proc_encode_coding_system[p->outfd];
5673 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5674
5675 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5676 || (BUFFERP (object)
5677 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5678 || EQ (object, Qt))
5679 {
5680 pset_encode_coding_system
5681 (p, complement_process_encoding_system (p->encode_coding_system));
5682 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5683 {
5684 /* The coding system for encoding was changed to raw-text
5685 because we sent a unibyte text previously. Now we are
5686 sending a multibyte text, thus we must encode it by the
5687 original coding system specified for the current process.
5688
5689 Another reason we come here is that the coding system
5690 was just complemented and a new one was returned by
5691 complement_process_encoding_system. */
5692 setup_coding_system (p->encode_coding_system, coding);
5693 Vlast_coding_system_used = p->encode_coding_system;
5694 }
5695 coding->src_multibyte = 1;
5696 }
5697 else
5698 {
5699 coding->src_multibyte = 0;
5700 /* For sending a unibyte text, character code conversion should
5701 not take place but EOL conversion should. So, setup raw-text
5702 or one of the subsidiary if we have not yet done it. */
5703 if (CODING_REQUIRE_ENCODING (coding))
5704 {
5705 if (CODING_REQUIRE_FLUSHING (coding))
5706 {
5707 /* But, before changing the coding, we must flush out data. */
5708 coding->mode |= CODING_MODE_LAST_BLOCK;
5709 send_process (proc, "", 0, Qt);
5710 coding->mode &= CODING_MODE_LAST_BLOCK;
5711 }
5712 setup_coding_system (raw_text_coding_system
5713 (Vlast_coding_system_used),
5714 coding);
5715 coding->src_multibyte = 0;
5716 }
5717 }
5718 coding->dst_multibyte = 0;
5719
5720 if (CODING_REQUIRE_ENCODING (coding))
5721 {
5722 coding->dst_object = Qt;
5723 if (BUFFERP (object))
5724 {
5725 ptrdiff_t from_byte, from, to;
5726 ptrdiff_t save_pt, save_pt_byte;
5727 struct buffer *cur = current_buffer;
5728
5729 set_buffer_internal (XBUFFER (object));
5730 save_pt = PT, save_pt_byte = PT_BYTE;
5731
5732 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5733 from = BYTE_TO_CHAR (from_byte);
5734 to = BYTE_TO_CHAR (from_byte + len);
5735 TEMP_SET_PT_BOTH (from, from_byte);
5736 encode_coding_object (coding, object, from, from_byte,
5737 to, from_byte + len, Qt);
5738 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5739 set_buffer_internal (cur);
5740 }
5741 else if (STRINGP (object))
5742 {
5743 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5744 SBYTES (object), Qt);
5745 }
5746 else
5747 {
5748 coding->dst_object = make_unibyte_string (buf, len);
5749 coding->produced = len;
5750 }
5751
5752 len = coding->produced;
5753 object = coding->dst_object;
5754 buf = SSDATA (object);
5755 }
5756
5757 /* If there is already data in the write_queue, put the new data
5758 in the back of queue. Otherwise, ignore it. */
5759 if (!NILP (p->write_queue))
5760 write_queue_push (p, object, buf, len, 0);
5761
5762 do /* while !NILP (p->write_queue) */
5763 {
5764 ptrdiff_t cur_len = -1;
5765 const char *cur_buf;
5766 Lisp_Object cur_object;
5767
5768 /* If write_queue is empty, ignore it. */
5769 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5770 {
5771 cur_len = len;
5772 cur_buf = buf;
5773 cur_object = object;
5774 }
5775
5776 while (cur_len > 0)
5777 {
5778 /* Send this batch, using one or more write calls. */
5779 ptrdiff_t written = 0;
5780 int outfd = p->outfd;
5781 #ifdef DATAGRAM_SOCKETS
5782 if (DATAGRAM_CHAN_P (outfd))
5783 {
5784 rv = sendto (outfd, cur_buf, cur_len,
5785 0, datagram_address[outfd].sa,
5786 datagram_address[outfd].len);
5787 if (rv >= 0)
5788 written = rv;
5789 else if (errno == EMSGSIZE)
5790 report_file_error ("Sending datagram", proc);
5791 }
5792 else
5793 #endif
5794 {
5795 #ifdef HAVE_GNUTLS
5796 if (p->gnutls_p && p->gnutls_state)
5797 written = emacs_gnutls_write (p, cur_buf, cur_len);
5798 else
5799 #endif
5800 written = emacs_write_sig (outfd, cur_buf, cur_len);
5801 rv = (written ? 0 : -1);
5802 if (p->read_output_delay > 0
5803 && p->adaptive_read_buffering == 1)
5804 {
5805 p->read_output_delay = 0;
5806 process_output_delay_count--;
5807 p->read_output_skip = 0;
5808 }
5809 }
5810
5811 if (rv < 0)
5812 {
5813 if (errno == EAGAIN
5814 #ifdef EWOULDBLOCK
5815 || errno == EWOULDBLOCK
5816 #endif
5817 )
5818 /* Buffer is full. Wait, accepting input;
5819 that may allow the program
5820 to finish doing output and read more. */
5821 {
5822 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5823 /* A gross hack to work around a bug in FreeBSD.
5824 In the following sequence, read(2) returns
5825 bogus data:
5826
5827 write(2) 1022 bytes
5828 write(2) 954 bytes, get EAGAIN
5829 read(2) 1024 bytes in process_read_output
5830 read(2) 11 bytes in process_read_output
5831
5832 That is, read(2) returns more bytes than have
5833 ever been written successfully. The 1033 bytes
5834 read are the 1022 bytes written successfully
5835 after processing (for example with CRs added if
5836 the terminal is set up that way which it is
5837 here). The same bytes will be seen again in a
5838 later read(2), without the CRs. */
5839
5840 if (errno == EAGAIN)
5841 {
5842 int flags = FWRITE;
5843 ioctl (p->outfd, TIOCFLUSH, &flags);
5844 }
5845 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5846
5847 /* Put what we should have written in wait_queue. */
5848 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5849 wait_reading_process_output (0, 20 * 1000 * 1000,
5850 0, 0, Qnil, NULL, 0);
5851 /* Reread queue, to see what is left. */
5852 break;
5853 }
5854 else if (errno == EPIPE)
5855 {
5856 p->raw_status_new = 0;
5857 pset_status (p, list2 (Qexit, make_number (256)));
5858 p->tick = ++process_tick;
5859 deactivate_process (proc);
5860 error ("process %s no longer connected to pipe; closed it",
5861 SDATA (p->name));
5862 }
5863 else
5864 /* This is a real error. */
5865 report_file_error ("Writing to process", proc);
5866 }
5867 cur_buf += written;
5868 cur_len -= written;
5869 }
5870 }
5871 while (!NILP (p->write_queue));
5872 }
5873
5874 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5875 3, 3, 0,
5876 doc: /* Send current contents of region as input to PROCESS.
5877 PROCESS may be a process, a buffer, the name of a process or buffer, or
5878 nil, indicating the current buffer's process.
5879 Called from program, takes three arguments, PROCESS, START and END.
5880 If the region is more than 500 characters long,
5881 it is sent in several bunches. This may happen even for shorter regions.
5882 Output from processes can arrive in between bunches. */)
5883 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5884 {
5885 Lisp_Object proc = get_process (process);
5886 ptrdiff_t start_byte, end_byte;
5887
5888 validate_region (&start, &end);
5889
5890 start_byte = CHAR_TO_BYTE (XINT (start));
5891 end_byte = CHAR_TO_BYTE (XINT (end));
5892
5893 if (XINT (start) < GPT && XINT (end) > GPT)
5894 move_gap_both (XINT (start), start_byte);
5895
5896 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5897 end_byte - start_byte, Fcurrent_buffer ());
5898
5899 return Qnil;
5900 }
5901
5902 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5903 2, 2, 0,
5904 doc: /* Send PROCESS the contents of STRING as input.
5905 PROCESS may be a process, a buffer, the name of a process or buffer, or
5906 nil, indicating the current buffer's process.
5907 If STRING is more than 500 characters long,
5908 it is sent in several bunches. This may happen even for shorter strings.
5909 Output from processes can arrive in between bunches. */)
5910 (Lisp_Object process, Lisp_Object string)
5911 {
5912 Lisp_Object proc;
5913 CHECK_STRING (string);
5914 proc = get_process (process);
5915 send_process (proc, SSDATA (string),
5916 SBYTES (string), string);
5917 return Qnil;
5918 }
5919 \f
5920 /* Return the foreground process group for the tty/pty that
5921 the process P uses. */
5922 static pid_t
5923 emacs_get_tty_pgrp (struct Lisp_Process *p)
5924 {
5925 pid_t gid = -1;
5926
5927 #ifdef TIOCGPGRP
5928 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5929 {
5930 int fd;
5931 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5932 master side. Try the slave side. */
5933 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5934
5935 if (fd != -1)
5936 {
5937 ioctl (fd, TIOCGPGRP, &gid);
5938 emacs_close (fd);
5939 }
5940 }
5941 #endif /* defined (TIOCGPGRP ) */
5942
5943 return gid;
5944 }
5945
5946 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5947 Sprocess_running_child_p, 0, 1, 0,
5948 doc: /* Return non-nil if PROCESS has given the terminal to a
5949 child. If the operating system does not make it possible to find out,
5950 return t. If we can find out, return the numeric ID of the foreground
5951 process group. */)
5952 (Lisp_Object process)
5953 {
5954 /* Initialize in case ioctl doesn't exist or gives an error,
5955 in a way that will cause returning t. */
5956 pid_t gid;
5957 Lisp_Object proc;
5958 struct Lisp_Process *p;
5959
5960 proc = get_process (process);
5961 p = XPROCESS (proc);
5962
5963 if (!EQ (p->type, Qreal))
5964 error ("Process %s is not a subprocess",
5965 SDATA (p->name));
5966 if (p->infd < 0)
5967 error ("Process %s is not active",
5968 SDATA (p->name));
5969
5970 gid = emacs_get_tty_pgrp (p);
5971
5972 if (gid == p->pid)
5973 return Qnil;
5974 if (gid != -1)
5975 return make_number (gid);
5976 return Qt;
5977 }
5978 \f
5979 /* Send a signal number SIGNO to PROCESS.
5980 If CURRENT_GROUP is t, that means send to the process group
5981 that currently owns the terminal being used to communicate with PROCESS.
5982 This is used for various commands in shell mode.
5983 If CURRENT_GROUP is lambda, that means send to the process group
5984 that currently owns the terminal, but only if it is NOT the shell itself.
5985
5986 If NOMSG is false, insert signal-announcements into process's buffers
5987 right away.
5988
5989 If we can, we try to signal PROCESS by sending control characters
5990 down the pty. This allows us to signal inferiors who have changed
5991 their uid, for which kill would return an EPERM error. */
5992
5993 static void
5994 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5995 bool nomsg)
5996 {
5997 Lisp_Object proc;
5998 struct Lisp_Process *p;
5999 pid_t gid;
6000 bool no_pgrp = 0;
6001
6002 proc = get_process (process);
6003 p = XPROCESS (proc);
6004
6005 if (!EQ (p->type, Qreal))
6006 error ("Process %s is not a subprocess",
6007 SDATA (p->name));
6008 if (p->infd < 0)
6009 error ("Process %s is not active",
6010 SDATA (p->name));
6011
6012 if (!p->pty_flag)
6013 current_group = Qnil;
6014
6015 /* If we are using pgrps, get a pgrp number and make it negative. */
6016 if (NILP (current_group))
6017 /* Send the signal to the shell's process group. */
6018 gid = p->pid;
6019 else
6020 {
6021 #ifdef SIGNALS_VIA_CHARACTERS
6022 /* If possible, send signals to the entire pgrp
6023 by sending an input character to it. */
6024
6025 struct termios t;
6026 cc_t *sig_char = NULL;
6027
6028 tcgetattr (p->infd, &t);
6029
6030 switch (signo)
6031 {
6032 case SIGINT:
6033 sig_char = &t.c_cc[VINTR];
6034 break;
6035
6036 case SIGQUIT:
6037 sig_char = &t.c_cc[VQUIT];
6038 break;
6039
6040 case SIGTSTP:
6041 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6042 sig_char = &t.c_cc[VSWTCH];
6043 #else
6044 sig_char = &t.c_cc[VSUSP];
6045 #endif
6046 break;
6047 }
6048
6049 if (sig_char && *sig_char != CDISABLE)
6050 {
6051 send_process (proc, (char *) sig_char, 1, Qnil);
6052 return;
6053 }
6054 /* If we can't send the signal with a character,
6055 fall through and send it another way. */
6056
6057 /* The code above may fall through if it can't
6058 handle the signal. */
6059 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6060
6061 #ifdef TIOCGPGRP
6062 /* Get the current pgrp using the tty itself, if we have that.
6063 Otherwise, use the pty to get the pgrp.
6064 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6065 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6066 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6067 His patch indicates that if TIOCGPGRP returns an error, then
6068 we should just assume that p->pid is also the process group id. */
6069
6070 gid = emacs_get_tty_pgrp (p);
6071
6072 if (gid == -1)
6073 /* If we can't get the information, assume
6074 the shell owns the tty. */
6075 gid = p->pid;
6076
6077 /* It is not clear whether anything really can set GID to -1.
6078 Perhaps on some system one of those ioctls can or could do so.
6079 Or perhaps this is vestigial. */
6080 if (gid == -1)
6081 no_pgrp = 1;
6082 #else /* ! defined (TIOCGPGRP) */
6083 /* Can't select pgrps on this system, so we know that
6084 the child itself heads the pgrp. */
6085 gid = p->pid;
6086 #endif /* ! defined (TIOCGPGRP) */
6087
6088 /* If current_group is lambda, and the shell owns the terminal,
6089 don't send any signal. */
6090 if (EQ (current_group, Qlambda) && gid == p->pid)
6091 return;
6092 }
6093
6094 #ifdef SIGCONT
6095 if (signo == SIGCONT)
6096 {
6097 p->raw_status_new = 0;
6098 pset_status (p, Qrun);
6099 p->tick = ++process_tick;
6100 if (!nomsg)
6101 {
6102 status_notify (NULL, NULL);
6103 redisplay_preserve_echo_area (13);
6104 }
6105 }
6106 #endif
6107
6108 #ifdef TIOCSIGSEND
6109 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6110 We don't know whether the bug is fixed in later HP-UX versions. */
6111 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6112 return;
6113 #endif
6114
6115 /* If we don't have process groups, send the signal to the immediate
6116 subprocess. That isn't really right, but it's better than any
6117 obvious alternative. */
6118 pid_t pid = no_pgrp ? gid : - gid;
6119
6120 /* Do not kill an already-reaped process, as that could kill an
6121 innocent bystander that happens to have the same process ID. */
6122 sigset_t oldset;
6123 block_child_signal (&oldset);
6124 if (p->alive)
6125 kill (pid, signo);
6126 unblock_child_signal (&oldset);
6127 }
6128
6129 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6130 doc: /* Interrupt process PROCESS.
6131 PROCESS may be a process, a buffer, or the name of a process or buffer.
6132 No arg or nil means current buffer's process.
6133 Second arg CURRENT-GROUP non-nil means send signal to
6134 the current process-group of the process's controlling terminal
6135 rather than to the process's own process group.
6136 If the process is a shell, this means interrupt current subjob
6137 rather than the shell.
6138
6139 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6140 don't send the signal. */)
6141 (Lisp_Object process, Lisp_Object current_group)
6142 {
6143 process_send_signal (process, SIGINT, current_group, 0);
6144 return process;
6145 }
6146
6147 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6148 doc: /* Kill process PROCESS. May be process or name of one.
6149 See function `interrupt-process' for more details on usage. */)
6150 (Lisp_Object process, Lisp_Object current_group)
6151 {
6152 process_send_signal (process, SIGKILL, current_group, 0);
6153 return process;
6154 }
6155
6156 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6157 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6158 See function `interrupt-process' for more details on usage. */)
6159 (Lisp_Object process, Lisp_Object current_group)
6160 {
6161 process_send_signal (process, SIGQUIT, current_group, 0);
6162 return process;
6163 }
6164
6165 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6166 doc: /* Stop process PROCESS. May be process or name of one.
6167 See function `interrupt-process' for more details on usage.
6168 If PROCESS is a network or serial process, inhibit handling of incoming
6169 traffic. */)
6170 (Lisp_Object process, Lisp_Object current_group)
6171 {
6172 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6173 || PIPECONN_P (process)))
6174 {
6175 struct Lisp_Process *p;
6176
6177 p = XPROCESS (process);
6178 if (NILP (p->command)
6179 && p->infd >= 0)
6180 {
6181 FD_CLR (p->infd, &input_wait_mask);
6182 FD_CLR (p->infd, &non_keyboard_wait_mask);
6183 }
6184 pset_command (p, Qt);
6185 return process;
6186 }
6187 #ifndef SIGTSTP
6188 error ("No SIGTSTP support");
6189 #else
6190 process_send_signal (process, SIGTSTP, current_group, 0);
6191 #endif
6192 return process;
6193 }
6194
6195 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6196 doc: /* Continue process PROCESS. May be process or name of one.
6197 See function `interrupt-process' for more details on usage.
6198 If PROCESS is a network or serial process, resume handling of incoming
6199 traffic. */)
6200 (Lisp_Object process, Lisp_Object current_group)
6201 {
6202 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6203 || PIPECONN_P (process)))
6204 {
6205 struct Lisp_Process *p;
6206
6207 p = XPROCESS (process);
6208 if (EQ (p->command, Qt)
6209 && p->infd >= 0
6210 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6211 {
6212 FD_SET (p->infd, &input_wait_mask);
6213 FD_SET (p->infd, &non_keyboard_wait_mask);
6214 #ifdef WINDOWSNT
6215 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6216 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6217 #else /* not WINDOWSNT */
6218 tcflush (p->infd, TCIFLUSH);
6219 #endif /* not WINDOWSNT */
6220 }
6221 pset_command (p, Qnil);
6222 return process;
6223 }
6224 #ifdef SIGCONT
6225 process_send_signal (process, SIGCONT, current_group, 0);
6226 #else
6227 error ("No SIGCONT support");
6228 #endif
6229 return process;
6230 }
6231
6232 /* Return the integer value of the signal whose abbreviation is ABBR,
6233 or a negative number if there is no such signal. */
6234 static int
6235 abbr_to_signal (char const *name)
6236 {
6237 int i, signo;
6238 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6239
6240 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6241 name += 3;
6242
6243 for (i = 0; i < sizeof sigbuf; i++)
6244 {
6245 sigbuf[i] = c_toupper (name[i]);
6246 if (! sigbuf[i])
6247 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6248 }
6249
6250 return -1;
6251 }
6252
6253 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6254 2, 2, "sProcess (name or number): \nnSignal code: ",
6255 doc: /* Send PROCESS the signal with code SIGCODE.
6256 PROCESS may also be a number specifying the process id of the
6257 process to signal; in this case, the process need not be a child of
6258 this Emacs.
6259 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6260 (Lisp_Object process, Lisp_Object sigcode)
6261 {
6262 pid_t pid;
6263 int signo;
6264
6265 if (STRINGP (process))
6266 {
6267 Lisp_Object tem = Fget_process (process);
6268 if (NILP (tem))
6269 {
6270 Lisp_Object process_number
6271 = string_to_number (SSDATA (process), 10, 1);
6272 if (NUMBERP (process_number))
6273 tem = process_number;
6274 }
6275 process = tem;
6276 }
6277 else if (!NUMBERP (process))
6278 process = get_process (process);
6279
6280 if (NILP (process))
6281 return process;
6282
6283 if (NUMBERP (process))
6284 CONS_TO_INTEGER (process, pid_t, pid);
6285 else
6286 {
6287 CHECK_PROCESS (process);
6288 pid = XPROCESS (process)->pid;
6289 if (pid <= 0)
6290 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6291 }
6292
6293 if (INTEGERP (sigcode))
6294 {
6295 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6296 signo = XINT (sigcode);
6297 }
6298 else
6299 {
6300 char *name;
6301
6302 CHECK_SYMBOL (sigcode);
6303 name = SSDATA (SYMBOL_NAME (sigcode));
6304
6305 signo = abbr_to_signal (name);
6306 if (signo < 0)
6307 error ("Undefined signal name %s", name);
6308 }
6309
6310 return make_number (kill (pid, signo));
6311 }
6312
6313 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6314 doc: /* Make PROCESS see end-of-file in its input.
6315 EOF comes after any text already sent to it.
6316 PROCESS may be a process, a buffer, the name of a process or buffer, or
6317 nil, indicating the current buffer's process.
6318 If PROCESS is a network connection, or is a process communicating
6319 through a pipe (as opposed to a pty), then you cannot send any more
6320 text to PROCESS after you call this function.
6321 If PROCESS is a serial process, wait until all output written to the
6322 process has been transmitted to the serial port. */)
6323 (Lisp_Object process)
6324 {
6325 Lisp_Object proc;
6326 struct coding_system *coding = NULL;
6327 int outfd;
6328
6329 if (DATAGRAM_CONN_P (process))
6330 return process;
6331
6332 proc = get_process (process);
6333 outfd = XPROCESS (proc)->outfd;
6334 if (outfd >= 0)
6335 coding = proc_encode_coding_system[outfd];
6336
6337 /* Make sure the process is really alive. */
6338 if (XPROCESS (proc)->raw_status_new)
6339 update_status (XPROCESS (proc));
6340 if (! EQ (XPROCESS (proc)->status, Qrun))
6341 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6342
6343 if (coding && CODING_REQUIRE_FLUSHING (coding))
6344 {
6345 coding->mode |= CODING_MODE_LAST_BLOCK;
6346 send_process (proc, "", 0, Qnil);
6347 }
6348
6349 if (XPROCESS (proc)->pty_flag)
6350 send_process (proc, "\004", 1, Qnil);
6351 else if (EQ (XPROCESS (proc)->type, Qserial))
6352 {
6353 #ifndef WINDOWSNT
6354 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6355 report_file_error ("Failed tcdrain", Qnil);
6356 #endif /* not WINDOWSNT */
6357 /* Do nothing on Windows because writes are blocking. */
6358 }
6359 else
6360 {
6361 struct Lisp_Process *p = XPROCESS (proc);
6362 int old_outfd = p->outfd;
6363 int new_outfd;
6364
6365 #ifdef HAVE_SHUTDOWN
6366 /* If this is a network connection, or socketpair is used
6367 for communication with the subprocess, call shutdown to cause EOF.
6368 (In some old system, shutdown to socketpair doesn't work.
6369 Then we just can't win.) */
6370 if (0 <= old_outfd
6371 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6372 shutdown (old_outfd, 1);
6373 #endif
6374 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6375 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6376 if (new_outfd < 0)
6377 report_file_error ("Opening null device", Qnil);
6378 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6379 p->outfd = new_outfd;
6380
6381 if (!proc_encode_coding_system[new_outfd])
6382 proc_encode_coding_system[new_outfd]
6383 = xmalloc (sizeof (struct coding_system));
6384 if (old_outfd >= 0)
6385 {
6386 *proc_encode_coding_system[new_outfd]
6387 = *proc_encode_coding_system[old_outfd];
6388 memset (proc_encode_coding_system[old_outfd], 0,
6389 sizeof (struct coding_system));
6390 }
6391 else
6392 setup_coding_system (p->encode_coding_system,
6393 proc_encode_coding_system[new_outfd]);
6394 }
6395 return process;
6396 }
6397 \f
6398 /* The main Emacs thread records child processes in three places:
6399
6400 - Vprocess_alist, for asynchronous subprocesses, which are child
6401 processes visible to Lisp.
6402
6403 - deleted_pid_list, for child processes invisible to Lisp,
6404 typically because of delete-process. These are recorded so that
6405 the processes can be reaped when they exit, so that the operating
6406 system's process table is not cluttered by zombies.
6407
6408 - the local variable PID in Fcall_process, call_process_cleanup and
6409 call_process_kill, for synchronous subprocesses.
6410 record_unwind_protect is used to make sure this process is not
6411 forgotten: if the user interrupts call-process and the child
6412 process refuses to exit immediately even with two C-g's,
6413 call_process_kill adds PID's contents to deleted_pid_list before
6414 returning.
6415
6416 The main Emacs thread invokes waitpid only on child processes that
6417 it creates and that have not been reaped. This avoid races on
6418 platforms such as GTK, where other threads create their own
6419 subprocesses which the main thread should not reap. For example,
6420 if the main thread attempted to reap an already-reaped child, it
6421 might inadvertently reap a GTK-created process that happened to
6422 have the same process ID. */
6423
6424 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6425 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6426 keep track of its own children. GNUstep is similar. */
6427
6428 static void dummy_handler (int sig) {}
6429 static signal_handler_t volatile lib_child_handler;
6430
6431 /* Handle a SIGCHLD signal by looking for known child processes of
6432 Emacs whose status have changed. For each one found, record its
6433 new status.
6434
6435 All we do is change the status; we do not run sentinels or print
6436 notifications. That is saved for the next time keyboard input is
6437 done, in order to avoid timing errors.
6438
6439 ** WARNING: this can be called during garbage collection.
6440 Therefore, it must not be fooled by the presence of mark bits in
6441 Lisp objects.
6442
6443 ** USG WARNING: Although it is not obvious from the documentation
6444 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6445 signal() before executing at least one wait(), otherwise the
6446 handler will be called again, resulting in an infinite loop. The
6447 relevant portion of the documentation reads "SIGCLD signals will be
6448 queued and the signal-catching function will be continually
6449 reentered until the queue is empty". Invoking signal() causes the
6450 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6451 Inc.
6452
6453 ** Malloc WARNING: This should never call malloc either directly or
6454 indirectly; if it does, that is a bug. */
6455
6456 static void
6457 handle_child_signal (int sig)
6458 {
6459 Lisp_Object tail, proc;
6460
6461 /* Find the process that signaled us, and record its status. */
6462
6463 /* The process can have been deleted by Fdelete_process, or have
6464 been started asynchronously by Fcall_process. */
6465 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6466 {
6467 bool all_pids_are_fixnums
6468 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6469 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6470 Lisp_Object head = XCAR (tail);
6471 Lisp_Object xpid;
6472 if (! CONSP (head))
6473 continue;
6474 xpid = XCAR (head);
6475 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6476 {
6477 pid_t deleted_pid;
6478 if (INTEGERP (xpid))
6479 deleted_pid = XINT (xpid);
6480 else
6481 deleted_pid = XFLOAT_DATA (xpid);
6482 if (child_status_changed (deleted_pid, 0, 0))
6483 {
6484 if (STRINGP (XCDR (head)))
6485 unlink (SSDATA (XCDR (head)));
6486 XSETCAR (tail, Qnil);
6487 }
6488 }
6489 }
6490
6491 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6492 FOR_EACH_PROCESS (tail, proc)
6493 {
6494 struct Lisp_Process *p = XPROCESS (proc);
6495 int status;
6496
6497 if (p->alive
6498 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6499 {
6500 /* Change the status of the process that was found. */
6501 p->tick = ++process_tick;
6502 p->raw_status = status;
6503 p->raw_status_new = 1;
6504
6505 /* If process has terminated, stop waiting for its output. */
6506 if (WIFSIGNALED (status) || WIFEXITED (status))
6507 {
6508 bool clear_desc_flag = 0;
6509 p->alive = 0;
6510 if (p->infd >= 0)
6511 clear_desc_flag = 1;
6512
6513 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6514 if (clear_desc_flag)
6515 {
6516 FD_CLR (p->infd, &input_wait_mask);
6517 FD_CLR (p->infd, &non_keyboard_wait_mask);
6518 }
6519 }
6520 }
6521 }
6522
6523 lib_child_handler (sig);
6524 #ifdef NS_IMPL_GNUSTEP
6525 /* NSTask in GNUstep sets its child handler each time it is called.
6526 So we must re-set ours. */
6527 catch_child_signal ();
6528 #endif
6529 }
6530
6531 static void
6532 deliver_child_signal (int sig)
6533 {
6534 deliver_process_signal (sig, handle_child_signal);
6535 }
6536 \f
6537
6538 static Lisp_Object
6539 exec_sentinel_error_handler (Lisp_Object error_val)
6540 {
6541 cmd_error_internal (error_val, "error in process sentinel: ");
6542 Vinhibit_quit = Qt;
6543 update_echo_area ();
6544 Fsleep_for (make_number (2), Qnil);
6545 return Qt;
6546 }
6547
6548 static void
6549 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6550 {
6551 Lisp_Object sentinel, odeactivate;
6552 struct Lisp_Process *p = XPROCESS (proc);
6553 ptrdiff_t count = SPECPDL_INDEX ();
6554 bool outer_running_asynch_code = running_asynch_code;
6555 int waiting = waiting_for_user_input_p;
6556
6557 if (inhibit_sentinels)
6558 return;
6559
6560 odeactivate = Vdeactivate_mark;
6561 #if 0
6562 Lisp_Object obuffer, okeymap;
6563 XSETBUFFER (obuffer, current_buffer);
6564 okeymap = BVAR (current_buffer, keymap);
6565 #endif
6566
6567 /* There's no good reason to let sentinels change the current
6568 buffer, and many callers of accept-process-output, sit-for, and
6569 friends don't expect current-buffer to be changed from under them. */
6570 record_unwind_current_buffer ();
6571
6572 sentinel = p->sentinel;
6573
6574 /* Inhibit quit so that random quits don't screw up a running filter. */
6575 specbind (Qinhibit_quit, Qt);
6576 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6577
6578 /* In case we get recursively called,
6579 and we already saved the match data nonrecursively,
6580 save the same match data in safely recursive fashion. */
6581 if (outer_running_asynch_code)
6582 {
6583 Lisp_Object tem;
6584 tem = Fmatch_data (Qnil, Qnil, Qnil);
6585 restore_search_regs ();
6586 record_unwind_save_match_data ();
6587 Fset_match_data (tem, Qt);
6588 }
6589
6590 /* For speed, if a search happens within this code,
6591 save the match data in a special nonrecursive fashion. */
6592 running_asynch_code = 1;
6593
6594 internal_condition_case_1 (read_process_output_call,
6595 list3 (sentinel, proc, reason),
6596 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6597 exec_sentinel_error_handler);
6598
6599 /* If we saved the match data nonrecursively, restore it now. */
6600 restore_search_regs ();
6601 running_asynch_code = outer_running_asynch_code;
6602
6603 Vdeactivate_mark = odeactivate;
6604
6605 /* Restore waiting_for_user_input_p as it was
6606 when we were called, in case the filter clobbered it. */
6607 waiting_for_user_input_p = waiting;
6608
6609 #if 0
6610 if (! EQ (Fcurrent_buffer (), obuffer)
6611 || ! EQ (current_buffer->keymap, okeymap))
6612 #endif
6613 /* But do it only if the caller is actually going to read events.
6614 Otherwise there's no need to make him wake up, and it could
6615 cause trouble (for example it would make sit_for return). */
6616 if (waiting_for_user_input_p == -1)
6617 record_asynch_buffer_change ();
6618
6619 unbind_to (count, Qnil);
6620 }
6621
6622 /* Report all recent events of a change in process status
6623 (either run the sentinel or output a message).
6624 This is usually done while Emacs is waiting for keyboard input
6625 but can be done at other times.
6626
6627 Return positive if any input was received from WAIT_PROC (or from
6628 any process if WAIT_PROC is null), zero if input was attempted but
6629 none received, and negative if we didn't even try. */
6630
6631 static int
6632 status_notify (struct Lisp_Process *deleting_process,
6633 struct Lisp_Process *wait_proc)
6634 {
6635 Lisp_Object proc;
6636 Lisp_Object tail, msg;
6637 int got_some_output = -1;
6638
6639 tail = Qnil;
6640 msg = Qnil;
6641
6642 /* Set this now, so that if new processes are created by sentinels
6643 that we run, we get called again to handle their status changes. */
6644 update_tick = process_tick;
6645
6646 FOR_EACH_PROCESS (tail, proc)
6647 {
6648 Lisp_Object symbol;
6649 register struct Lisp_Process *p = XPROCESS (proc);
6650
6651 if (p->tick != p->update_tick)
6652 {
6653 p->update_tick = p->tick;
6654
6655 /* If process is still active, read any output that remains. */
6656 while (! EQ (p->filter, Qt)
6657 && ! EQ (p->status, Qconnect)
6658 && ! EQ (p->status, Qlisten)
6659 /* Network or serial process not stopped: */
6660 && ! EQ (p->command, Qt)
6661 && p->infd >= 0
6662 && p != deleting_process)
6663 {
6664 int nread = read_process_output (proc, p->infd);
6665 if ((!wait_proc || wait_proc == XPROCESS (proc))
6666 && got_some_output < nread)
6667 got_some_output = nread;
6668 if (nread <= 0)
6669 break;
6670 }
6671
6672 /* Get the text to use for the message. */
6673 if (p->raw_status_new)
6674 update_status (p);
6675 msg = status_message (p);
6676
6677 /* If process is terminated, deactivate it or delete it. */
6678 symbol = p->status;
6679 if (CONSP (p->status))
6680 symbol = XCAR (p->status);
6681
6682 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6683 || EQ (symbol, Qclosed))
6684 {
6685 if (delete_exited_processes)
6686 remove_process (proc);
6687 else
6688 deactivate_process (proc);
6689 }
6690
6691 /* The actions above may have further incremented p->tick.
6692 So set p->update_tick again so that an error in the sentinel will
6693 not cause this code to be run again. */
6694 p->update_tick = p->tick;
6695 /* Now output the message suitably. */
6696 exec_sentinel (proc, msg);
6697 if (BUFFERP (p->buffer))
6698 /* In case it uses %s in mode-line-format. */
6699 bset_update_mode_line (XBUFFER (p->buffer));
6700 }
6701 } /* end for */
6702
6703 return got_some_output;
6704 }
6705
6706 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6707 Sinternal_default_process_sentinel, 2, 2, 0,
6708 doc: /* Function used as default sentinel for processes.
6709 This inserts a status message into the process's buffer, if there is one. */)
6710 (Lisp_Object proc, Lisp_Object msg)
6711 {
6712 Lisp_Object buffer, symbol;
6713 struct Lisp_Process *p;
6714 CHECK_PROCESS (proc);
6715 p = XPROCESS (proc);
6716 buffer = p->buffer;
6717 symbol = p->status;
6718 if (CONSP (symbol))
6719 symbol = XCAR (symbol);
6720
6721 if (!EQ (symbol, Qrun) && !NILP (buffer))
6722 {
6723 Lisp_Object tem;
6724 struct buffer *old = current_buffer;
6725 ptrdiff_t opoint, opoint_byte;
6726 ptrdiff_t before, before_byte;
6727
6728 /* Avoid error if buffer is deleted
6729 (probably that's why the process is dead, too). */
6730 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6731 return Qnil;
6732 Fset_buffer (buffer);
6733
6734 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6735 msg = (code_convert_string_norecord
6736 (msg, Vlocale_coding_system, 1));
6737
6738 opoint = PT;
6739 opoint_byte = PT_BYTE;
6740 /* Insert new output into buffer
6741 at the current end-of-output marker,
6742 thus preserving logical ordering of input and output. */
6743 if (XMARKER (p->mark)->buffer)
6744 Fgoto_char (p->mark);
6745 else
6746 SET_PT_BOTH (ZV, ZV_BYTE);
6747
6748 before = PT;
6749 before_byte = PT_BYTE;
6750
6751 tem = BVAR (current_buffer, read_only);
6752 bset_read_only (current_buffer, Qnil);
6753 insert_string ("\nProcess ");
6754 { /* FIXME: temporary kludge. */
6755 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6756 insert_string (" ");
6757 Finsert (1, &msg);
6758 bset_read_only (current_buffer, tem);
6759 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6760
6761 if (opoint >= before)
6762 SET_PT_BOTH (opoint + (PT - before),
6763 opoint_byte + (PT_BYTE - before_byte));
6764 else
6765 SET_PT_BOTH (opoint, opoint_byte);
6766
6767 set_buffer_internal (old);
6768 }
6769 return Qnil;
6770 }
6771
6772 \f
6773 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6774 Sset_process_coding_system, 1, 3, 0,
6775 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6776 DECODING will be used to decode subprocess output and ENCODING to
6777 encode subprocess input. */)
6778 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6779 {
6780 register struct Lisp_Process *p;
6781
6782 CHECK_PROCESS (process);
6783 p = XPROCESS (process);
6784 if (p->infd < 0)
6785 error ("Input file descriptor of %s closed", SDATA (p->name));
6786 if (p->outfd < 0)
6787 error ("Output file descriptor of %s closed", SDATA (p->name));
6788 Fcheck_coding_system (decoding);
6789 Fcheck_coding_system (encoding);
6790 encoding = coding_inherit_eol_type (encoding, Qnil);
6791 pset_decode_coding_system (p, decoding);
6792 pset_encode_coding_system (p, encoding);
6793 setup_process_coding_systems (process);
6794
6795 return Qnil;
6796 }
6797
6798 DEFUN ("process-coding-system",
6799 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6800 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6801 (register Lisp_Object process)
6802 {
6803 CHECK_PROCESS (process);
6804 return Fcons (XPROCESS (process)->decode_coding_system,
6805 XPROCESS (process)->encode_coding_system);
6806 }
6807
6808 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6809 Sset_process_filter_multibyte, 2, 2, 0,
6810 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6811 If FLAG is non-nil, the filter is given multibyte strings.
6812 If FLAG is nil, the filter is given unibyte strings. In this case,
6813 all character code conversion except for end-of-line conversion is
6814 suppressed. */)
6815 (Lisp_Object process, Lisp_Object flag)
6816 {
6817 register struct Lisp_Process *p;
6818
6819 CHECK_PROCESS (process);
6820 p = XPROCESS (process);
6821 if (NILP (flag))
6822 pset_decode_coding_system
6823 (p, raw_text_coding_system (p->decode_coding_system));
6824 setup_process_coding_systems (process);
6825
6826 return Qnil;
6827 }
6828
6829 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6830 Sprocess_filter_multibyte_p, 1, 1, 0,
6831 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6832 (Lisp_Object process)
6833 {
6834 register struct Lisp_Process *p;
6835 struct coding_system *coding;
6836
6837 CHECK_PROCESS (process);
6838 p = XPROCESS (process);
6839 if (p->infd < 0)
6840 return Qnil;
6841 coding = proc_decode_coding_system[p->infd];
6842 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6843 }
6844
6845
6846 \f
6847
6848 # ifdef HAVE_GPM
6849
6850 void
6851 add_gpm_wait_descriptor (int desc)
6852 {
6853 add_keyboard_wait_descriptor (desc);
6854 }
6855
6856 void
6857 delete_gpm_wait_descriptor (int desc)
6858 {
6859 delete_keyboard_wait_descriptor (desc);
6860 }
6861
6862 # endif
6863
6864 # ifdef USABLE_SIGIO
6865
6866 /* Return true if *MASK has a bit set
6867 that corresponds to one of the keyboard input descriptors. */
6868
6869 static bool
6870 keyboard_bit_set (fd_set *mask)
6871 {
6872 int fd;
6873
6874 for (fd = 0; fd <= max_input_desc; fd++)
6875 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6876 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6877 return 1;
6878
6879 return 0;
6880 }
6881 # endif
6882
6883 #else /* not subprocesses */
6884
6885 /* Defined in msdos.c. */
6886 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6887 struct timespec *, void *);
6888
6889 /* Implementation of wait_reading_process_output, assuming that there
6890 are no subprocesses. Used only by the MS-DOS build.
6891
6892 Wait for timeout to elapse and/or keyboard input to be available.
6893
6894 TIME_LIMIT is:
6895 timeout in seconds
6896 If negative, gobble data immediately available but don't wait for any.
6897
6898 NSECS is:
6899 an additional duration to wait, measured in nanoseconds
6900 If TIME_LIMIT is zero, then:
6901 If NSECS == 0, there is no limit.
6902 If NSECS > 0, the timeout consists of NSECS only.
6903 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6904
6905 READ_KBD is:
6906 0 to ignore keyboard input, or
6907 1 to return when input is available, or
6908 -1 means caller will actually read the input, so don't throw to
6909 the quit handler.
6910
6911 see full version for other parameters. We know that wait_proc will
6912 always be NULL, since `subprocesses' isn't defined.
6913
6914 DO_DISPLAY means redisplay should be done to show subprocess
6915 output that arrives.
6916
6917 Return -1 signifying we got no output and did not try. */
6918
6919 int
6920 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6921 bool do_display,
6922 Lisp_Object wait_for_cell,
6923 struct Lisp_Process *wait_proc, int just_wait_proc)
6924 {
6925 register int nfds;
6926 struct timespec end_time, timeout;
6927 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6928
6929 if (TYPE_MAXIMUM (time_t) < time_limit)
6930 time_limit = TYPE_MAXIMUM (time_t);
6931
6932 if (time_limit < 0 || nsecs < 0)
6933 wait = MINIMUM;
6934 else if (time_limit > 0 || nsecs > 0)
6935 {
6936 wait = TIMEOUT;
6937 end_time = timespec_add (current_timespec (),
6938 make_timespec (time_limit, nsecs));
6939 }
6940 else
6941 wait = INFINITY;
6942
6943 /* Turn off periodic alarms (in case they are in use)
6944 and then turn off any other atimers,
6945 because the select emulator uses alarms. */
6946 stop_polling ();
6947 turn_on_atimers (0);
6948
6949 while (1)
6950 {
6951 bool timeout_reduced_for_timers = false;
6952 fd_set waitchannels;
6953 int xerrno;
6954
6955 /* If calling from keyboard input, do not quit
6956 since we want to return C-g as an input character.
6957 Otherwise, do pending quit if requested. */
6958 if (read_kbd >= 0)
6959 QUIT;
6960
6961 /* Exit now if the cell we're waiting for became non-nil. */
6962 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6963 break;
6964
6965 /* Compute time from now till when time limit is up. */
6966 /* Exit if already run out. */
6967 if (wait == TIMEOUT)
6968 {
6969 struct timespec now = current_timespec ();
6970 if (timespec_cmp (end_time, now) <= 0)
6971 break;
6972 timeout = timespec_sub (end_time, now);
6973 }
6974 else
6975 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
6976
6977 /* If our caller will not immediately handle keyboard events,
6978 run timer events directly.
6979 (Callers that will immediately read keyboard events
6980 call timer_delay on their own.) */
6981 if (NILP (wait_for_cell))
6982 {
6983 struct timespec timer_delay;
6984
6985 do
6986 {
6987 unsigned old_timers_run = timers_run;
6988 timer_delay = timer_check ();
6989 if (timers_run != old_timers_run && do_display)
6990 /* We must retry, since a timer may have requeued itself
6991 and that could alter the time delay. */
6992 redisplay_preserve_echo_area (14);
6993 else
6994 break;
6995 }
6996 while (!detect_input_pending ());
6997
6998 /* If there is unread keyboard input, also return. */
6999 if (read_kbd != 0
7000 && requeued_events_pending_p ())
7001 break;
7002
7003 if (timespec_valid_p (timer_delay))
7004 {
7005 if (timespec_cmp (timer_delay, timeout) < 0)
7006 {
7007 timeout = timer_delay;
7008 timeout_reduced_for_timers = true;
7009 }
7010 }
7011 }
7012
7013 /* Cause C-g and alarm signals to take immediate action,
7014 and cause input available signals to zero out timeout. */
7015 if (read_kbd < 0)
7016 set_waiting_for_input (&timeout);
7017
7018 /* If a frame has been newly mapped and needs updating,
7019 reprocess its display stuff. */
7020 if (frame_garbaged && do_display)
7021 {
7022 clear_waiting_for_input ();
7023 redisplay_preserve_echo_area (15);
7024 if (read_kbd < 0)
7025 set_waiting_for_input (&timeout);
7026 }
7027
7028 /* Wait till there is something to do. */
7029 FD_ZERO (&waitchannels);
7030 if (read_kbd && detect_input_pending ())
7031 nfds = 0;
7032 else
7033 {
7034 if (read_kbd || !NILP (wait_for_cell))
7035 FD_SET (0, &waitchannels);
7036 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7037 }
7038
7039 xerrno = errno;
7040
7041 /* Make C-g and alarm signals set flags again. */
7042 clear_waiting_for_input ();
7043
7044 /* If we woke up due to SIGWINCH, actually change size now. */
7045 do_pending_window_change (0);
7046
7047 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7048 /* We waited the full specified time, so return now. */
7049 break;
7050
7051 if (nfds == -1)
7052 {
7053 /* If the system call was interrupted, then go around the
7054 loop again. */
7055 if (xerrno == EINTR)
7056 FD_ZERO (&waitchannels);
7057 else
7058 report_file_errno ("Failed select", Qnil, xerrno);
7059 }
7060
7061 /* Check for keyboard input. */
7062
7063 if (read_kbd
7064 && detect_input_pending_run_timers (do_display))
7065 {
7066 swallow_events (do_display);
7067 if (detect_input_pending_run_timers (do_display))
7068 break;
7069 }
7070
7071 /* If there is unread keyboard input, also return. */
7072 if (read_kbd
7073 && requeued_events_pending_p ())
7074 break;
7075
7076 /* If wait_for_cell. check for keyboard input
7077 but don't run any timers.
7078 ??? (It seems wrong to me to check for keyboard
7079 input at all when wait_for_cell, but the code
7080 has been this way since July 1994.
7081 Try changing this after version 19.31.) */
7082 if (! NILP (wait_for_cell)
7083 && detect_input_pending ())
7084 {
7085 swallow_events (do_display);
7086 if (detect_input_pending ())
7087 break;
7088 }
7089
7090 /* Exit now if the cell we're waiting for became non-nil. */
7091 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7092 break;
7093 }
7094
7095 start_polling ();
7096
7097 return -1;
7098 }
7099
7100 #endif /* not subprocesses */
7101
7102 /* The following functions are needed even if async subprocesses are
7103 not supported. Some of them are no-op stubs in that case. */
7104
7105 #ifdef HAVE_TIMERFD
7106
7107 /* Add FD, which is a descriptor returned by timerfd_create,
7108 to the set of non-keyboard input descriptors. */
7109
7110 void
7111 add_timer_wait_descriptor (int fd)
7112 {
7113 FD_SET (fd, &input_wait_mask);
7114 FD_SET (fd, &non_keyboard_wait_mask);
7115 FD_SET (fd, &non_process_wait_mask);
7116 fd_callback_info[fd].func = timerfd_callback;
7117 fd_callback_info[fd].data = NULL;
7118 fd_callback_info[fd].condition |= FOR_READ;
7119 if (fd > max_input_desc)
7120 max_input_desc = fd;
7121 }
7122
7123 #endif /* HAVE_TIMERFD */
7124
7125 /* Add DESC to the set of keyboard input descriptors. */
7126
7127 void
7128 add_keyboard_wait_descriptor (int desc)
7129 {
7130 #ifdef subprocesses /* Actually means "not MSDOS". */
7131 FD_SET (desc, &input_wait_mask);
7132 FD_SET (desc, &non_process_wait_mask);
7133 if (desc > max_input_desc)
7134 max_input_desc = desc;
7135 #endif
7136 }
7137
7138 /* From now on, do not expect DESC to give keyboard input. */
7139
7140 void
7141 delete_keyboard_wait_descriptor (int desc)
7142 {
7143 #ifdef subprocesses
7144 FD_CLR (desc, &input_wait_mask);
7145 FD_CLR (desc, &non_process_wait_mask);
7146 delete_input_desc (desc);
7147 #endif
7148 }
7149
7150 /* Setup coding systems of PROCESS. */
7151
7152 void
7153 setup_process_coding_systems (Lisp_Object process)
7154 {
7155 #ifdef subprocesses
7156 struct Lisp_Process *p = XPROCESS (process);
7157 int inch = p->infd;
7158 int outch = p->outfd;
7159 Lisp_Object coding_system;
7160
7161 if (inch < 0 || outch < 0)
7162 return;
7163
7164 if (!proc_decode_coding_system[inch])
7165 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7166 coding_system = p->decode_coding_system;
7167 if (EQ (p->filter, Qinternal_default_process_filter)
7168 && BUFFERP (p->buffer))
7169 {
7170 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7171 coding_system = raw_text_coding_system (coding_system);
7172 }
7173 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7174
7175 if (!proc_encode_coding_system[outch])
7176 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7177 setup_coding_system (p->encode_coding_system,
7178 proc_encode_coding_system[outch]);
7179 #endif
7180 }
7181
7182 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7183 doc: /* Return the (or a) process associated with BUFFER.
7184 BUFFER may be a buffer or the name of one. */)
7185 (register Lisp_Object buffer)
7186 {
7187 #ifdef subprocesses
7188 register Lisp_Object buf, tail, proc;
7189
7190 if (NILP (buffer)) return Qnil;
7191 buf = Fget_buffer (buffer);
7192 if (NILP (buf)) return Qnil;
7193
7194 FOR_EACH_PROCESS (tail, proc)
7195 if (EQ (XPROCESS (proc)->buffer, buf))
7196 return proc;
7197 #endif /* subprocesses */
7198 return Qnil;
7199 }
7200
7201 DEFUN ("process-inherit-coding-system-flag",
7202 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7203 1, 1, 0,
7204 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7205 If this flag is t, `buffer-file-coding-system' of the buffer
7206 associated with PROCESS will inherit the coding system used to decode
7207 the process output. */)
7208 (register Lisp_Object process)
7209 {
7210 #ifdef subprocesses
7211 CHECK_PROCESS (process);
7212 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7213 #else
7214 /* Ignore the argument and return the value of
7215 inherit-process-coding-system. */
7216 return inherit_process_coding_system ? Qt : Qnil;
7217 #endif
7218 }
7219
7220 /* Kill all processes associated with `buffer'.
7221 If `buffer' is nil, kill all processes. */
7222
7223 void
7224 kill_buffer_processes (Lisp_Object buffer)
7225 {
7226 #ifdef subprocesses
7227 Lisp_Object tail, proc;
7228
7229 FOR_EACH_PROCESS (tail, proc)
7230 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7231 {
7232 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7233 Fdelete_process (proc);
7234 else if (XPROCESS (proc)->infd >= 0)
7235 process_send_signal (proc, SIGHUP, Qnil, 1);
7236 }
7237 #else /* subprocesses */
7238 /* Since we have no subprocesses, this does nothing. */
7239 #endif /* subprocesses */
7240 }
7241
7242 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7243 Swaiting_for_user_input_p, 0, 0, 0,
7244 doc: /* Return non-nil if Emacs is waiting for input from the user.
7245 This is intended for use by asynchronous process output filters and sentinels. */)
7246 (void)
7247 {
7248 #ifdef subprocesses
7249 return (waiting_for_user_input_p ? Qt : Qnil);
7250 #else
7251 return Qnil;
7252 #endif
7253 }
7254
7255 /* Stop reading input from keyboard sources. */
7256
7257 void
7258 hold_keyboard_input (void)
7259 {
7260 kbd_is_on_hold = 1;
7261 }
7262
7263 /* Resume reading input from keyboard sources. */
7264
7265 void
7266 unhold_keyboard_input (void)
7267 {
7268 kbd_is_on_hold = 0;
7269 }
7270
7271 /* Return true if keyboard input is on hold, zero otherwise. */
7272
7273 bool
7274 kbd_on_hold_p (void)
7275 {
7276 return kbd_is_on_hold;
7277 }
7278
7279 \f
7280 /* Enumeration of and access to system processes a-la ps(1). */
7281
7282 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7283 0, 0, 0,
7284 doc: /* Return a list of numerical process IDs of all running processes.
7285 If this functionality is unsupported, return nil.
7286
7287 See `process-attributes' for getting attributes of a process given its ID. */)
7288 (void)
7289 {
7290 return list_system_processes ();
7291 }
7292
7293 DEFUN ("process-attributes", Fprocess_attributes,
7294 Sprocess_attributes, 1, 1, 0,
7295 doc: /* Return attributes of the process given by its PID, a number.
7296
7297 Value is an alist where each element is a cons cell of the form
7298
7299 (KEY . VALUE)
7300
7301 If this functionality is unsupported, the value is nil.
7302
7303 See `list-system-processes' for getting a list of all process IDs.
7304
7305 The KEYs of the attributes that this function may return are listed
7306 below, together with the type of the associated VALUE (in parentheses).
7307 Not all platforms support all of these attributes; unsupported
7308 attributes will not appear in the returned alist.
7309 Unless explicitly indicated otherwise, numbers can have either
7310 integer or floating point values.
7311
7312 euid -- Effective user User ID of the process (number)
7313 user -- User name corresponding to euid (string)
7314 egid -- Effective user Group ID of the process (number)
7315 group -- Group name corresponding to egid (string)
7316 comm -- Command name (executable name only) (string)
7317 state -- Process state code, such as "S", "R", or "T" (string)
7318 ppid -- Parent process ID (number)
7319 pgrp -- Process group ID (number)
7320 sess -- Session ID, i.e. process ID of session leader (number)
7321 ttname -- Controlling tty name (string)
7322 tpgid -- ID of foreground process group on the process's tty (number)
7323 minflt -- number of minor page faults (number)
7324 majflt -- number of major page faults (number)
7325 cminflt -- cumulative number of minor page faults (number)
7326 cmajflt -- cumulative number of major page faults (number)
7327 utime -- user time used by the process, in (current-time) format,
7328 which is a list of integers (HIGH LOW USEC PSEC)
7329 stime -- system time used by the process (current-time)
7330 time -- sum of utime and stime (current-time)
7331 cutime -- user time used by the process and its children (current-time)
7332 cstime -- system time used by the process and its children (current-time)
7333 ctime -- sum of cutime and cstime (current-time)
7334 pri -- priority of the process (number)
7335 nice -- nice value of the process (number)
7336 thcount -- process thread count (number)
7337 start -- time the process started (current-time)
7338 vsize -- virtual memory size of the process in KB's (number)
7339 rss -- resident set size of the process in KB's (number)
7340 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7341 pcpu -- percents of CPU time used by the process (floating-point number)
7342 pmem -- percents of total physical memory used by process's resident set
7343 (floating-point number)
7344 args -- command line which invoked the process (string). */)
7345 ( Lisp_Object pid)
7346 {
7347 return system_process_attributes (pid);
7348 }
7349
7350 #ifdef subprocesses
7351 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7352 Invoke this after init_process_emacs, and after glib and/or GNUstep
7353 futz with the SIGCHLD handler, but before Emacs forks any children.
7354 This function's caller should block SIGCHLD. */
7355
7356 void
7357 catch_child_signal (void)
7358 {
7359 struct sigaction action, old_action;
7360 sigset_t oldset;
7361 emacs_sigaction_init (&action, deliver_child_signal);
7362 block_child_signal (&oldset);
7363 sigaction (SIGCHLD, &action, &old_action);
7364 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7365 || ! (old_action.sa_flags & SA_SIGINFO));
7366
7367 if (old_action.sa_handler != deliver_child_signal)
7368 lib_child_handler
7369 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7370 ? dummy_handler
7371 : old_action.sa_handler);
7372 unblock_child_signal (&oldset);
7373 }
7374 #endif /* subprocesses */
7375
7376 \f
7377 /* This is not called "init_process" because that is the name of a
7378 Mach system call, so it would cause problems on Darwin systems. */
7379 void
7380 init_process_emacs (void)
7381 {
7382 #ifdef subprocesses
7383 register int i;
7384
7385 inhibit_sentinels = 0;
7386
7387 #ifndef CANNOT_DUMP
7388 if (! noninteractive || initialized)
7389 #endif
7390 {
7391 #if defined HAVE_GLIB && !defined WINDOWSNT
7392 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7393 this should always fail, but is enough to initialize glib's
7394 private SIGCHLD handler, allowing catch_child_signal to copy
7395 it into lib_child_handler. */
7396 g_source_unref (g_child_watch_source_new (getpid ()));
7397 #endif
7398 catch_child_signal ();
7399 }
7400
7401 FD_ZERO (&input_wait_mask);
7402 FD_ZERO (&non_keyboard_wait_mask);
7403 FD_ZERO (&non_process_wait_mask);
7404 FD_ZERO (&write_mask);
7405 max_process_desc = max_input_desc = -1;
7406 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7407
7408 #ifdef NON_BLOCKING_CONNECT
7409 FD_ZERO (&connect_wait_mask);
7410 num_pending_connects = 0;
7411 #endif
7412
7413 process_output_delay_count = 0;
7414 process_output_skip = 0;
7415
7416 /* Don't do this, it caused infinite select loops. The display
7417 method should call add_keyboard_wait_descriptor on stdin if it
7418 needs that. */
7419 #if 0
7420 FD_SET (0, &input_wait_mask);
7421 #endif
7422
7423 Vprocess_alist = Qnil;
7424 deleted_pid_list = Qnil;
7425 for (i = 0; i < FD_SETSIZE; i++)
7426 {
7427 chan_process[i] = Qnil;
7428 proc_buffered_char[i] = -1;
7429 }
7430 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7431 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7432 #ifdef DATAGRAM_SOCKETS
7433 memset (datagram_address, 0, sizeof datagram_address);
7434 #endif
7435
7436 #if defined (DARWIN_OS)
7437 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7438 processes. As such, we only change the default value. */
7439 if (initialized)
7440 {
7441 char const *release = (STRINGP (Voperating_system_release)
7442 ? SSDATA (Voperating_system_release)
7443 : 0);
7444 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7445 Vprocess_connection_type = Qnil;
7446 }
7447 }
7448 #endif
7449 #endif /* subprocesses */
7450 kbd_is_on_hold = 0;
7451 }
7452
7453 void
7454 syms_of_process (void)
7455 {
7456 #ifdef subprocesses
7457
7458 DEFSYM (Qprocessp, "processp");
7459 DEFSYM (Qrun, "run");
7460 DEFSYM (Qstop, "stop");
7461 DEFSYM (Qsignal, "signal");
7462
7463 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7464 here again. */
7465
7466 DEFSYM (Qopen, "open");
7467 DEFSYM (Qclosed, "closed");
7468 DEFSYM (Qconnect, "connect");
7469 DEFSYM (Qfailed, "failed");
7470 DEFSYM (Qlisten, "listen");
7471 DEFSYM (Qlocal, "local");
7472 DEFSYM (Qipv4, "ipv4");
7473 #ifdef AF_INET6
7474 DEFSYM (Qipv6, "ipv6");
7475 #endif
7476 DEFSYM (Qdatagram, "datagram");
7477 DEFSYM (Qseqpacket, "seqpacket");
7478
7479 DEFSYM (QCport, ":port");
7480 DEFSYM (QCspeed, ":speed");
7481 DEFSYM (QCprocess, ":process");
7482
7483 DEFSYM (QCbytesize, ":bytesize");
7484 DEFSYM (QCstopbits, ":stopbits");
7485 DEFSYM (QCparity, ":parity");
7486 DEFSYM (Qodd, "odd");
7487 DEFSYM (Qeven, "even");
7488 DEFSYM (QCflowcontrol, ":flowcontrol");
7489 DEFSYM (Qhw, "hw");
7490 DEFSYM (Qsw, "sw");
7491 DEFSYM (QCsummary, ":summary");
7492
7493 DEFSYM (Qreal, "real");
7494 DEFSYM (Qnetwork, "network");
7495 DEFSYM (Qserial, "serial");
7496 DEFSYM (Qpipe, "pipe");
7497 DEFSYM (QCbuffer, ":buffer");
7498 DEFSYM (QChost, ":host");
7499 DEFSYM (QCservice, ":service");
7500 DEFSYM (QClocal, ":local");
7501 DEFSYM (QCremote, ":remote");
7502 DEFSYM (QCcoding, ":coding");
7503 DEFSYM (QCserver, ":server");
7504 DEFSYM (QCnowait, ":nowait");
7505 DEFSYM (QCsentinel, ":sentinel");
7506 DEFSYM (QClog, ":log");
7507 DEFSYM (QCnoquery, ":noquery");
7508 DEFSYM (QCstop, ":stop");
7509 DEFSYM (QCplist, ":plist");
7510 DEFSYM (QCcommand, ":command");
7511 DEFSYM (QCconnection_type, ":connection-type");
7512 DEFSYM (QCstderr, ":stderr");
7513 DEFSYM (Qpty, "pty");
7514 DEFSYM (Qpipe, "pipe");
7515
7516 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7517
7518 staticpro (&Vprocess_alist);
7519 staticpro (&deleted_pid_list);
7520
7521 #endif /* subprocesses */
7522
7523 DEFSYM (QCname, ":name");
7524 DEFSYM (QCtype, ":type");
7525
7526 DEFSYM (Qeuid, "euid");
7527 DEFSYM (Qegid, "egid");
7528 DEFSYM (Quser, "user");
7529 DEFSYM (Qgroup, "group");
7530 DEFSYM (Qcomm, "comm");
7531 DEFSYM (Qstate, "state");
7532 DEFSYM (Qppid, "ppid");
7533 DEFSYM (Qpgrp, "pgrp");
7534 DEFSYM (Qsess, "sess");
7535 DEFSYM (Qttname, "ttname");
7536 DEFSYM (Qtpgid, "tpgid");
7537 DEFSYM (Qminflt, "minflt");
7538 DEFSYM (Qmajflt, "majflt");
7539 DEFSYM (Qcminflt, "cminflt");
7540 DEFSYM (Qcmajflt, "cmajflt");
7541 DEFSYM (Qutime, "utime");
7542 DEFSYM (Qstime, "stime");
7543 DEFSYM (Qtime, "time");
7544 DEFSYM (Qcutime, "cutime");
7545 DEFSYM (Qcstime, "cstime");
7546 DEFSYM (Qctime, "ctime");
7547 #ifdef subprocesses
7548 DEFSYM (Qinternal_default_process_sentinel,
7549 "internal-default-process-sentinel");
7550 DEFSYM (Qinternal_default_process_filter,
7551 "internal-default-process-filter");
7552 #endif
7553 DEFSYM (Qpri, "pri");
7554 DEFSYM (Qnice, "nice");
7555 DEFSYM (Qthcount, "thcount");
7556 DEFSYM (Qstart, "start");
7557 DEFSYM (Qvsize, "vsize");
7558 DEFSYM (Qrss, "rss");
7559 DEFSYM (Qetime, "etime");
7560 DEFSYM (Qpcpu, "pcpu");
7561 DEFSYM (Qpmem, "pmem");
7562 DEFSYM (Qargs, "args");
7563
7564 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7565 doc: /* Non-nil means delete processes immediately when they exit.
7566 A value of nil means don't delete them until `list-processes' is run. */);
7567
7568 delete_exited_processes = 1;
7569
7570 #ifdef subprocesses
7571 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7572 doc: /* Control type of device used to communicate with subprocesses.
7573 Values are nil to use a pipe, or t or `pty' to use a pty.
7574 The value has no effect if the system has no ptys or if all ptys are busy:
7575 then a pipe is used in any case.
7576 The value takes effect when `start-process' is called. */);
7577 Vprocess_connection_type = Qt;
7578
7579 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7580 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7581 On some systems, when Emacs reads the output from a subprocess, the output data
7582 is read in very small blocks, potentially resulting in very poor performance.
7583 This behavior can be remedied to some extent by setting this variable to a
7584 non-nil value, as it will automatically delay reading from such processes, to
7585 allow them to produce more output before Emacs tries to read it.
7586 If the value is t, the delay is reset after each write to the process; any other
7587 non-nil value means that the delay is not reset on write.
7588 The variable takes effect when `start-process' is called. */);
7589 Vprocess_adaptive_read_buffering = Qt;
7590
7591 defsubr (&Sprocessp);
7592 defsubr (&Sget_process);
7593 defsubr (&Sdelete_process);
7594 defsubr (&Sprocess_status);
7595 defsubr (&Sprocess_exit_status);
7596 defsubr (&Sprocess_id);
7597 defsubr (&Sprocess_name);
7598 defsubr (&Sprocess_tty_name);
7599 defsubr (&Sprocess_command);
7600 defsubr (&Sset_process_buffer);
7601 defsubr (&Sprocess_buffer);
7602 defsubr (&Sprocess_mark);
7603 defsubr (&Sset_process_filter);
7604 defsubr (&Sprocess_filter);
7605 defsubr (&Sset_process_sentinel);
7606 defsubr (&Sprocess_sentinel);
7607 defsubr (&Sset_process_window_size);
7608 defsubr (&Sset_process_inherit_coding_system_flag);
7609 defsubr (&Sset_process_query_on_exit_flag);
7610 defsubr (&Sprocess_query_on_exit_flag);
7611 defsubr (&Sprocess_contact);
7612 defsubr (&Sprocess_plist);
7613 defsubr (&Sset_process_plist);
7614 defsubr (&Sprocess_list);
7615 defsubr (&Smake_process);
7616 defsubr (&Smake_pipe_process);
7617 defsubr (&Sserial_process_configure);
7618 defsubr (&Smake_serial_process);
7619 defsubr (&Sset_network_process_option);
7620 defsubr (&Smake_network_process);
7621 defsubr (&Sformat_network_address);
7622 defsubr (&Snetwork_interface_list);
7623 defsubr (&Snetwork_interface_info);
7624 #ifdef DATAGRAM_SOCKETS
7625 defsubr (&Sprocess_datagram_address);
7626 defsubr (&Sset_process_datagram_address);
7627 #endif
7628 defsubr (&Saccept_process_output);
7629 defsubr (&Sprocess_send_region);
7630 defsubr (&Sprocess_send_string);
7631 defsubr (&Sinterrupt_process);
7632 defsubr (&Skill_process);
7633 defsubr (&Squit_process);
7634 defsubr (&Sstop_process);
7635 defsubr (&Scontinue_process);
7636 defsubr (&Sprocess_running_child_p);
7637 defsubr (&Sprocess_send_eof);
7638 defsubr (&Ssignal_process);
7639 defsubr (&Swaiting_for_user_input_p);
7640 defsubr (&Sprocess_type);
7641 defsubr (&Sinternal_default_process_sentinel);
7642 defsubr (&Sinternal_default_process_filter);
7643 defsubr (&Sset_process_coding_system);
7644 defsubr (&Sprocess_coding_system);
7645 defsubr (&Sset_process_filter_multibyte);
7646 defsubr (&Sprocess_filter_multibyte_p);
7647
7648 #endif /* subprocesses */
7649
7650 defsubr (&Sget_buffer_process);
7651 defsubr (&Sprocess_inherit_coding_system_flag);
7652 defsubr (&Slist_system_processes);
7653 defsubr (&Sprocess_attributes);
7654
7655 {
7656 Lisp_Object subfeatures = Qnil;
7657 const struct socket_options *sopt;
7658
7659 #define ADD_SUBFEATURE(key, val) \
7660 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7661
7662 #ifdef NON_BLOCKING_CONNECT
7663 ADD_SUBFEATURE (QCnowait, Qt);
7664 #endif
7665 #ifdef DATAGRAM_SOCKETS
7666 ADD_SUBFEATURE (QCtype, Qdatagram);
7667 #endif
7668 #ifdef HAVE_SEQPACKET
7669 ADD_SUBFEATURE (QCtype, Qseqpacket);
7670 #endif
7671 #ifdef HAVE_LOCAL_SOCKETS
7672 ADD_SUBFEATURE (QCfamily, Qlocal);
7673 #endif
7674 ADD_SUBFEATURE (QCfamily, Qipv4);
7675 #ifdef AF_INET6
7676 ADD_SUBFEATURE (QCfamily, Qipv6);
7677 #endif
7678 #ifdef HAVE_GETSOCKNAME
7679 ADD_SUBFEATURE (QCservice, Qt);
7680 #endif
7681 ADD_SUBFEATURE (QCserver, Qt);
7682
7683 for (sopt = socket_options; sopt->name; sopt++)
7684 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7685
7686 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7687 }
7688
7689 }