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