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