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