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