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