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