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