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