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