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