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