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