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