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