Use common memory management functions for lwlib and refactor users.
[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]);
194b4d9f 4633 if (p && p->gnutls_p && p->gnutls_state && p->infd
5b76caa4
PE
4634 && ((emacs_gnutls_record_check_pending
4635 (p->gnutls_state))
4636 > 0))
4637 {
4638 nfds++;
4639 FD_SET (p->infd, &Available);
4640 }
4641 }
261b6fd4
LMI
4642 }
4643 else
4644 {
4645 /* Check this specific channel. */
5b76caa4 4646 if (wait_proc->gnutls_p /* Check for valid process. */
69369809 4647 && wait_proc->gnutls_state
261b6fd4 4648 /* Do we have pending data? */
5b76caa4
PE
4649 && ((emacs_gnutls_record_check_pending
4650 (wait_proc->gnutls_state))
4651 > 0))
261b6fd4
LMI
4652 {
4653 nfds = 1;
4654 /* Set to Available. */
4655 FD_SET (wait_proc->infd, &Available);
4656 }
4657 }
4658 }
e061a11b 4659#endif
dd2a17ab 4660 }
6720a7fb 4661
d0d6b7c5
JB
4662 xerrno = errno;
4663
4664 /* Make C-g and alarm signals set flags again */
4665 clear_waiting_for_input ();
4666
4667 /* If we woke up due to SIGWINCH, actually change size now. */
2b653806 4668 do_pending_window_change (0);
d0d6b7c5 4669
209c6a58
CY
4670 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4671 /* We waited the full specified time, so return now. */
4672 break;
d0d6b7c5
JB
4673 if (nfds < 0)
4674 {
4675 if (xerrno == EINTR)
dd2a17ab 4676 no_avail = 1;
d0d6b7c5 4677 else if (xerrno == EBADF)
7e649856 4678 emacs_abort ();
d0d6b7c5 4679 else
4e604a5d 4680 report_file_errno ("Failed select", Qnil, xerrno);
d0d6b7c5 4681 }
dd2a17ab
KS
4682
4683 if (no_avail)
4684 {
4685 FD_ZERO (&Available);
3fad2ad2 4686 check_write = 0;
dd2a17ab
KS
4687 }
4688
d0d6b7c5
JB
4689 /* Check for keyboard input */
4690 /* If there is any, return immediately
4691 to give it higher priority than subprocesses */
4692
b89a415a 4693 if (read_kbd != 0)
6ed6233b 4694 {
9fa1de30 4695 unsigned old_timers_run = timers_run;
c88164fe 4696 struct buffer *old_buffer = current_buffer;
c0323133 4697 Lisp_Object old_window = selected_window;
0bce5d9e 4698 bool leave = 0;
177c0ea7 4699
5d6c2aa3 4700 if (detect_input_pending_run_timers (do_display))
a2fab450
GM
4701 {
4702 swallow_events (do_display);
4703 if (detect_input_pending_run_timers (do_display))
4704 leave = 1;
4705 }
6ed6233b 4706
a2fab450
GM
4707 /* If a timer has run, this might have changed buffers
4708 an alike. Make read_key_sequence aware of that. */
4709 if (timers_run != old_timers_run
c88164fe 4710 && waiting_for_user_input_p == -1
c0323133
GM
4711 && (old_buffer != current_buffer
4712 || !EQ (old_window, selected_window)))
a2fab450
GM
4713 record_asynch_buffer_change ();
4714
4715 if (leave)
4716 break;
177c0ea7
JB
4717 }
4718
69645afc 4719 /* If there is unread keyboard input, also return. */
b89a415a 4720 if (read_kbd != 0
69645afc
RS
4721 && requeued_events_pending_p ())
4722 break;
4723
77e1b3d4
RS
4724 /* If we are not checking for keyboard input now,
4725 do process events (but don't run any timers).
4726 This is so that X events will be processed.
0c9960e9 4727 Otherwise they may have to wait until polling takes place.
77e1b3d4
RS
4728 That would causes delays in pasting selections, for example.
4729
4730 (We used to do this only if wait_for_cell.) */
b89a415a 4731 if (read_kbd == 0 && detect_input_pending ())
f854a00b
RS
4732 {
4733 swallow_events (do_display);
0c9960e9 4734#if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
f854a00b
RS
4735 if (detect_input_pending ())
4736 break;
5d5beb62 4737#endif
0c9960e9 4738 }
f854a00b 4739
84aa3ace 4740 /* Exit now if the cell we're waiting for became non-nil. */
f3fbd155 4741 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
84aa3ace
RS
4742 break;
4743
4a4bbad2 4744#ifdef USABLE_SIGIO
5d5beb62 4745 /* If we think we have keyboard input waiting, but didn't get SIGIO,
d0d6b7c5
JB
4746 go read it. This can happen with X on BSD after logging out.
4747 In that case, there really is no input and no SIGIO,
4748 but select says there is input. */
4749
b89a415a 4750 if (read_kbd && interrupt_input
2601f59e 4751 && keyboard_bit_set (&Available) && ! noninteractive)
4d7e6e51 4752 handle_input_available_signal (SIGIO);
4746118a 4753#endif
d0d6b7c5 4754
d0d6b7c5
JB
4755 if (! wait_proc)
4756 got_some_input |= nfds > 0;
4757
32676c08
JB
4758 /* If checking input just got us a size-change event from X,
4759 obey it now if we should. */
b89a415a 4760 if (read_kbd || ! NILP (wait_for_cell))
2b653806 4761 do_pending_window_change (0);
32676c08 4762
a9f2c884 4763 /* Check for data from a process. */
dd2a17ab
KS
4764 if (no_avail || nfds == 0)
4765 continue;
4766
3fad2ad2
J
4767 for (channel = 0; channel <= max_input_desc; ++channel)
4768 {
4769 struct fd_callback_data *d = &fd_callback_info[channel];
de1339b0
PE
4770 if (d->func
4771 && ((d->condition & FOR_READ
4772 && FD_ISSET (channel, &Available))
4773 || (d->condition & FOR_WRITE
4774 && FD_ISSET (channel, &write_mask))))
4775 d->func (channel, d->data);
4776 }
3fad2ad2 4777
a69281ff 4778 for (channel = 0; channel <= max_process_desc; channel++)
d0d6b7c5 4779 {
a69281ff 4780 if (FD_ISSET (channel, &Available)
3fad2ad2
J
4781 && FD_ISSET (channel, &non_keyboard_wait_mask)
4782 && !FD_ISSET (channel, &non_process_wait_mask))
d0d6b7c5
JB
4783 {
4784 int nread;
4785
4786 /* If waiting for this channel, arrange to return as
4787 soon as no more input to be processed. No more
4788 waiting. */
4789 if (wait_channel == channel)
4790 {
a9f2c884 4791 wait_channel = -1;
d35af63c 4792 nsecs = -1;
d0d6b7c5
JB
4793 got_some_input = 1;
4794 }
4795 proc = chan_process[channel];
4796 if (NILP (proc))
4797 continue;
4798
e690ca94 4799 /* If this is a server stream socket, accept connection. */
4d2b044c 4800 if (EQ (XPROCESS (proc)->status, Qlisten))
e690ca94
KS
4801 {
4802 server_accept_connection (proc, channel);
4803 continue;
4804 }
4805
d0d6b7c5
JB
4806 /* Read data from the process, starting with our
4807 buffered-ahead character if we have one. */
4808
4809 nread = read_process_output (proc, channel);
4810 if (nread > 0)
4811 {
4812 /* Since read_process_output can run a filter,
4813 which can call accept-process-output,
4814 don't try to read from any other processes
4815 before doing the select again. */
4816 FD_ZERO (&Available);
4817
4818 if (do_display)
3007ebfb 4819 redisplay_preserve_echo_area (12);
d0d6b7c5
JB
4820 }
4821#ifdef EWOULDBLOCK
4822 else if (nread == -1 && errno == EWOULDBLOCK)
4823 ;
0b75e9a4 4824#endif
d0d6b7c5
JB
4825 else if (nread == -1 && errno == EAGAIN)
4826 ;
49cdacda
PE
4827#ifdef WINDOWSNT
4828 /* FIXME: Is this special case still needed? */
d0d6b7c5
JB
4829 /* Note that we cannot distinguish between no input
4830 available now and a closed pipe.
4831 With luck, a closed pipe will be accompanied by
4832 subprocess termination and SIGCHLD. */
d888760c 4833 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
d0d6b7c5 4834 ;
49cdacda 4835#endif
d0d6b7c5
JB
4836#ifdef HAVE_PTYS
4837 /* On some OSs with ptys, when the process on one end of
4838 a pty exits, the other end gets an error reading with
4839 errno = EIO instead of getting an EOF (0 bytes read).
4840 Therefore, if we get an error reading and errno =
4841 EIO, just continue, because the child process has
4842 exited and should clean itself up soon (e.g. when we
207a7ef0 4843 get a SIGCHLD). */
d0d6b7c5 4844 else if (nread == -1 && errno == EIO)
4740825c 4845 {
f30d612a
CY
4846 struct Lisp_Process *p = XPROCESS (proc);
4847
4848 /* Clear the descriptor now, so we only raise the
4849 signal once. */
4850 FD_CLR (channel, &input_wait_mask);
4851 FD_CLR (channel, &non_keyboard_wait_mask);
4852
4853 if (p->pid == -2)
4854 {
20ef56db
PE
4855 /* If the EIO occurs on a pty, the SIGCHLD handler's
4856 waitpid call will not find the process object to
f30d612a
CY
4857 delete. Do it here. */
4858 p->tick = ++process_tick;
6a09a33b 4859 pset_status (p, Qfailed);
f30d612a 4860 }
4740825c
KS
4861 }
4862#endif /* HAVE_PTYS */
5063c0e1
TN
4863 /* If we can detect process termination, don't consider the
4864 process gone just because its pipe is closed. */
d888760c 4865 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
d0d6b7c5 4866 ;
d0d6b7c5
JB
4867 else
4868 {
4869 /* Preserve status of processes already terminated. */
60f0fb11 4870 XPROCESS (proc)->tick = ++process_tick;
d0d6b7c5 4871 deactivate_process (proc);
6bfd98e7 4872 if (XPROCESS (proc)->raw_status_new)
d0d6b7c5 4873 update_status (XPROCESS (proc));
4d2b044c 4874 if (EQ (XPROCESS (proc)->status, Qrun))
6a09a33b
PE
4875 pset_status (XPROCESS (proc),
4876 list2 (Qexit, make_number (256)));
d0d6b7c5
JB
4877 }
4878 }
177c0ea7 4879#ifdef NON_BLOCKING_CONNECT
3fad2ad2 4880 if (FD_ISSET (channel, &Writeok)
1566f511 4881 && FD_ISSET (channel, &connect_wait_mask))
dd2a17ab
KS
4882 {
4883 struct Lisp_Process *p;
dd2a17ab
KS
4884
4885 FD_CLR (channel, &connect_wait_mask);
d8a4b27a 4886 FD_CLR (channel, &write_mask);
dd2a17ab 4887 if (--num_pending_connects < 0)
1088b922 4888 emacs_abort ();
dd2a17ab
KS
4889
4890 proc = chan_process[channel];
4891 if (NILP (proc))
4892 continue;
4893
4894 p = XPROCESS (proc);
4895
4896#ifdef GNU_LINUX
4897 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
63136da6 4898 So only use it on systems where it is known to work. */
dd2a17ab 4899 {
401bf9b4 4900 socklen_t xlen = sizeof (xerrno);
ed3751c8 4901 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
dd2a17ab
KS
4902 xerrno = errno;
4903 }
4904#else
44c887be
PJ
4905 {
4906 struct sockaddr pname;
fb83ea63 4907 socklen_t pnamelen = sizeof (pname);
44c887be
PJ
4908
4909 /* If connection failed, getpeername will fail. */
4910 xerrno = 0;
ed3751c8 4911 if (getpeername (channel, &pname, &pnamelen) < 0)
44c887be
PJ
4912 {
4913 /* Obtain connect failure code through error slippage. */
4914 char dummy;
dd2a17ab 4915 xerrno = errno;
ed3751c8 4916 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
44c887be
PJ
4917 xerrno = errno;
4918 }
4919 }
dd2a17ab
KS
4920#endif
4921 if (xerrno)
4922 {
60f0fb11 4923 p->tick = ++process_tick;
6a09a33b 4924 pset_status (p, list2 (Qfailed, make_number (xerrno)));
dd2a17ab
KS
4925 deactivate_process (proc);
4926 }
4927 else
4928 {
6a09a33b 4929 pset_status (p, Qrun);
dd2a17ab
KS
4930 /* Execute the sentinel here. If we had relied on
4931 status_notify to do it later, it will read input
4932 from the process before calling the sentinel. */
4933 exec_sentinel (proc, build_string ("open\n"));
4d2b044c 4934 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
dd2a17ab 4935 {
60f0fb11
SM
4936 FD_SET (p->infd, &input_wait_mask);
4937 FD_SET (p->infd, &non_keyboard_wait_mask);
dd2a17ab
KS
4938 }
4939 }
4940 }
4941#endif /* NON_BLOCKING_CONNECT */
1aa8d505
SM
4942 } /* End for each file descriptor. */
4943 } /* End while exit conditions not met. */
d0d6b7c5 4944
2beb96f9 4945 unbind_to (count, Qnil);
d430ee71 4946
ffd56f97
JB
4947 /* If calling from keyboard input, do not quit
4948 since we want to return C-g as an input character.
4949 Otherwise, do pending quit if requested. */
b89a415a 4950 if (read_kbd >= 0)
ffd56f97
JB
4951 {
4952 /* Prevent input_pending from remaining set if we quit. */
4953 clear_input_pending ();
4954 QUIT;
4955 }
efa2a55c 4956
d0d6b7c5
JB
4957 return got_some_input;
4958}
4959\f
3b9a3dfa
RS
4960/* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4961
4962static Lisp_Object
d3da34e0 4963read_process_output_call (Lisp_Object fun_and_args)
3b9a3dfa 4964{
70949dac 4965 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
3b9a3dfa
RS
4966}
4967
4968static Lisp_Object
b93aacde 4969read_process_output_error_handler (Lisp_Object error_val)
3b9a3dfa 4970{
b93aacde 4971 cmd_error_internal (error_val, "error in process filter: ");
3b9a3dfa
RS
4972 Vinhibit_quit = Qt;
4973 update_echo_area ();
833ba342 4974 Fsleep_for (make_number (2), Qnil);
8c983bf2 4975 return Qt;
3b9a3dfa
RS
4976}
4977
1aa8d505
SM
4978static void
4979read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4980 ssize_t nbytes,
4981 struct coding_system *coding);
4982
d0d6b7c5
JB
4983/* Read pending output from the process channel,
4984 starting with our buffered-ahead character if we have one.
0fa1789e 4985 Yield number of decoded characters read.
d0d6b7c5 4986
116c423c 4987 This function reads at most 4096 characters.
d0d6b7c5 4988 If you want to read all available subprocess output,
0fa1789e
KH
4989 you must call it repeatedly until it returns zero.
4990
4991 The characters read are decoded according to PROC's coding-system
4992 for decoding. */
d0d6b7c5 4993
ff6daed3 4994static int
d3da34e0 4995read_process_output (Lisp_Object proc, register int channel)
d0d6b7c5 4996{
368f4090 4997 register ssize_t nbytes;
d0d6b7c5 4998 char *chars;
d0d6b7c5 4999 register struct Lisp_Process *p = XPROCESS (proc);
c7580538 5000 struct coding_system *coding = proc_decode_coding_system[channel];
60f0fb11 5001 int carryover = p->decoding_carryover;
116c423c 5002 int readmax = 4096;
d311d28c 5003 ptrdiff_t count = SPECPDL_INDEX ();
3a4fa2f2 5004 Lisp_Object odeactivate;
d0d6b7c5 5005
38182d90 5006 chars = alloca (carryover + readmax);
e7fbaa65
KH
5007 if (carryover)
5008 /* See the comment above. */
4d2b044c 5009 memcpy (chars, SDATA (p->decoding_buf), carryover);
0fa1789e 5010
e690ca94
KS
5011#ifdef DATAGRAM_SOCKETS
5012 /* We have a working select, so proc_buffered_char is always -1. */
5013 if (DATAGRAM_CHAN_P (channel))
5014 {
401bf9b4 5015 socklen_t len = datagram_address[channel].len;
39b1da20 5016 nbytes = recvfrom (channel, chars + carryover, readmax,
e690ca94
KS
5017 0, datagram_address[channel].sa, &len);
5018 }
5019 else
5020#endif
6b61353c 5021 {
908589fd 5022 bool buffered = proc_buffered_char[channel] >= 0;
82eaa333
PE
5023 if (buffered)
5024 {
5025 chars[carryover] = proc_buffered_char[channel];
5026 proc_buffered_char[channel] = -1;
5027 }
8af55556 5028#ifdef HAVE_GNUTLS
194b4d9f 5029 if (p->gnutls_p && p->gnutls_state)
959ad23f 5030 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
82eaa333 5031 readmax - buffered);
8af55556
TZ
5032 else
5033#endif
82eaa333
PE
5034 nbytes = emacs_read (channel, chars + carryover + buffered,
5035 readmax - buffered);
6b61353c 5036#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11 5037 if (nbytes > 0 && p->adaptive_read_buffering)
6b61353c 5038 {
60f0fb11 5039 int delay = p->read_output_delay;
6b61353c
KH
5040 if (nbytes < 256)
5041 {
5042 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5043 {
5044 if (delay == 0)
5045 process_output_delay_count++;
5046 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5047 }
5048 }
82eaa333 5049 else if (delay > 0 && nbytes == readmax - buffered)
6b61353c
KH
5050 {
5051 delay -= READ_OUTPUT_DELAY_INCREMENT;
5052 if (delay == 0)
5053 process_output_delay_count--;
5054 }
60f0fb11 5055 p->read_output_delay = delay;
6b61353c
KH
5056 if (delay)
5057 {
60f0fb11 5058 p->read_output_skip = 1;
6b61353c
KH
5059 process_output_skip = 1;
5060 }
5061 }
5062#endif
fe07cdfa
PE
5063 nbytes += buffered;
5064 nbytes += buffered && nbytes <= 0;
d0d6b7c5 5065 }
d0d6b7c5 5066
60f0fb11 5067 p->decoding_carryover = 0;
ca65341e 5068
ed7a4b2d 5069 /* At this point, NBYTES holds number of bytes just received
0fa1789e 5070 (including the one in proc_buffered_char[channel]). */
de7fbd09
KH
5071 if (nbytes <= 0)
5072 {
5073 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5074 return nbytes;
5075 coding->mode |= CODING_MODE_LAST_BLOCK;
5076 }
d0d6b7c5 5077
1d2fc612 5078 /* Now set NBYTES how many bytes we must decode. */
e7fbaa65 5079 nbytes += carryover;
0fa1789e 5080
3a4fa2f2
SM
5081 odeactivate = Vdeactivate_mark;
5082 /* There's no good reason to let process filters change the current
5083 buffer, and many callers of accept-process-output, sit-for, and
5084 friends don't expect current-buffer to be changed from under them. */
66322887 5085 record_unwind_current_buffer ();
3a4fa2f2 5086
1aa8d505
SM
5087 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5088
5089 /* Handling the process output should not deactivate the mark. */
5090 Vdeactivate_mark = odeactivate;
5091
5092 unbind_to (count, Qnil);
5093 return nbytes;
5094}
5095
5096static void
5097read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5098 ssize_t nbytes,
5099 struct coding_system *coding)
5100{
5101 Lisp_Object outstream = p->filter;
5102 Lisp_Object text;
5103 bool outer_running_asynch_code = running_asynch_code;
5104 int waiting = waiting_for_user_input_p;
30c78175 5105
1aa8d505
SM
5106 /* No need to gcpro these, because all we do with them later
5107 is test them for EQness, and none of them should be a string. */
aba7731a 5108#if 0
1aa8d505
SM
5109 Lisp_Object obuffer, okeymap;
5110 XSETBUFFER (obuffer, current_buffer);
5111 okeymap = BVAR (current_buffer, keymap);
aba7731a 5112#endif
30c78175 5113
1aa8d505
SM
5114 /* We inhibit quit here instead of just catching it so that
5115 hitting ^G when a filter happens to be running won't screw
5116 it up. */
5117 specbind (Qinhibit_quit, Qt);
5118 specbind (Qlast_nonmenu_event, Qt);
4da2f5be 5119
1aa8d505
SM
5120 /* In case we get recursively called,
5121 and we already saved the match data nonrecursively,
5122 save the same match data in safely recursive fashion. */
5123 if (outer_running_asynch_code)
5124 {
5125 Lisp_Object tem;
5126 /* Don't clobber the CURRENT match data, either! */
5127 tem = Fmatch_data (Qnil, Qnil, Qnil);
5128 restore_search_regs ();
5129 record_unwind_save_match_data ();
5130 Fset_match_data (tem, Qt);
5131 }
4da2f5be 5132
1aa8d505
SM
5133 /* For speed, if a search happens within this code,
5134 save the match data in a special nonrecursive fashion. */
5135 running_asynch_code = 1;
ed7a4b2d 5136
1aa8d505
SM
5137 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5138 text = coding->dst_object;
5139 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5140 /* A new coding system might be found. */
5141 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5142 {
5143 pset_decode_coding_system (p, Vlast_coding_system_used);
ed7a4b2d 5144
1aa8d505
SM
5145 /* Don't call setup_coding_system for
5146 proc_decode_coding_system[channel] here. It is done in
5147 detect_coding called via decode_coding above. */
ed7a4b2d 5148
1aa8d505
SM
5149 /* If a coding system for encoding is not yet decided, we set
5150 it as the same as coding-system for decoding.
51c6067d 5151
1aa8d505
SM
5152 But, before doing that we must check if
5153 proc_encode_coding_system[p->outfd] surely points to a
5154 valid memory because p->outfd will be changed once EOF is
5155 sent to the process. */
5156 if (NILP (p->encode_coding_system)
5157 && proc_encode_coding_system[p->outfd])
dd8c7a53 5158 {
1aa8d505
SM
5159 pset_encode_coding_system
5160 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5161 setup_coding_system (p->encode_coding_system,
5162 proc_encode_coding_system[p->outfd]);
dd8c7a53 5163 }
1aa8d505 5164 }
d0d6b7c5 5165
1aa8d505
SM
5166 if (coding->carryover_bytes > 0)
5167 {
5168 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5169 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5170 memcpy (SDATA (p->decoding_buf), coding->carryover,
5171 coding->carryover_bytes);
5172 p->decoding_carryover = coding->carryover_bytes;
5173 }
5174 if (SBYTES (text) > 0)
5175 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5176 sometimes it's simply wrong to wrap (e.g. when called from
5177 accept-process-output). */
5178 internal_condition_case_1 (read_process_output_call,
6c6f1994 5179 list3 (outstream, make_lisp_proc (p), text),
1aa8d505
SM
5180 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5181 read_process_output_error_handler);
5182
5183 /* If we saved the match data nonrecursively, restore it now. */
5184 restore_search_regs ();
5185 running_asynch_code = outer_running_asynch_code;
5186
5187 /* Restore waiting_for_user_input_p as it was
5188 when we were called, in case the filter clobbered it. */
5189 waiting_for_user_input_p = waiting;
bbce7d72 5190
7973cfa8
RS
5191#if 0 /* Call record_asynch_buffer_change unconditionally,
5192 because we might have changed minor modes or other things
5193 that affect key bindings. */
1aa8d505
SM
5194 if (! EQ (Fcurrent_buffer (), obuffer)
5195 || ! EQ (current_buffer->keymap, okeymap))
5196#endif
5197 /* But do it only if the caller is actually going to read events.
5198 Otherwise there's no need to make him wake up, and it could
5199 cause trouble (for example it would make sit_for return). */
5200 if (waiting_for_user_input_p == -1)
5201 record_asynch_buffer_change ();
5202}
5203
5204DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5205 Sinternal_default_process_filter, 2, 2, 0,
458e643b 5206 doc: /* Function used as default process filter.
f33095ed
GM
5207This inserts the process's output into its buffer, if there is one.
5208Otherwise it discards the output. */)
1aa8d505
SM
5209 (Lisp_Object proc, Lisp_Object text)
5210{
5211 struct Lisp_Process *p;
5212 ptrdiff_t opoint;
d0d6b7c5 5213
1aa8d505
SM
5214 CHECK_PROCESS (proc);
5215 p = XPROCESS (proc);
5216 CHECK_STRING (text);
5217
5218 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
d0d6b7c5 5219 {
b0310da4 5220 Lisp_Object old_read_only;
d311d28c
PE
5221 ptrdiff_t old_begv, old_zv;
5222 ptrdiff_t old_begv_byte, old_zv_byte;
5223 ptrdiff_t before, before_byte;
5224 ptrdiff_t opoint_byte;
926b7e5e 5225 struct buffer *b;
30c78175 5226
4d2b044c 5227 Fset_buffer (p->buffer);
6ec8bbd2 5228 opoint = PT;
d8a2934e 5229 opoint_byte = PT_BYTE;
4b4deea2 5230 old_read_only = BVAR (current_buffer, read_only);
12ca5cdf
RS
5231 old_begv = BEGV;
5232 old_zv = ZV;
d8a2934e
RS
5233 old_begv_byte = BEGV_BYTE;
5234 old_zv_byte = ZV_BYTE;
b0310da4 5235
39eb03f1 5236 bset_read_only (current_buffer, Qnil);
d0d6b7c5 5237
032f7451
DA
5238 /* Insert new output into buffer at the current end-of-output
5239 marker, thus preserving logical ordering of input and output. */
4d2b044c 5240 if (XMARKER (p->mark)->buffer)
032f7451 5241 set_point_from_marker (p->mark);
d0d6b7c5 5242 else
d8a2934e 5243 SET_PT_BOTH (ZV, ZV_BYTE);
12ca5cdf 5244 before = PT;
d8a2934e 5245 before_byte = PT_BYTE;
b0310da4
JB
5246
5247 /* If the output marker is outside of the visible region, save
5248 the restriction and widen. */
6ec8bbd2 5249 if (! (BEGV <= PT && PT <= ZV))
b0310da4
JB
5250 Fwiden ();
5251
d69864bf 5252 /* Adjust the multibyteness of TEXT to that of the buffer. */
4b4deea2 5253 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
d69864bf
KH
5254 != ! STRING_MULTIBYTE (text))
5255 text = (STRING_MULTIBYTE (text)
57bb5c37 5256 ? Fstring_as_unibyte (text)
03f04413 5257 : Fstring_to_multibyte (text));
57bb5c37
KH
5258 /* Insert before markers in case we are inserting where
5259 the buffer's mark is, and the user's next command is Meta-y. */
e430e5ba
KH
5260 insert_from_string_before_markers (text, 0, 0,
5261 SCHARS (text), SBYTES (text), 0);
0d023da1 5262
926b7e5e
GM
5263 /* Make sure the process marker's position is valid when the
5264 process buffer is changed in the signal_after_change above.
5265 W3 is known to do that. */
4d2b044c
DA
5266 if (BUFFERP (p->buffer)
5267 && (b = XBUFFER (p->buffer), b != current_buffer))
5268 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
926b7e5e 5269 else
4d2b044c 5270 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
b0310da4 5271
2ec9db5d 5272 update_mode_lines = 23;
d0d6b7c5 5273
12ca5cdf
RS
5274 /* Make sure opoint and the old restrictions
5275 float ahead of any new text just as point would. */
5276 if (opoint >= before)
d8a2934e
RS
5277 {
5278 opoint += PT - before;
5279 opoint_byte += PT_BYTE - before_byte;
5280 }
12ca5cdf 5281 if (old_begv > before)
d8a2934e
RS
5282 {
5283 old_begv += PT - before;
5284 old_begv_byte += PT_BYTE - before_byte;
5285 }
12ca5cdf 5286 if (old_zv >= before)
d8a2934e
RS
5287 {
5288 old_zv += PT - before;
5289 old_zv_byte += PT_BYTE - before_byte;
5290 }
12ca5cdf 5291
b0310da4 5292 /* If the restriction isn't what it should be, set it. */
12ca5cdf
RS
5293 if (old_begv != BEGV || old_zv != ZV)
5294 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
b0310da4 5295
39eb03f1 5296 bset_read_only (current_buffer, old_read_only);
d8a2934e 5297 SET_PT_BOTH (opoint, opoint_byte);
d0d6b7c5 5298 }
1aa8d505 5299 return Qnil;
d0d6b7c5 5300}
d0d6b7c5 5301\f
1aa8d505 5302/* Sending data to subprocess. */
d0d6b7c5 5303
20ca2e94
TN
5304/* In send_process, when a write fails temporarily,
5305 wait_reading_process_output is called. It may execute user code,
5306 e.g. timers, that attempts to write new data to the same process.
5307 We must ensure that data is sent in the right order, and not
5308 interspersed half-completed with other writes (Bug#10815). This is
5309 handled by the write_queue element of struct process. It is a list
5310 with each entry having the form
5311
5312 (string . (offset . length))
5313
5314 where STRING is a lisp string, OFFSET is the offset into the
5315 string's byte sequence from which we should begin to send, and
5316 LENGTH is the number of bytes left to send. */
5317
5318/* Create a new entry in write_queue.
5319 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5320 BUF is a pointer to the string sequence of the input_obj or a C
5321 string in case of Qt or Qnil. */
5322
5323static void
5324write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
0bce5d9e 5325 const char *buf, ptrdiff_t len, bool front)
20ca2e94 5326{
7ea2b339 5327 ptrdiff_t offset;
20ca2e94
TN
5328 Lisp_Object entry, obj;
5329
5330 if (STRINGP (input_obj))
5331 {
5332 offset = buf - SSDATA (input_obj);
5333 obj = input_obj;
5334 }
5335 else
5336 {
5337 offset = 0;
5338 obj = make_unibyte_string (buf, len);
5339 }
5340
5341 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5342
5343 if (front)
6a09a33b 5344 pset_write_queue (p, Fcons (entry, p->write_queue));
20ca2e94 5345 else
6c6f1994 5346 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
20ca2e94
TN
5347}
5348
5349/* Remove the first element in the write_queue of process P, put its
0bce5d9e
PE
5350 contents in OBJ, BUF and LEN, and return true. If the
5351 write_queue is empty, return false. */
20ca2e94 5352
0bce5d9e 5353static bool
20ca2e94 5354write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
7ea2b339 5355 const char **buf, ptrdiff_t *len)
20ca2e94
TN
5356{
5357 Lisp_Object entry, offset_length;
7ea2b339 5358 ptrdiff_t offset;
20ca2e94 5359
4d2b044c 5360 if (NILP (p->write_queue))
20ca2e94
TN
5361 return 0;
5362
4d2b044c 5363 entry = XCAR (p->write_queue);
6a09a33b 5364 pset_write_queue (p, XCDR (p->write_queue));
20ca2e94
TN
5365
5366 *obj = XCAR (entry);
5367 offset_length = XCDR (entry);
5368
5369 *len = XINT (XCDR (offset_length));
5370 offset = XINT (XCAR (offset_length));
7ea2b339 5371 *buf = SSDATA (*obj) + offset;
20ca2e94
TN
5372
5373 return 1;
5374}
5375
4556b700
RS
5376/* Send some data to process PROC.
5377 BUF is the beginning of the data; LEN is the number of characters.
a92e4183
KH
5378 OBJECT is the Lisp object that the data comes from. If OBJECT is
5379 nil or t, it means that the data comes from C string.
0fa1789e 5380
a92e4183
KH
5381 If OBJECT is not nil, the data is encoded by PROC's coding-system
5382 for encoding before it is sent.
1fb0098c
GM
5383
5384 This function can evaluate Lisp code and can garbage collect. */
4556b700 5385
ff6daed3 5386static void
4d7e6e51
PE
5387send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5388 Lisp_Object object)
d0d6b7c5 5389{
6b61353c 5390 struct Lisp_Process *p = XPROCESS (proc);
368f4090 5391 ssize_t rv;
0fa1789e 5392 struct coding_system *coding;
6044e593 5393
6bfd98e7 5394 if (p->raw_status_new)
6b61353c 5395 update_status (p);
4d2b044c
DA
5396 if (! EQ (p->status, Qrun))
5397 error ("Process %s not running", SDATA (p->name));
60f0fb11 5398 if (p->outfd < 0)
4d2b044c 5399 error ("Output file descriptor of %s is closed", SDATA (p->name));
0fa1789e 5400
60f0fb11 5401 coding = proc_encode_coding_system[p->outfd];
5bbf78c1 5402 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
486b111b 5403
ed7a4b2d
KH
5404 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5405 || (BUFFERP (object)
4b4deea2 5406 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
a92e4183 5407 || EQ (object, Qt))
278bfdd6 5408 {
6a09a33b
PE
5409 pset_encode_coding_system
5410 (p, complement_process_encoding_system (p->encode_coding_system));
4d2b044c 5411 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
fcaf8878
KH
5412 {
5413 /* The coding system for encoding was changed to raw-text
5414 because we sent a unibyte text previously. Now we are
5415 sending a multibyte text, thus we must encode it by the
5416 original coding system specified for the current process.
5417
da6062e6
PE
5418 Another reason we come here is that the coding system
5419 was just complemented and a new one was returned by
fcaf8878 5420 complement_process_encoding_system. */
4d2b044c
DA
5421 setup_coding_system (p->encode_coding_system, coding);
5422 Vlast_coding_system_used = p->encode_coding_system;
fcaf8878 5423 }
e08bbb84 5424 coding->src_multibyte = 1;
278bfdd6
KH
5425 }
5426 else
5427 {
a0241d01 5428 coding->src_multibyte = 0;
a92e4183
KH
5429 /* For sending a unibyte text, character code conversion should
5430 not take place but EOL conversion should. So, setup raw-text
5431 or one of the subsidiary if we have not yet done it. */
5bbf78c1 5432 if (CODING_REQUIRE_ENCODING (coding))
a92e4183
KH
5433 {
5434 if (CODING_REQUIRE_FLUSHING (coding))
5435 {
5436 /* But, before changing the coding, we must flush out data. */
5437 coding->mode |= CODING_MODE_LAST_BLOCK;
5438 send_process (proc, "", 0, Qt);
8f924df7 5439 coding->mode &= CODING_MODE_LAST_BLOCK;
a92e4183 5440 }
5bbf78c1
KH
5441 setup_coding_system (raw_text_coding_system
5442 (Vlast_coding_system_used),
5443 coding);
e08bbb84 5444 coding->src_multibyte = 0;
a92e4183 5445 }
278bfdd6 5446 }
a4a37e65
KH
5447 coding->dst_multibyte = 0;
5448
ed7a4b2d 5449 if (CODING_REQUIRE_ENCODING (coding))
0fa1789e 5450 {
5bbf78c1 5451 coding->dst_object = Qt;
ed7a4b2d 5452 if (BUFFERP (object))
0fa1789e 5453 {
d311d28c
PE
5454 ptrdiff_t from_byte, from, to;
5455 ptrdiff_t save_pt, save_pt_byte;
5bbf78c1
KH
5456 struct buffer *cur = current_buffer;
5457
5458 set_buffer_internal (XBUFFER (object));
5459 save_pt = PT, save_pt_byte = PT_BYTE;
5460
400a67ff 5461 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5bbf78c1
KH
5462 from = BYTE_TO_CHAR (from_byte);
5463 to = BYTE_TO_CHAR (from_byte + len);
5464 TEMP_SET_PT_BOTH (from, from_byte);
5465 encode_coding_object (coding, object, from, from_byte,
5466 to, from_byte + len, Qt);
5467 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5468 set_buffer_internal (cur);
ed7a4b2d
KH
5469 }
5470 else if (STRINGP (object))
5471 {
550c8289
KH
5472 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5473 SBYTES (object), Qt);
0fa1789e 5474 }
5bbf78c1 5475 else
452294c2 5476 {
5bbf78c1
KH
5477 coding->dst_object = make_unibyte_string (buf, len);
5478 coding->produced = len;
452294c2 5479 }
ed7a4b2d 5480
e7fbaa65 5481 len = coding->produced;
347f3cd3 5482 object = coding->dst_object;
400a67ff 5483 buf = SSDATA (object);
0fa1789e 5484 }
d0d6b7c5 5485
4d7e6e51
PE
5486 /* If there is already data in the write_queue, put the new data
5487 in the back of queue. Otherwise, ignore it. */
5488 if (!NILP (p->write_queue))
5489 write_queue_push (p, object, buf, len, 0);
20ca2e94 5490
4d7e6e51
PE
5491 do /* while !NILP (p->write_queue) */
5492 {
5493 ptrdiff_t cur_len = -1;
5494 const char *cur_buf;
5495 Lisp_Object cur_object;
20ca2e94 5496
4d7e6e51
PE
5497 /* If write_queue is empty, ignore it. */
5498 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
0daad115 5499 {
4d7e6e51
PE
5500 cur_len = len;
5501 cur_buf = buf;
5502 cur_object = object;
5503 }
20ca2e94 5504
4d7e6e51
PE
5505 while (cur_len > 0)
5506 {
5507 /* Send this batch, using one or more write calls. */
5508 ptrdiff_t written = 0;
5509 int outfd = p->outfd;
5510#ifdef DATAGRAM_SOCKETS
5511 if (DATAGRAM_CHAN_P (outfd))
20ca2e94 5512 {
4d7e6e51
PE
5513 rv = sendto (outfd, cur_buf, cur_len,
5514 0, datagram_address[outfd].sa,
5515 datagram_address[outfd].len);
908589fd 5516 if (rv >= 0)
4d7e6e51
PE
5517 written = rv;
5518 else if (errno == EMSGSIZE)
4e604a5d 5519 report_file_error ("Sending datagram", proc);
20ca2e94 5520 }
4d7e6e51 5521 else
e690ca94 5522#endif
4d7e6e51 5523 {
8af55556 5524#ifdef HAVE_GNUTLS
194b4d9f 5525 if (p->gnutls_p && p->gnutls_state)
4d7e6e51
PE
5526 written = emacs_gnutls_write (p, cur_buf, cur_len);
5527 else
8af55556 5528#endif
4ebbdd67 5529 written = emacs_write_sig (outfd, cur_buf, cur_len);
4d7e6e51 5530 rv = (written ? 0 : -1);
6b61353c 5531#ifdef ADAPTIVE_READ_BUFFERING
4d7e6e51
PE
5532 if (p->read_output_delay > 0
5533 && p->adaptive_read_buffering == 1)
5534 {
5535 p->read_output_delay = 0;
5536 process_output_delay_count--;
5537 p->read_output_skip = 0;
6b61353c 5538 }
4d7e6e51
PE
5539#endif
5540 }
4556b700 5541
4d7e6e51
PE
5542 if (rv < 0)
5543 {
22626a85 5544 if (errno == EAGAIN
d0d6b7c5 5545#ifdef EWOULDBLOCK
4d7e6e51 5546 || errno == EWOULDBLOCK
d0d6b7c5 5547#endif
4d7e6e51
PE
5548 )
5549 /* Buffer is full. Wait, accepting input;
5550 that may allow the program
5551 to finish doing output and read more. */
5552 {
3433b6bd 5553#ifdef BROKEN_PTY_READ_AFTER_EAGAIN
4d7e6e51
PE
5554 /* A gross hack to work around a bug in FreeBSD.
5555 In the following sequence, read(2) returns
5556 bogus data:
5557
5558 write(2) 1022 bytes
5559 write(2) 954 bytes, get EAGAIN
5560 read(2) 1024 bytes in process_read_output
5561 read(2) 11 bytes in process_read_output
5562
5563 That is, read(2) returns more bytes than have
5564 ever been written successfully. The 1033 bytes
5565 read are the 1022 bytes written successfully
5566 after processing (for example with CRs added if
5567 the terminal is set up that way which it is
5568 here). The same bytes will be seen again in a
5569 later read(2), without the CRs. */
5570
5571 if (errno == EAGAIN)
5572 {
5573 int flags = FWRITE;
5574 ioctl (p->outfd, TIOCFLUSH, &flags);
5575 }
3433b6bd 5576#endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
177c0ea7 5577
4d7e6e51
PE
5578 /* Put what we should have written in wait_queue. */
5579 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5580 wait_reading_process_output (0, 20 * 1000 * 1000,
5581 0, 0, Qnil, NULL, 0);
5582 /* Reread queue, to see what is left. */
5583 break;
0daad115 5584 }
4d7e6e51
PE
5585 else if (errno == EPIPE)
5586 {
5587 p->raw_status_new = 0;
5588 pset_status (p, list2 (Qexit, make_number (256)));
5589 p->tick = ++process_tick;
5590 deactivate_process (proc);
5591 error ("process %s no longer connected to pipe; closed it",
5592 SDATA (p->name));
5593 }
5594 else
5595 /* This is a real error. */
4e604a5d 5596 report_file_error ("Writing to process", proc);
0daad115 5597 }
4d7e6e51
PE
5598 cur_buf += written;
5599 cur_len -= written;
0daad115 5600 }
d0d6b7c5 5601 }
4d7e6e51 5602 while (!NILP (p->write_queue));
d0d6b7c5
JB
5603}
5604
5605DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
fdb82f93
PJ
5606 3, 3, 0,
5607 doc: /* Send current contents of region as input to PROCESS.
5608PROCESS may be a process, a buffer, the name of a process or buffer, or
5609nil, indicating the current buffer's process.
5610Called from program, takes three arguments, PROCESS, START and END.
5611If the region is more than 500 characters long,
5612it is sent in several bunches. This may happen even for shorter regions.
5613Output from processes can arrive in between bunches. */)
5842a27b 5614 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
d0d6b7c5 5615{
13002885
DA
5616 Lisp_Object proc = get_process (process);
5617 ptrdiff_t start_byte, end_byte;
d0d6b7c5 5618
d0d6b7c5 5619 validate_region (&start, &end);
1b234f64 5620
13002885
DA
5621 start_byte = CHAR_TO_BYTE (XINT (start));
5622 end_byte = CHAR_TO_BYTE (XINT (end));
5623
1b234f64 5624 if (XINT (start) < GPT && XINT (end) > GPT)
13002885 5625 move_gap_both (XINT (start), start_byte);
1b234f64 5626
e454145b 5627 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
13002885 5628 end_byte - start_byte, Fcurrent_buffer ());
1b234f64 5629
d0d6b7c5
JB
5630 return Qnil;
5631}
5632
5633DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
fdb82f93
PJ
5634 2, 2, 0,
5635 doc: /* Send PROCESS the contents of STRING as input.
5636PROCESS may be a process, a buffer, the name of a process or buffer, or
5637nil, indicating the current buffer's process.
5638If STRING is more than 500 characters long,
5639it is sent in several bunches. This may happen even for shorter strings.
5640Output from processes can arrive in between bunches. */)
5842a27b 5641 (Lisp_Object process, Lisp_Object string)
d0d6b7c5
JB
5642{
5643 Lisp_Object proc;
b7826503 5644 CHECK_STRING (string);
d0d6b7c5 5645 proc = get_process (process);
400a67ff 5646 send_process (proc, SSDATA (string),
1b234f64 5647 SBYTES (string), string);
d0d6b7c5
JB
5648 return Qnil;
5649}
5650\f
16782258
JD
5651/* Return the foreground process group for the tty/pty that
5652 the process P uses. */
dde14581 5653static pid_t
d3da34e0 5654emacs_get_tty_pgrp (struct Lisp_Process *p)
16782258 5655{
dde14581 5656 pid_t gid = -1;
16782258 5657
f3d9532b 5658#ifdef TIOCGPGRP
4d2b044c 5659 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
16782258
JD
5660 {
5661 int fd;
5662 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5663 master side. Try the slave side. */
4d2b044c 5664 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
16782258
JD
5665
5666 if (fd != -1)
5667 {
5668 ioctl (fd, TIOCGPGRP, &gid);
5669 emacs_close (fd);
5670 }
5671 }
5672#endif /* defined (TIOCGPGRP ) */
5673
5674 return gid;
5675}
5676
b81ea5ef
RS
5677DEFUN ("process-running-child-p", Fprocess_running_child_p,
5678 Sprocess_running_child_p, 0, 1, 0,
fdb82f93
PJ
5679 doc: /* Return t if PROCESS has given the terminal to a child.
5680If the operating system does not make it possible to find out,
5681return t unconditionally. */)
5842a27b 5682 (Lisp_Object process)
b81ea5ef
RS
5683{
5684 /* Initialize in case ioctl doesn't exist or gives an error,
5685 in a way that will cause returning t. */
dde14581 5686 pid_t gid;
b81ea5ef
RS
5687 Lisp_Object proc;
5688 struct Lisp_Process *p;
5689
5690 proc = get_process (process);
5691 p = XPROCESS (proc);
5692
4d2b044c 5693 if (!EQ (p->type, Qreal))
b81ea5ef 5694 error ("Process %s is not a subprocess",
4d2b044c 5695 SDATA (p->name));
60f0fb11 5696 if (p->infd < 0)
b81ea5ef 5697 error ("Process %s is not active",
4d2b044c 5698 SDATA (p->name));
b81ea5ef 5699
16782258 5700 gid = emacs_get_tty_pgrp (p);
b81ea5ef 5701
6bfd98e7 5702 if (gid == p->pid)
b81ea5ef
RS
5703 return Qnil;
5704 return Qt;
5705}
5706\f
d0d6b7c5 5707/* send a signal number SIGNO to PROCESS.
b81ea5ef
RS
5708 If CURRENT_GROUP is t, that means send to the process group
5709 that currently owns the terminal being used to communicate with PROCESS.
d0d6b7c5 5710 This is used for various commands in shell mode.
b81ea5ef
RS
5711 If CURRENT_GROUP is lambda, that means send to the process group
5712 that currently owns the terminal, but only if it is NOT the shell itself.
5713
0bce5d9e 5714 If NOMSG is false, insert signal-announcements into process's buffers
b0310da4
JB
5715 right away.
5716
5717 If we can, we try to signal PROCESS by sending control characters
e333e864 5718 down the pty. This allows us to signal inferiors who have changed
d983a10b 5719 their uid, for which kill would return an EPERM error. */
d0d6b7c5 5720
f9738840 5721static void
d3da34e0 5722process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
0bce5d9e 5723 bool nomsg)
d0d6b7c5
JB
5724{
5725 Lisp_Object proc;
0bce5d9e 5726 struct Lisp_Process *p;
dde14581 5727 pid_t gid;
0bce5d9e 5728 bool no_pgrp = 0;
d0d6b7c5
JB
5729
5730 proc = get_process (process);
5731 p = XPROCESS (proc);
5732
4d2b044c 5733 if (!EQ (p->type, Qreal))
d0d6b7c5 5734 error ("Process %s is not a subprocess",
4d2b044c 5735 SDATA (p->name));
60f0fb11 5736 if (p->infd < 0)
d0d6b7c5 5737 error ("Process %s is not active",
4d2b044c 5738 SDATA (p->name));
d0d6b7c5 5739
60f0fb11 5740 if (!p->pty_flag)
d0d6b7c5
JB
5741 current_group = Qnil;
5742
d0d6b7c5 5743 /* If we are using pgrps, get a pgrp number and make it negative. */
2af70a0c
RS
5744 if (NILP (current_group))
5745 /* Send the signal to the shell's process group. */
6bfd98e7 5746 gid = p->pid;
2af70a0c 5747 else
d0d6b7c5 5748 {
b0310da4 5749#ifdef SIGNALS_VIA_CHARACTERS
d0d6b7c5
JB
5750 /* If possible, send signals to the entire pgrp
5751 by sending an input character to it. */
b0310da4 5752
6be429b1 5753 struct termios t;
7f916a36
RS
5754 cc_t *sig_char = NULL;
5755
60f0fb11 5756 tcgetattr (p->infd, &t);
6be429b1
JB
5757
5758 switch (signo)
5759 {
5760 case SIGINT:
7f916a36
RS
5761 sig_char = &t.c_cc[VINTR];
5762 break;
6be429b1
JB
5763
5764 case SIGQUIT:
7f916a36
RS
5765 sig_char = &t.c_cc[VQUIT];
5766 break;
6be429b1
JB
5767
5768 case SIGTSTP:
d0adf46f 5769#if defined (VSWTCH) && !defined (PREFER_VSUSP)
7f916a36 5770 sig_char = &t.c_cc[VSWTCH];
6be429b1 5771#else
7f916a36 5772 sig_char = &t.c_cc[VSUSP];
6be429b1 5773#endif
7f916a36 5774 break;
6be429b1
JB
5775 }
5776
ca4313d5 5777 if (sig_char && *sig_char != CDISABLE)
f1c206fc 5778 {
f990b4e5 5779 send_process (proc, (char *) sig_char, 1, Qnil);
f1c206fc
RS
5780 return;
5781 }
5782 /* If we can't send the signal with a character,
5783 fall through and send it another way. */
f1c206fc
RS
5784
5785 /* The code above may fall through if it can't
5786 handle the signal. */
20505336 5787#endif /* defined (SIGNALS_VIA_CHARACTERS) */
d0d6b7c5 5788
177c0ea7 5789#ifdef TIOCGPGRP
2af70a0c 5790 /* Get the current pgrp using the tty itself, if we have that.
d0d6b7c5
JB
5791 Otherwise, use the pty to get the pgrp.
5792 On pfa systems, saka@pfu.fujitsu.co.JP writes:
b0310da4
JB
5793 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5794 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
d0d6b7c5
JB
5795 His patch indicates that if TIOCGPGRP returns an error, then
5796 we should just assume that p->pid is also the process group id. */
d0d6b7c5 5797
16782258 5798 gid = emacs_get_tty_pgrp (p);
f3d9532b 5799
16782258
JD
5800 if (gid == -1)
5801 /* If we can't get the information, assume
5802 the shell owns the tty. */
6bfd98e7 5803 gid = p->pid;
2af70a0c
RS
5804
5805 /* It is not clear whether anything really can set GID to -1.
5806 Perhaps on some system one of those ioctls can or could do so.
5807 Or perhaps this is vestigial. */
d0d6b7c5
JB
5808 if (gid == -1)
5809 no_pgrp = 1;
b0310da4 5810#else /* ! defined (TIOCGPGRP ) */
301c3fe4
JB
5811 /* Can't select pgrps on this system, so we know that
5812 the child itself heads the pgrp. */
6bfd98e7 5813 gid = p->pid;
301c3fe4 5814#endif /* ! defined (TIOCGPGRP ) */
b81ea5ef
RS
5815
5816 /* If current_group is lambda, and the shell owns the terminal,
5817 don't send any signal. */
6bfd98e7 5818 if (EQ (current_group, Qlambda) && gid == p->pid)
b81ea5ef 5819 return;
d0d6b7c5 5820 }
d0d6b7c5 5821
d0d6b7c5 5822#ifdef SIGCONT
26495794
PE
5823 if (signo == SIGCONT)
5824 {
6bfd98e7 5825 p->raw_status_new = 0;
6a09a33b 5826 pset_status (p, Qrun);
60f0fb11 5827 p->tick = ++process_tick;
d0d6b7c5 5828 if (!nomsg)
e42bdf01
CY
5829 {
5830 status_notify (NULL);
5831 redisplay_preserve_echo_area (13);
5832 }
d0d6b7c5 5833 }
26495794 5834#endif
d0d6b7c5 5835
ca0279be
PE
5836#ifdef TIOCSIGSEND
5837 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5838 We don't know whether the bug is fixed in later HP-UX versions. */
5839 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
5840 return;
5841#endif
5842
d0d6b7c5
JB
5843 /* If we don't have process groups, send the signal to the immediate
5844 subprocess. That isn't really right, but it's better than any
5845 obvious alternative. */
ca0279be 5846 pid_t pid = no_pgrp ? gid : - gid;
d0d6b7c5 5847
ca0279be
PE
5848 /* Do not kill an already-reaped process, as that could kill an
5849 innocent bystander that happens to have the same process ID. */
5850 sigset_t oldset;
5851 block_child_signal (&oldset);
5852 if (p->alive)
5853 kill (pid, signo);
5854 unblock_child_signal (&oldset);
d0d6b7c5
JB
5855}
5856
5857DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
fdb82f93
PJ
5858 doc: /* Interrupt process PROCESS.
5859PROCESS may be a process, a buffer, or the name of a process or buffer.
f3d9532b 5860No arg or nil means current buffer's process.
fdb82f93
PJ
5861Second arg CURRENT-GROUP non-nil means send signal to
5862the current process-group of the process's controlling terminal
5863rather than to the process's own process group.
5864If the process is a shell, this means interrupt current subjob
5865rather than the shell.
5866
5867If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5868don't send the signal. */)
5842a27b 5869 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5870{
5871 process_send_signal (process, SIGINT, current_group, 0);
5872 return process;
5873}
5874
5875DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
fdb82f93
PJ
5876 doc: /* Kill process PROCESS. May be process or name of one.
5877See function `interrupt-process' for more details on usage. */)
5842a27b 5878 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5879{
5880 process_send_signal (process, SIGKILL, current_group, 0);
5881 return process;
5882}
5883
5884DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
fdb82f93
PJ
5885 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5886See function `interrupt-process' for more details on usage. */)
5842a27b 5887 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5888{
5889 process_send_signal (process, SIGQUIT, current_group, 0);
5890 return process;
5891}
5892
5893DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
fdb82f93 5894 doc: /* Stop process PROCESS. May be process or name of one.
177c0ea7 5895See function `interrupt-process' for more details on usage.
d888760c
GM
5896If PROCESS is a network or serial process, inhibit handling of incoming
5897traffic. */)
5842a27b 5898 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5 5899{
d888760c 5900 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
e690ca94
KS
5901 {
5902 struct Lisp_Process *p;
177c0ea7 5903
e690ca94 5904 p = XPROCESS (process);
4d2b044c 5905 if (NILP (p->command)
60f0fb11 5906 && p->infd >= 0)
e690ca94 5907 {
60f0fb11
SM
5908 FD_CLR (p->infd, &input_wait_mask);
5909 FD_CLR (p->infd, &non_keyboard_wait_mask);
e690ca94 5910 }
6a09a33b 5911 pset_command (p, Qt);
e690ca94
KS
5912 return process;
5913 }
d0d6b7c5 5914#ifndef SIGTSTP
a9a73d6c 5915 error ("No SIGTSTP support");
d0d6b7c5
JB
5916#else
5917 process_send_signal (process, SIGTSTP, current_group, 0);
5918#endif
5919 return process;
5920}
5921
5922DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
fdb82f93 5923 doc: /* Continue process PROCESS. May be process or name of one.
177c0ea7 5924See function `interrupt-process' for more details on usage.
d888760c
GM
5925If PROCESS is a network or serial process, resume handling of incoming
5926traffic. */)
5842a27b 5927 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5 5928{
d888760c 5929 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
e690ca94
KS
5930 {
5931 struct Lisp_Process *p;
5932
5933 p = XPROCESS (process);
4d2b044c 5934 if (EQ (p->command, Qt)
60f0fb11 5935 && p->infd >= 0
4d2b044c 5936 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
e690ca94 5937 {
60f0fb11
SM
5938 FD_SET (p->infd, &input_wait_mask);
5939 FD_SET (p->infd, &non_keyboard_wait_mask);
d888760c
GM
5940#ifdef WINDOWSNT
5941 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5942 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
a7ebc409 5943#else /* not WINDOWSNT */
d888760c 5944 tcflush (p->infd, TCIFLUSH);
a7ebc409 5945#endif /* not WINDOWSNT */
e690ca94 5946 }
6a09a33b 5947 pset_command (p, Qnil);
e690ca94
KS
5948 return process;
5949 }
d0d6b7c5
JB
5950#ifdef SIGCONT
5951 process_send_signal (process, SIGCONT, current_group, 0);
5952#else
a9a73d6c 5953 error ("No SIGCONT support");
d0d6b7c5
JB
5954#endif
5955 return process;
5956}
5957
d983a10b
PE
5958/* Return the integer value of the signal whose abbreviation is ABBR,
5959 or a negative number if there is no such signal. */
5960static int
5961abbr_to_signal (char const *name)
5962{
5963 int i, signo;
5964 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5965
5966 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5967 name += 3;
5968
5969 for (i = 0; i < sizeof sigbuf; i++)
5970 {
5971 sigbuf[i] = c_toupper (name[i]);
5972 if (! sigbuf[i])
5973 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5974 }
5975
5976 return -1;
5977}
5978
d0d6b7c5 5979DEFUN ("signal-process", Fsignal_process, Ssignal_process,
cdd5ea86
KS
5980 2, 2, "sProcess (name or number): \nnSignal code: ",
5981 doc: /* Send PROCESS the signal with code SIGCODE.
648f6edf 5982PROCESS may also be a number specifying the process id of the
cdd5ea86
KS
5983process to signal; in this case, the process need not be a child of
5984this Emacs.
fdb82f93 5985SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5842a27b 5986 (Lisp_Object process, Lisp_Object sigcode)
d0d6b7c5 5987{
6bfd98e7 5988 pid_t pid;
d983a10b 5989 int signo;
cdd5ea86 5990
cdd5ea86
KS
5991 if (STRINGP (process))
5992 {
d311d28c
PE
5993 Lisp_Object tem = Fget_process (process);
5994 if (NILP (tem))
cdd5ea86 5995 {
d44287d4
PE
5996 Lisp_Object process_number =
5997 string_to_number (SSDATA (process), 10, 1);
5998 if (INTEGERP (process_number) || FLOATP (process_number))
5999 tem = process_number;
cdd5ea86
KS
6000 }
6001 process = tem;
6002 }
d44287d4 6003 else if (!NUMBERP (process))
cdd5ea86 6004 process = get_process (process);
177c0ea7 6005
cdd5ea86
KS
6006 if (NILP (process))
6007 return process;
6008
d83cf4cc
PE
6009 if (NUMBERP (process))
6010 CONS_TO_INTEGER (process, pid_t, pid);
d44287d4
PE
6011 else
6012 {
6013 CHECK_PROCESS (process);
6014 pid = XPROCESS (process)->pid;
6015 if (pid <= 0)
4d2b044c 6016 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
d44287d4 6017 }
4766242d 6018
4766242d 6019 if (INTEGERP (sigcode))
d983a10b
PE
6020 {
6021 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6022 signo = XINT (sigcode);
6023 }
4766242d
RS
6024 else
6025 {
25a48bd0 6026 char *name;
4766242d 6027
b7826503 6028 CHECK_SYMBOL (sigcode);
25a48bd0 6029 name = SSDATA (SYMBOL_NAME (sigcode));
4766242d 6030
d983a10b
PE
6031 signo = abbr_to_signal (name);
6032 if (signo < 0)
9fa195a2 6033 error ("Undefined signal name %s", name);
4766242d
RS
6034 }
6035
d983a10b 6036 return make_number (kill (pid, signo));
d0d6b7c5
JB
6037}
6038
6039DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
fdb82f93
PJ
6040 doc: /* Make PROCESS see end-of-file in its input.
6041EOF comes after any text already sent to it.
6042PROCESS may be a process, a buffer, the name of a process or buffer, or
6043nil, indicating the current buffer's process.
6044If PROCESS is a network connection, or is a process communicating
6045through a pipe (as opposed to a pty), then you cannot send any more
d888760c
GM
6046text to PROCESS after you call this function.
6047If PROCESS is a serial process, wait until all output written to the
6048process has been transmitted to the serial port. */)
5842a27b 6049 (Lisp_Object process)
d0d6b7c5
JB
6050{
6051 Lisp_Object proc;
1014b1dc
EZ
6052 struct coding_system *coding = NULL;
6053 int outfd;
d0d6b7c5 6054
e690ca94
KS
6055 if (DATAGRAM_CONN_P (process))
6056 return process;
6057
d0d6b7c5 6058 proc = get_process (process);
1014b1dc
EZ
6059 outfd = XPROCESS (proc)->outfd;
6060 if (outfd >= 0)
6061 coding = proc_encode_coding_system[outfd];
577d03d5
RS
6062
6063 /* Make sure the process is really alive. */
6bfd98e7 6064 if (XPROCESS (proc)->raw_status_new)
577d03d5 6065 update_status (XPROCESS (proc));
4d2b044c
DA
6066 if (! EQ (XPROCESS (proc)->status, Qrun))
6067 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
577d03d5 6068
1014b1dc 6069 if (coding && CODING_REQUIRE_FLUSHING (coding))
de7fbd09
KH
6070 {
6071 coding->mode |= CODING_MODE_LAST_BLOCK;
6072 send_process (proc, "", 0, Qnil);
6073 }
6074
60f0fb11 6075 if (XPROCESS (proc)->pty_flag)
4556b700 6076 send_process (proc, "\004", 1, Qnil);
4d2b044c 6077 else if (EQ (XPROCESS (proc)->type, Qserial))
d888760c 6078 {
a7ebc409 6079#ifndef WINDOWSNT
d888760c 6080 if (tcdrain (XPROCESS (proc)->outfd) != 0)
4e604a5d 6081 report_file_error ("Failed tcdrain", Qnil);
a7ebc409 6082#endif /* not WINDOWSNT */
d888760c
GM
6083 /* Do nothing on Windows because writes are blocking. */
6084 }
d0d6b7c5
JB
6085 else
6086 {
1014b1dc
EZ
6087 struct Lisp_Process *p = XPROCESS (proc);
6088 int old_outfd = p->outfd;
94fcd171 6089 int new_outfd;
4525f571 6090
93853f3d 6091#ifdef HAVE_SHUTDOWN
02f55c4b
RS
6092 /* If this is a network connection, or socketpair is used
6093 for communication with the subprocess, call shutdown to cause EOF.
6094 (In some old system, shutdown to socketpair doesn't work.
6095 Then we just can't win.) */
1014b1dc
EZ
6096 if (EQ (p->type, Qnetwork)
6097 || p->infd == old_outfd)
94fcd171
PE
6098 shutdown (old_outfd, 1);
6099#endif
1014b1dc 6100 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
68c45bf0 6101 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
27448380 6102 if (new_outfd < 0)
94fcd171 6103 report_file_error ("Opening null device", Qnil);
1014b1dc
EZ
6104 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6105 p->outfd = new_outfd;
4525f571
RS
6106
6107 if (!proc_encode_coding_system[new_outfd])
6108 proc_encode_coding_system[new_outfd]
23f86fce 6109 = xmalloc (sizeof (struct coding_system));
1014b1dc
EZ
6110 if (old_outfd >= 0)
6111 {
6112 *proc_encode_coding_system[new_outfd]
6113 = *proc_encode_coding_system[old_outfd];
6114 memset (proc_encode_coding_system[old_outfd], 0,
6115 sizeof (struct coding_system));
6116 }
6117 else
6118 setup_coding_system (p->encode_coding_system,
6119 proc_encode_coding_system[new_outfd]);
d0d6b7c5 6120 }
d0d6b7c5
JB
6121 return process;
6122}
d0d6b7c5 6123\f
bb5f74ee 6124/* The main Emacs thread records child processes in three places:
0b3d4a47 6125
bb5f74ee
PE
6126 - Vprocess_alist, for asynchronous subprocesses, which are child
6127 processes visible to Lisp.
6128
6129 - deleted_pid_list, for child processes invisible to Lisp,
6130 typically because of delete-process. These are recorded so that
6131 the processes can be reaped when they exit, so that the operating
6132 system's process table is not cluttered by zombies.
0b3d4a47 6133
bb5f74ee
PE
6134 - the local variable PID in Fcall_process, call_process_cleanup and
6135 call_process_kill, for synchronous subprocesses.
6136 record_unwind_protect is used to make sure this process is not
6137 forgotten: if the user interrupts call-process and the child
6138 process refuses to exit immediately even with two C-g's,
6139 call_process_kill adds PID's contents to deleted_pid_list before
6140 returning.
0b3d4a47 6141
bb5f74ee
PE
6142 The main Emacs thread invokes waitpid only on child processes that
6143 it creates and that have not been reaped. This avoid races on
6144 platforms such as GTK, where other threads create their own
6145 subprocesses which the main thread should not reap. For example,
6146 if the main thread attempted to reap an already-reaped child, it
6147 might inadvertently reap a GTK-created process that happened to
6148 have the same process ID. */
6149
f019a684
PE
6150/* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6151 its own SIGCHLD handling. On POSIXish systems, glib needs this to
fa55d2aa
PE
6152 keep track of its own children. GNUstep is similar. */
6153
f019a684 6154static void dummy_handler (int sig) {}
fa55d2aa 6155static signal_handler_t volatile lib_child_handler;
f019a684 6156
bb5f74ee
PE
6157/* Handle a SIGCHLD signal by looking for known child processes of
6158 Emacs whose status have changed. For each one found, record its
6159 new status.
177c0ea7 6160
3fed8ad5
GM
6161 All we do is change the status; we do not run sentinels or print
6162 notifications. That is saved for the next time keyboard input is
6163 done, in order to avoid timing errors.
6164
6165 ** WARNING: this can be called during garbage collection.
6166 Therefore, it must not be fooled by the presence of mark bits in
6167 Lisp objects.
6168
6169 ** USG WARNING: Although it is not obvious from the documentation
6170 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6171 signal() before executing at least one wait(), otherwise the
6172 handler will be called again, resulting in an infinite loop. The
6173 relevant portion of the documentation reads "SIGCLD signals will be
6174 queued and the signal-catching function will be continually
6175 reentered until the queue is empty". Invoking signal() causes the
6176 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6b61353c
KH
6177 Inc.
6178
6179 ** Malloc WARNING: This should never call malloc either directly or
6180 indirectly; if it does, that is a bug */
d0d6b7c5 6181
bb5f74ee
PE
6182static void
6183handle_child_signal (int sig)
d0d6b7c5 6184{
d5a1acfa 6185 Lisp_Object tail, proc;
d0d6b7c5 6186
20ef56db 6187 /* Find the process that signaled us, and record its status. */
d0d6b7c5 6188
bb5f74ee
PE
6189 /* The process can have been deleted by Fdelete_process, or have
6190 been started asynchronously by Fcall_process. */
20ef56db
PE
6191 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6192 {
0b3d4a47
PE
6193 bool all_pids_are_fixnums
6194 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6195 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
94fcd171 6196 Lisp_Object head = XCAR (tail);
22490125
PE
6197 Lisp_Object xpid;
6198 if (! CONSP (head))
6199 continue;
6200 xpid = XCAR (head);
0b3d4a47 6201 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
a5cfdda8 6202 {
0b3d4a47
PE
6203 pid_t deleted_pid;
6204 if (INTEGERP (xpid))
6205 deleted_pid = XINT (xpid);
6206 else
6207 deleted_pid = XFLOAT_DATA (xpid);
bb5f74ee 6208 if (child_status_changed (deleted_pid, 0, 0))
94fcd171
PE
6209 {
6210 if (STRINGP (XCDR (head)))
6211 unlink (SSDATA (XCDR (head)));
6212 XSETCAR (tail, Qnil);
6213 }
a5cfdda8 6214 }
20ef56db 6215 }
a5cfdda8 6216
20ef56db 6217 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
d5a1acfa 6218 FOR_EACH_PROCESS (tail, proc)
20ef56db 6219 {
0b3d4a47 6220 struct Lisp_Process *p = XPROCESS (proc);
bb5f74ee
PE
6221 int status;
6222
da9aff11 6223 if (p->alive
d355cad6 6224 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
0b3d4a47
PE
6225 {
6226 /* Change the status of the process that was found. */
6227 p->tick = ++process_tick;
bb5f74ee 6228 p->raw_status = status;
0b3d4a47 6229 p->raw_status_new = 1;
177c0ea7 6230
0b3d4a47 6231 /* If process has terminated, stop waiting for its output. */
bb5f74ee 6232 if (WIFSIGNALED (status) || WIFEXITED (status))
0b3d4a47 6233 {
0bce5d9e 6234 bool clear_desc_flag = 0;
0b3d4a47
PE
6235 p->alive = 0;
6236 if (p->infd >= 0)
6237 clear_desc_flag = 1;
e98d950b 6238
0b3d4a47
PE
6239 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6240 if (clear_desc_flag)
6241 {
6242 FD_CLR (p->infd, &input_wait_mask);
6243 FD_CLR (p->infd, &non_keyboard_wait_mask);
6244 }
6245 }
d0d6b7c5 6246 }
20ef56db 6247 }
f019a684
PE
6248
6249 lib_child_handler (sig);
2c41e781 6250#ifdef NS_IMPL_GNUSTEP
a6c4680a 6251 /* NSTask in GNUstep sets its child handler each time it is called.
2c41e781
JD
6252 So we must re-set ours. */
6253 catch_child_signal();
6254#endif
d0d6b7c5 6255}
20ef56db
PE
6256
6257static void
6258deliver_child_signal (int sig)
6259{
4d7e6e51 6260 deliver_process_signal (sig, handle_child_signal);
20ef56db 6261}
d0d6b7c5
JB
6262\f
6263
3b9a3dfa 6264static Lisp_Object
b93aacde 6265exec_sentinel_error_handler (Lisp_Object error_val)
3b9a3dfa 6266{
b93aacde 6267 cmd_error_internal (error_val, "error in process sentinel: ");
3b9a3dfa
RS
6268 Vinhibit_quit = Qt;
6269 update_echo_area ();
833ba342 6270 Fsleep_for (make_number (2), Qnil);
8c983bf2 6271 return Qt;
3b9a3dfa
RS
6272}
6273
d0d6b7c5 6274static void
d3da34e0 6275exec_sentinel (Lisp_Object proc, Lisp_Object reason)
d0d6b7c5 6276{
aba7731a 6277 Lisp_Object sentinel, odeactivate;
1882aa38 6278 struct Lisp_Process *p = XPROCESS (proc);
d311d28c 6279 ptrdiff_t count = SPECPDL_INDEX ();
1882aa38 6280 bool outer_running_asynch_code = running_asynch_code;
bbce7d72 6281 int waiting = waiting_for_user_input_p;
d0d6b7c5 6282
84af9896
RS
6283 if (inhibit_sentinels)
6284 return;
6285
dfc21838
RS
6286 /* No need to gcpro these, because all we do with them later
6287 is test them for EQness, and none of them should be a string. */
8fb3cf64 6288 odeactivate = Vdeactivate_mark;
aba7731a
PE
6289#if 0
6290 Lisp_Object obuffer, okeymap;
dfc21838 6291 XSETBUFFER (obuffer, current_buffer);
4b4deea2 6292 okeymap = BVAR (current_buffer, keymap);
aba7731a 6293#endif
dfc21838 6294
97e53006
SM
6295 /* There's no good reason to let sentinels change the current
6296 buffer, and many callers of accept-process-output, sit-for, and
6297 friends don't expect current-buffer to be changed from under them. */
66322887 6298 record_unwind_current_buffer ();
97e53006 6299
4d2b044c 6300 sentinel = p->sentinel;
d0d6b7c5 6301
d0d6b7c5
JB
6302 /* Inhibit quit so that random quits don't screw up a running filter. */
6303 specbind (Qinhibit_quit, Qt);
f00c449b 6304 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
3b9a3dfa 6305
4da2f5be
RS
6306 /* In case we get recursively called,
6307 and we already saved the match data nonrecursively,
6308 save the same match data in safely recursive fashion. */
6309 if (outer_running_asynch_code)
6310 {
6311 Lisp_Object tem;
89f2614d
KS
6312 tem = Fmatch_data (Qnil, Qnil, Qnil);
6313 restore_search_regs ();
6314 record_unwind_save_match_data ();
6315 Fset_match_data (tem, Qt);
4da2f5be
RS
6316 }
6317
6318 /* For speed, if a search happens within this code,
6319 save the match data in a special nonrecursive fashion. */
7074fde6 6320 running_asynch_code = 1;
4da2f5be 6321
3b9a3dfa 6322 internal_condition_case_1 (read_process_output_call,
6c6f1994 6323 list3 (sentinel, proc, reason),
3b9a3dfa
RS
6324 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6325 exec_sentinel_error_handler);
4da2f5be
RS
6326
6327 /* If we saved the match data nonrecursively, restore it now. */
89f2614d 6328 restore_search_regs ();
4da2f5be 6329 running_asynch_code = outer_running_asynch_code;
8fb3cf64
KH
6330
6331 Vdeactivate_mark = odeactivate;
bbce7d72
RS
6332
6333 /* Restore waiting_for_user_input_p as it was
6334 when we were called, in case the filter clobbered it. */
6335 waiting_for_user_input_p = waiting;
6336
7973cfa8 6337#if 0
dfc21838
RS
6338 if (! EQ (Fcurrent_buffer (), obuffer)
6339 || ! EQ (current_buffer->keymap, okeymap))
7973cfa8 6340#endif
927e08be
RS
6341 /* But do it only if the caller is actually going to read events.
6342 Otherwise there's no need to make him wake up, and it could
7157b8fe 6343 cause trouble (for example it would make sit_for return). */
927e08be
RS
6344 if (waiting_for_user_input_p == -1)
6345 record_asynch_buffer_change ();
8fb3cf64 6346
2ea6d561 6347 unbind_to (count, Qnil);
d0d6b7c5
JB
6348}
6349
6350/* Report all recent events of a change in process status
6351 (either run the sentinel or output a message).
b50fe468
RS
6352 This is usually done while Emacs is waiting for keyboard input
6353 but can be done at other times. */
d0d6b7c5 6354
ff6daed3 6355static void
d3da34e0 6356status_notify (struct Lisp_Process *deleting_process)
d0d6b7c5 6357{
1aa8d505 6358 register Lisp_Object proc;
2e4149a8 6359 Lisp_Object tail, msg;
d0d6b7c5
JB
6360 struct gcpro gcpro1, gcpro2;
6361
2e4149a8
KH
6362 tail = Qnil;
6363 msg = Qnil;
d0d6b7c5
JB
6364 /* We need to gcpro tail; if read_process_output calls a filter
6365 which deletes a process and removes the cons to which tail points
6366 from Vprocess_alist, and then causes a GC, tail is an unprotected
6367 reference. */
6368 GCPRO2 (tail, msg);
6369
30623085
RS
6370 /* Set this now, so that if new processes are created by sentinels
6371 that we run, we get called again to handle their status changes. */
6372 update_tick = process_tick;
6373
d5a1acfa 6374 FOR_EACH_PROCESS (tail, proc)
d0d6b7c5 6375 {
30623085 6376 Lisp_Object symbol;
d5a1acfa 6377 register struct Lisp_Process *p = XPROCESS (proc);
30623085 6378
60f0fb11 6379 if (p->tick != p->update_tick)
d0d6b7c5 6380 {
60f0fb11 6381 p->update_tick = p->tick;
d0d6b7c5 6382
30623085 6383 /* If process is still active, read any output that remains. */
4d2b044c
DA
6384 while (! EQ (p->filter, Qt)
6385 && ! EQ (p->status, Qconnect)
6386 && ! EQ (p->status, Qlisten)
d888760c 6387 /* Network or serial process not stopped: */
4d2b044c 6388 && ! EQ (p->command, Qt)
60f0fb11 6389 && p->infd >= 0
ff6daed3 6390 && p != deleting_process
60f0fb11 6391 && read_process_output (proc, p->infd) > 0);
d0d6b7c5 6392
30623085 6393 /* Get the text to use for the message. */
6bfd98e7 6394 if (p->raw_status_new)
30623085 6395 update_status (p);
116c423c 6396 msg = status_message (p);
d0d6b7c5 6397
30623085 6398 /* If process is terminated, deactivate it or delete it. */
4d2b044c
DA
6399 symbol = p->status;
6400 if (CONSP (p->status))
6401 symbol = XCAR (p->status);
d0d6b7c5 6402
30623085
RS
6403 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6404 || EQ (symbol, Qclosed))
6405 {
6406 if (delete_exited_processes)
6407 remove_process (proc);
6408 else
6409 deactivate_process (proc);
6410 }
d0d6b7c5 6411
0ad61fe7 6412 /* The actions above may have further incremented p->tick.
1aa8d505
SM
6413 So set p->update_tick again so that an error in the sentinel will
6414 not cause this code to be run again. */
60f0fb11 6415 p->update_tick = p->tick;
30623085 6416 /* Now output the message suitably. */
1aa8d505 6417 exec_sentinel (proc, msg);
30623085
RS
6418 }
6419 } /* end for */
d0d6b7c5 6420
2ec9db5d 6421 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
d0d6b7c5
JB
6422 UNGCPRO;
6423}
0fa1789e 6424
1aa8d505
SM
6425DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6426 Sinternal_default_process_sentinel, 2, 2, 0,
458e643b 6427 doc: /* Function used as default sentinel for processes.
f33095ed 6428This inserts a status message into the process's buffer, if there is one. */)
1aa8d505
SM
6429 (Lisp_Object proc, Lisp_Object msg)
6430{
6431 Lisp_Object buffer, symbol;
6432 struct Lisp_Process *p;
6433 CHECK_PROCESS (proc);
6434 p = XPROCESS (proc);
6435 buffer = p->buffer;
6436 symbol = p->status;
6437 if (CONSP (symbol))
6438 symbol = XCAR (symbol);
6439
6440 if (!EQ (symbol, Qrun) && !NILP (buffer))
6441 {
6442 Lisp_Object tem;
6443 struct buffer *old = current_buffer;
6444 ptrdiff_t opoint, opoint_byte;
6445 ptrdiff_t before, before_byte;
6446
6447 /* Avoid error if buffer is deleted
6448 (probably that's why the process is dead, too). */
6449 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6450 return Qnil;
6451 Fset_buffer (buffer);
6452
6453 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6454 msg = (code_convert_string_norecord
6455 (msg, Vlocale_coding_system, 1));
6456
6457 opoint = PT;
6458 opoint_byte = PT_BYTE;
6459 /* Insert new output into buffer
6460 at the current end-of-output marker,
6461 thus preserving logical ordering of input and output. */
6462 if (XMARKER (p->mark)->buffer)
6463 Fgoto_char (p->mark);
6464 else
6465 SET_PT_BOTH (ZV, ZV_BYTE);
6466
6467 before = PT;
6468 before_byte = PT_BYTE;
6469
6470 tem = BVAR (current_buffer, read_only);
6471 bset_read_only (current_buffer, Qnil);
6472 insert_string ("\nProcess ");
6473 { /* FIXME: temporary kludge. */
6474 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6475 insert_string (" ");
6476 Finsert (1, &msg);
6477 bset_read_only (current_buffer, tem);
6478 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6479
6480 if (opoint >= before)
6481 SET_PT_BOTH (opoint + (PT - before),
6482 opoint_byte + (PT_BYTE - before_byte));
6483 else
6484 SET_PT_BOTH (opoint, opoint_byte);
6485
6486 set_buffer_internal (old);
6487 }
6488 return Qnil;
6489}
6490
0fa1789e
KH
6491\f
6492DEFUN ("set-process-coding-system", Fset_process_coding_system,
6493 Sset_process_coding_system, 1, 3, 0,
fdb82f93
PJ
6494 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6495DECODING will be used to decode subprocess output and ENCODING to
6496encode subprocess input. */)
5842a27b 6497 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
0fa1789e
KH
6498{
6499 register struct Lisp_Process *p;
6500
f3d9532b
JB
6501 CHECK_PROCESS (process);
6502 p = XPROCESS (process);
60f0fb11 6503 if (p->infd < 0)
4d2b044c 6504 error ("Input file descriptor of %s closed", SDATA (p->name));
60f0fb11 6505 if (p->outfd < 0)
4d2b044c 6506 error ("Output file descriptor of %s closed", SDATA (p->name));
03f04413
KH
6507 Fcheck_coding_system (decoding);
6508 Fcheck_coding_system (encoding);
76d812bb 6509 encoding = coding_inherit_eol_type (encoding, Qnil);
6a09a33b
PE
6510 pset_decode_coding_system (p, decoding);
6511 pset_encode_coding_system (p, encoding);
f3d9532b 6512 setup_process_coding_systems (process);
0fa1789e
KH
6513
6514 return Qnil;
6515}
6516
6517DEFUN ("process-coding-system",
6518 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
fdb82f93 6519 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
5842a27b 6520 (register Lisp_Object process)
0fa1789e 6521{
f3d9532b 6522 CHECK_PROCESS (process);
4d2b044c
DA
6523 return Fcons (XPROCESS (process)->decode_coding_system,
6524 XPROCESS (process)->encode_coding_system);
0fa1789e 6525}
03f04413
KH
6526
6527DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6528 Sset_process_filter_multibyte, 2, 2, 0,
7392e23c
KS
6529 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6530If FLAG is non-nil, the filter is given multibyte strings.
6531If FLAG is nil, the filter is given unibyte strings. In this case,
03f04413
KH
6532all character code conversion except for end-of-line conversion is
6533suppressed. */)
5842a27b 6534 (Lisp_Object process, Lisp_Object flag)
03f04413
KH
6535{
6536 register struct Lisp_Process *p;
6537
f3d9532b
JB
6538 CHECK_PROCESS (process);
6539 p = XPROCESS (process);
5431bd6a 6540 if (NILP (flag))
6a09a33b
PE
6541 pset_decode_coding_system
6542 (p, raw_text_coding_system (p->decode_coding_system));
f3d9532b 6543 setup_process_coding_systems (process);
03f04413
KH
6544
6545 return Qnil;
6546}
6547
6548DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6549 Sprocess_filter_multibyte_p, 1, 1, 0,
6550 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
5842a27b 6551 (Lisp_Object process)
03f04413
KH
6552{
6553 register struct Lisp_Process *p;
5431bd6a 6554 struct coding_system *coding;
03f04413 6555
f3d9532b
JB
6556 CHECK_PROCESS (process);
6557 p = XPROCESS (process);
5431bd6a
SM
6558 coding = proc_decode_coding_system[p->infd];
6559 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
03f04413
KH
6560}
6561
6562
d0d6b7c5 6563\f
cb768704 6564
4475bec4
PE
6565# ifdef HAVE_GPM
6566
994d9841 6567void
d3da34e0 6568add_gpm_wait_descriptor (int desc)
994d9841 6569{
3fad2ad2 6570 add_keyboard_wait_descriptor (desc);
994d9841
NR
6571}
6572
994d9841 6573void
d3da34e0 6574delete_gpm_wait_descriptor (int desc)
994d9841 6575{
3fad2ad2 6576 delete_keyboard_wait_descriptor (desc);
994d9841
NR
6577}
6578
4475bec4
PE
6579# endif
6580
4a4bbad2 6581# ifdef USABLE_SIGIO
006c5daa 6582
0bce5d9e 6583/* Return true if *MASK has a bit set
a69281ff
RS
6584 that corresponds to one of the keyboard input descriptors. */
6585
0bce5d9e 6586static bool
d3da34e0 6587keyboard_bit_set (fd_set *mask)
a69281ff
RS
6588{
6589 int fd;
6590
3fad2ad2 6591 for (fd = 0; fd <= max_input_desc; fd++)
a69281ff
RS
6592 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6593 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6594 return 1;
6595
6596 return 0;
6597}
006c5daa 6598# endif
934e2a68 6599
f388c88a 6600#else /* not subprocesses */
934e2a68 6601
f388c88a 6602/* Defined on msdos.c. */
d486344e 6603extern int sys_select (int, fd_set *, fd_set *, fd_set *,
43aac990 6604 struct timespec *, void *);
934e2a68 6605
f388c88a
EZ
6606/* Implementation of wait_reading_process_output, assuming that there
6607 are no subprocesses. Used only by the MS-DOS build.
934e2a68 6608
f388c88a 6609 Wait for timeout to elapse and/or keyboard input to be available.
934e2a68 6610
d188e26b 6611 TIME_LIMIT is:
d35af63c
PE
6612 timeout in seconds
6613 If negative, gobble data immediately available but don't wait for any.
6614
d188e26b 6615 NSECS is:
d35af63c
PE
6616 an additional duration to wait, measured in nanoseconds
6617 If TIME_LIMIT is zero, then:
d188e26b
PE
6618 If NSECS == 0, there is no limit.
6619 If NSECS > 0, the timeout consists of NSECS only.
d35af63c 6620 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
934e2a68 6621
a0bee46f 6622 READ_KBD is:
f388c88a
EZ
6623 0 to ignore keyboard input, or
6624 1 to return when input is available, or
6625 -1 means caller will actually read the input, so don't throw to
6626 the quit handler.
934e2a68 6627
f388c88a
EZ
6628 see full version for other parameters. We know that wait_proc will
6629 always be NULL, since `subprocesses' isn't defined.
934e2a68 6630
9fa1de30 6631 DO_DISPLAY means redisplay should be done to show subprocess
f388c88a 6632 output that arrives.
934e2a68 6633
f388c88a
EZ
6634 Return true if we received input from any process. */
6635
0bce5d9e 6636bool
d35af63c 6637wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
9fa1de30 6638 bool do_display,
1408902e
EZ
6639 Lisp_Object wait_for_cell,
6640 struct Lisp_Process *wait_proc, int just_wait_proc)
d0d6b7c5 6641{
f388c88a 6642 register int nfds;
43aac990 6643 struct timespec end_time, timeout;
d0d6b7c5 6644
d35af63c
PE
6645 if (time_limit < 0)
6646 {
6647 time_limit = 0;
6648 nsecs = -1;
6649 }
6650 else if (TYPE_MAXIMUM (time_t) < time_limit)
6651 time_limit = TYPE_MAXIMUM (time_t);
6652
f388c88a 6653 /* What does time_limit really mean? */
908589fd 6654 if (time_limit || nsecs > 0)
f388c88a 6655 {
43aac990
PE
6656 timeout = make_timespec (time_limit, nsecs);
6657 end_time = timespec_add (current_timespec (), timeout);
f388c88a 6658 }
84af9896 6659
f388c88a
EZ
6660 /* Turn off periodic alarms (in case they are in use)
6661 and then turn off any other atimers,
6662 because the select emulator uses alarms. */
6663 stop_polling ();
6664 turn_on_atimers (0);
d0d6b7c5 6665
f388c88a
EZ
6666 while (1)
6667 {
0bce5d9e 6668 bool timeout_reduced_for_timers = 0;
d486344e 6669 fd_set waitchannels;
a0bee46f 6670 int xerrno;
dd2281ae 6671
f388c88a
EZ
6672 /* If calling from keyboard input, do not quit
6673 since we want to return C-g as an input character.
6674 Otherwise, do pending quit if requested. */
6675 if (read_kbd >= 0)
6676 QUIT;
bad49fc7 6677
f388c88a
EZ
6678 /* Exit now if the cell we're waiting for became non-nil. */
6679 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6680 break;
0a65b032 6681
1aa8d505
SM
6682 /* Compute time from now till when time limit is up. */
6683 /* Exit if already run out. */
d35af63c 6684 if (nsecs < 0)
52fd88d3 6685 {
216ee680 6686 /* A negative timeout means
52fd88d3 6687 gobble output available now
1aa8d505 6688 but don't wait at all. */
52fd88d3 6689
43aac990 6690 timeout = make_timespec (0, 0);
52fd88d3 6691 }
908589fd 6692 else if (time_limit || nsecs > 0)
6720a7fb 6693 {
43aac990
PE
6694 struct timespec now = current_timespec ();
6695 if (timespec_cmp (end_time, now) <= 0)
6720a7fb 6696 break;
43aac990 6697 timeout = timespec_sub (end_time, now);
6720a7fb 6698 }
52fd88d3
EZ
6699 else
6700 {
43aac990 6701 timeout = make_timespec (100000, 0);
52fd88d3 6702 }
6720a7fb 6703
bae8d137
RS
6704 /* If our caller will not immediately handle keyboard events,
6705 run timer events directly.
6706 (Callers that will immediately read keyboard events
6707 call timer_delay on their own.) */
f3fbd155 6708 if (NILP (wait_for_cell))
bae8d137 6709 {
43aac990 6710 struct timespec timer_delay;
0a65b032 6711
9baacf76 6712 do
0a65b032 6713 {
9fa1de30 6714 unsigned old_timers_run = timers_run;
f868cd8a 6715 timer_delay = timer_check ();
9baacf76
GM
6716 if (timers_run != old_timers_run && do_display)
6717 /* We must retry, since a timer may have requeued itself
6718 and that could alter the time delay. */
3007ebfb 6719 redisplay_preserve_echo_area (14);
9baacf76
GM
6720 else
6721 break;
0a65b032 6722 }
9baacf76 6723 while (!detect_input_pending ());
0a65b032 6724
52fd88d3 6725 /* If there is unread keyboard input, also return. */
b89a415a 6726 if (read_kbd != 0
52fd88d3
EZ
6727 && requeued_events_pending_p ())
6728 break;
6729
43aac990 6730 if (timespec_valid_p (timer_delay) && nsecs >= 0)
bae8d137 6731 {
43aac990 6732 if (timespec_cmp (timer_delay, timeout) < 0)
bae8d137 6733 {
f694e5d2 6734 timeout = timer_delay;
bae8d137
RS
6735 timeout_reduced_for_timers = 1;
6736 }
6737 }
6738 }
6739
6720a7fb
JB
6740 /* Cause C-g and alarm signals to take immediate action,
6741 and cause input available signals to zero out timeout. */
b89a415a 6742 if (read_kbd < 0)
6720a7fb
JB
6743 set_waiting_for_input (&timeout);
6744
ff11dfa1 6745 /* If a frame has been newly mapped and needs updating,
6720a7fb 6746 reprocess its display stuff. */
5164ee8e 6747 if (frame_garbaged && do_display)
0a65b032
RS
6748 {
6749 clear_waiting_for_input ();
3007ebfb 6750 redisplay_preserve_echo_area (15);
b89a415a 6751 if (read_kbd < 0)
0a65b032
RS
6752 set_waiting_for_input (&timeout);
6753 }
6720a7fb 6754
a0bee46f
PE
6755 /* Wait till there is something to do. */
6756 FD_ZERO (&waitchannels);
b89a415a 6757 if (read_kbd && detect_input_pending ())
a0bee46f
PE
6758 nfds = 0;
6759 else
1861b214 6760 {
a0bee46f
PE
6761 if (read_kbd || !NILP (wait_for_cell))
6762 FD_SET (0, &waitchannels);
6763 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
1861b214 6764 }
f694e5d2
KH
6765
6766 xerrno = errno;
6720a7fb
JB
6767
6768 /* Make C-g and alarm signals set flags again */
6769 clear_waiting_for_input ();
6770
6771 /* If we woke up due to SIGWINCH, actually change size now. */
2b653806 6772 do_pending_window_change (0);
6720a7fb 6773
d35af63c 6774 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
f694e5d2
KH
6775 /* We waited the full specified time, so return now. */
6776 break;
6777
6720a7fb
JB
6778 if (nfds == -1)
6779 {
6780 /* If the system call was interrupted, then go around the
6781 loop again. */
f694e5d2 6782 if (xerrno == EINTR)
8db121c4 6783 FD_ZERO (&waitchannels);
f694e5d2 6784 else
4e604a5d 6785 report_file_errno ("Failed select", Qnil, xerrno);
6720a7fb 6786 }
6720a7fb 6787
f694e5d2
KH
6788 /* Check for keyboard input */
6789
b89a415a 6790 if (read_kbd
78c1afb6 6791 && detect_input_pending_run_timers (do_display))
f694e5d2 6792 {
78c1afb6 6793 swallow_events (do_display);
f694e5d2 6794 if (detect_input_pending_run_timers (do_display))
a2fab450 6795 break;
78c1afb6
EZ
6796 }
6797
52fd88d3 6798 /* If there is unread keyboard input, also return. */
b89a415a 6799 if (read_kbd
52fd88d3
EZ
6800 && requeued_events_pending_p ())
6801 break;
6802
f854a00b
RS
6803 /* If wait_for_cell. check for keyboard input
6804 but don't run any timers.
6805 ??? (It seems wrong to me to check for keyboard
6806 input at all when wait_for_cell, but the code
6807 has been this way since July 1994.
6808 Try changing this after version 19.31.) */
f3fbd155 6809 if (! NILP (wait_for_cell)
f854a00b
RS
6810 && detect_input_pending ())
6811 {
6812 swallow_events (do_display);
6813 if (detect_input_pending ())
6814 break;
6815 }
6816
0a65b032 6817 /* Exit now if the cell we're waiting for became non-nil. */
f3fbd155 6818 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
0a65b032 6819 break;
6720a7fb
JB
6820 }
6821
a87b802f
JB
6822 start_polling ();
6823
6720a7fb
JB
6824 return 0;
6825}
6826
f388c88a
EZ
6827#endif /* not subprocesses */
6828
6829/* The following functions are needed even if async subprocesses are
6830 not supported. Some of them are no-op stubs in that case. */
6720a7fb 6831
01faa934
DN
6832/* Add DESC to the set of keyboard input descriptors. */
6833
6834void
6835add_keyboard_wait_descriptor (int desc)
6836{
bf05eed6 6837#ifdef subprocesses /* actually means "not MSDOS" */
01faa934
DN
6838 FD_SET (desc, &input_wait_mask);
6839 FD_SET (desc, &non_process_wait_mask);
3fad2ad2
J
6840 if (desc > max_input_desc)
6841 max_input_desc = desc;
bf05eed6 6842#endif
01faa934
DN
6843}
6844
6845/* From now on, do not expect DESC to give keyboard input. */
6846
6847void
6848delete_keyboard_wait_descriptor (int desc)
6849{
bf05eed6 6850#ifdef subprocesses
01faa934
DN
6851 FD_CLR (desc, &input_wait_mask);
6852 FD_CLR (desc, &non_process_wait_mask);
2878ba7e 6853 delete_input_desc (desc);
bf05eed6 6854#endif
01faa934
DN
6855}
6856
fc549af9
EZ
6857/* Setup coding systems of PROCESS. */
6858
6859void
6860setup_process_coding_systems (Lisp_Object process)
6861{
6862#ifdef subprocesses
6863 struct Lisp_Process *p = XPROCESS (process);
6864 int inch = p->infd;
6865 int outch = p->outfd;
6866 Lisp_Object coding_system;
6867
6868 if (inch < 0 || outch < 0)
6869 return;
6870
6871 if (!proc_decode_coding_system[inch])
38182d90 6872 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
4d2b044c 6873 coding_system = p->decode_coding_system;
1aa8d505
SM
6874 if (EQ (p->filter, Qinternal_default_process_filter)
6875 && BUFFERP (p->buffer))
fc549af9 6876 {
4d2b044c 6877 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
fc549af9
EZ
6878 coding_system = raw_text_coding_system (coding_system);
6879 }
6880 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6881
6882 if (!proc_encode_coding_system[outch])
38182d90 6883 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
4d2b044c 6884 setup_coding_system (p->encode_coding_system,
fc549af9
EZ
6885 proc_encode_coding_system[outch]);
6886#endif
6887}
6888
6720a7fb 6889DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
f388c88a
EZ
6890 doc: /* Return the (or a) process associated with BUFFER.
6891BUFFER may be a buffer or the name of one. */)
6892 (register Lisp_Object buffer)
6720a7fb 6893{
f388c88a
EZ
6894#ifdef subprocesses
6895 register Lisp_Object buf, tail, proc;
6896
6897 if (NILP (buffer)) return Qnil;
6898 buf = Fget_buffer (buffer);
6899 if (NILP (buf)) return Qnil;
6900
d5a1acfa
DA
6901 FOR_EACH_PROCESS (tail, proc)
6902 if (EQ (XPROCESS (proc)->buffer, buf))
6903 return proc;
f388c88a 6904#endif /* subprocesses */
6720a7fb
JB
6905 return Qnil;
6906}
6907
52a1b894 6908DEFUN ("process-inherit-coding-system-flag",
fdb82f93
PJ
6909 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6910 1, 1, 0,
f388c88a
EZ
6911 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6912If this flag is t, `buffer-file-coding-system' of the buffer
6913associated with PROCESS will inherit the coding system used to decode
6914the process output. */)
5842a27b 6915 (register Lisp_Object process)
52a1b894 6916{
f388c88a
EZ
6917#ifdef subprocesses
6918 CHECK_PROCESS (process);
6919 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6920#else
52a1b894
EZ
6921 /* Ignore the argument and return the value of
6922 inherit-process-coding-system. */
6923 return inherit_process_coding_system ? Qt : Qnil;
f388c88a 6924#endif
52a1b894
EZ
6925}
6926
6720a7fb 6927/* Kill all processes associated with `buffer'.
f388c88a 6928 If `buffer' is nil, kill all processes */
6720a7fb 6929
d9bb0c32 6930void
f388c88a 6931kill_buffer_processes (Lisp_Object buffer)
6720a7fb 6932{
f388c88a
EZ
6933#ifdef subprocesses
6934 Lisp_Object tail, proc;
6935
d5a1acfa
DA
6936 FOR_EACH_PROCESS (tail, proc)
6937 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6938 {
6939 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6940 Fdelete_process (proc);
6941 else if (XPROCESS (proc)->infd >= 0)
6942 process_send_signal (proc, SIGHUP, Qnil, 1);
6943 }
f388c88a
EZ
6944#else /* subprocesses */
6945 /* Since we have no subprocesses, this does nothing. */
6946#endif /* subprocesses */
6720a7fb
JB
6947}
6948
a7ca3326 6949DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
16a97296 6950 Swaiting_for_user_input_p, 0, 0, 0,
1aa8d505 6951 doc: /* Return non-nil if Emacs is waiting for input from the user.
77defa9a
EZ
6952This is intended for use by asynchronous process output filters and sentinels. */)
6953 (void)
6954{
6955#ifdef subprocesses
6956 return (waiting_for_user_input_p ? Qt : Qnil);
6957#else
6958 return Qnil;
6959#endif
6960}
6961
d568829b
EZ
6962/* Stop reading input from keyboard sources. */
6963
6964void
6965hold_keyboard_input (void)
6966{
6967 kbd_is_on_hold = 1;
6968}
6969
6970/* Resume reading input from keyboard sources. */
6971
6972void
6973unhold_keyboard_input (void)
6974{
6975 kbd_is_on_hold = 0;
6976}
6977
0bce5d9e 6978/* Return true if keyboard input is on hold, zero otherwise. */
d568829b 6979
0bce5d9e 6980bool
d568829b
EZ
6981kbd_on_hold_p (void)
6982{
6983 return kbd_is_on_hold;
6984}
6985
f388c88a
EZ
6986\f
6987/* Enumeration of and access to system processes a-la ps(1). */
6988
934e2a68
EZ
6989DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6990 0, 0, 0,
6991 doc: /* Return a list of numerical process IDs of all running processes.
6992If this functionality is unsupported, return nil.
6993
f388c88a
EZ
6994See `process-attributes' for getting attributes of a process given its ID. */)
6995 (void)
6996{
6997 return list_system_processes ();
6998}
6999
7000DEFUN ("process-attributes", Fprocess_attributes,
7001 Sprocess_attributes, 1, 1, 0,
7002 doc: /* Return attributes of the process given by its PID, a number.
7003
7004Value is an alist where each element is a cons cell of the form
7005
7006 \(KEY . VALUE)
7007
7008If this functionality is unsupported, the value is nil.
7009
7010See `list-system-processes' for getting a list of all process IDs.
7011
7012The KEYs of the attributes that this function may return are listed
7013below, together with the type of the associated VALUE (in parentheses).
7014Not all platforms support all of these attributes; unsupported
7015attributes will not appear in the returned alist.
7016Unless explicitly indicated otherwise, numbers can have either
7017integer or floating point values.
7018
7019 euid -- Effective user User ID of the process (number)
7020 user -- User name corresponding to euid (string)
7021 egid -- Effective user Group ID of the process (number)
7022 group -- Group name corresponding to egid (string)
7023 comm -- Command name (executable name only) (string)
7024 state -- Process state code, such as "S", "R", or "T" (string)
7025 ppid -- Parent process ID (number)
7026 pgrp -- Process group ID (number)
7027 sess -- Session ID, i.e. process ID of session leader (number)
7028 ttname -- Controlling tty name (string)
7029 tpgid -- ID of foreground process group on the process's tty (number)
7030 minflt -- number of minor page faults (number)
7031 majflt -- number of major page faults (number)
7032 cminflt -- cumulative number of minor page faults (number)
7033 cmajflt -- cumulative number of major page faults (number)
d35af63c
PE
7034 utime -- user time used by the process, in (current-time) format,
7035 which is a list of integers (HIGH LOW USEC PSEC)
7036 stime -- system time used by the process (current-time)
7037 time -- sum of utime and stime (current-time)
7038 cutime -- user time used by the process and its children (current-time)
7039 cstime -- system time used by the process and its children (current-time)
7040 ctime -- sum of cutime and cstime (current-time)
f388c88a
EZ
7041 pri -- priority of the process (number)
7042 nice -- nice value of the process (number)
7043 thcount -- process thread count (number)
d35af63c 7044 start -- time the process started (current-time)
f388c88a
EZ
7045 vsize -- virtual memory size of the process in KB's (number)
7046 rss -- resident set size of the process in KB's (number)
d35af63c 7047 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
f388c88a
EZ
7048 pcpu -- percents of CPU time used by the process (floating-point number)
7049 pmem -- percents of total physical memory used by process's resident set
7050 (floating-point number)
7051 args -- command line which invoked the process (string). */)
7052 ( Lisp_Object pid)
7053{
7054 return system_process_attributes (pid);
7055}
7056
bf6b4923 7057#ifdef subprocesses
fa55d2aa
PE
7058/* Arrange to catch SIGCHLD if this hasn't already been arranged.
7059 Invoke this after init_process_emacs, and after glib and/or GNUstep
7060 futz with the SIGCHLD handler, but before Emacs forks any children.
7061 This function's caller should block SIGCHLD. */
0dfeed58 7062
dae2f5ef
PE
7063#ifndef NS_IMPL_GNUSTEP
7064static
7065#endif
c0342369
JD
7066void
7067catch_child_signal (void)
7068{
f019a684 7069 struct sigaction action, old_action;
1e952f0a 7070 sigset_t oldset;
c0342369 7071 emacs_sigaction_init (&action, deliver_child_signal);
1e952f0a 7072 block_child_signal (&oldset);
f019a684
PE
7073 sigaction (SIGCHLD, &action, &old_action);
7074 eassert (! (old_action.sa_flags & SA_SIGINFO));
fa55d2aa 7075
dae2f5ef
PE
7076 if (old_action.sa_handler != deliver_child_signal)
7077 lib_child_handler
7078 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7079 ? dummy_handler
7080 : old_action.sa_handler);
1e952f0a 7081 unblock_child_signal (&oldset);
c0342369 7082}
bf6b4923 7083#endif /* subprocesses */
c0342369 7084
f388c88a 7085\f
b82da769
GM
7086/* This is not called "init_process" because that is the name of a
7087 Mach system call, so it would cause problems on Darwin systems. */
f388c88a 7088void
b82da769 7089init_process_emacs (void)
f388c88a
EZ
7090{
7091#ifdef subprocesses
7092 register int i;
7093
7094 inhibit_sentinels = 0;
7095
dae2f5ef
PE
7096#ifndef CANNOT_DUMP
7097 if (! noninteractive || initialized)
7098#endif
7099 {
8f43ce49 7100#if defined HAVE_GLIB && !defined WINDOWSNT
dae2f5ef
PE
7101 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7102 this should always fail, but is enough to initialize glib's
8f43ce49
PE
7103 private SIGCHLD handler, allowing catch_child_signal to copy
7104 it into lib_child_handler. */
dae2f5ef
PE
7105 g_source_unref (g_child_watch_source_new (getpid ()));
7106#endif
7107 catch_child_signal ();
7108 }
7109
f388c88a
EZ
7110 FD_ZERO (&input_wait_mask);
7111 FD_ZERO (&non_keyboard_wait_mask);
7112 FD_ZERO (&non_process_wait_mask);
3fad2ad2 7113 FD_ZERO (&write_mask);
2878ba7e 7114 max_process_desc = max_input_desc = -1;
3fad2ad2 7115 memset (fd_callback_info, 0, sizeof (fd_callback_info));
f388c88a
EZ
7116
7117#ifdef NON_BLOCKING_CONNECT
7118 FD_ZERO (&connect_wait_mask);
7119 num_pending_connects = 0;
7120#endif
7121
7122#ifdef ADAPTIVE_READ_BUFFERING
7123 process_output_delay_count = 0;
7124 process_output_skip = 0;
7125#endif
7126
7127 /* Don't do this, it caused infinite select loops. The display
7128 method should call add_keyboard_wait_descriptor on stdin if it
7129 needs that. */
7130#if 0
7131 FD_SET (0, &input_wait_mask);
7132#endif
7133
7134 Vprocess_alist = Qnil;
f388c88a 7135 deleted_pid_list = Qnil;
d486344e 7136 for (i = 0; i < FD_SETSIZE; i++)
f388c88a
EZ
7137 {
7138 chan_process[i] = Qnil;
7139 proc_buffered_char[i] = -1;
7140 }
7141 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7142 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7143#ifdef DATAGRAM_SOCKETS
7144 memset (datagram_address, 0, sizeof datagram_address);
7145#endif
7146
f388c88a
EZ
7147 {
7148 Lisp_Object subfeatures = Qnil;
7149 const struct socket_options *sopt;
7150
7151#define ADD_SUBFEATURE(key, val) \
7152 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7153
7154#ifdef NON_BLOCKING_CONNECT
7155 ADD_SUBFEATURE (QCnowait, Qt);
7156#endif
7157#ifdef DATAGRAM_SOCKETS
7158 ADD_SUBFEATURE (QCtype, Qdatagram);
7159#endif
7160#ifdef HAVE_SEQPACKET
7161 ADD_SUBFEATURE (QCtype, Qseqpacket);
7162#endif
7163#ifdef HAVE_LOCAL_SOCKETS
7164 ADD_SUBFEATURE (QCfamily, Qlocal);
7165#endif
7166 ADD_SUBFEATURE (QCfamily, Qipv4);
7167#ifdef AF_INET6
7168 ADD_SUBFEATURE (QCfamily, Qipv6);
7169#endif
7170#ifdef HAVE_GETSOCKNAME
7171 ADD_SUBFEATURE (QCservice, Qt);
7172#endif
f388c88a 7173 ADD_SUBFEATURE (QCserver, Qt);
f388c88a
EZ
7174
7175 for (sopt = socket_options; sopt->name; sopt++)
7176 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7177
7178 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7179 }
f388c88a
EZ
7180
7181#if defined (DARWIN_OS)
7182 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7183 processes. As such, we only change the default value. */
7184 if (initialized)
7185 {
f44bd759
PE
7186 char const *release = (STRINGP (Voperating_system_release)
7187 ? SSDATA (Voperating_system_release)
7188 : 0);
6de0e799 7189 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
f388c88a
EZ
7190 Vprocess_connection_type = Qnil;
7191 }
7192 }
7193#endif
7194#endif /* subprocesses */
7195 kbd_is_on_hold = 0;
7196}
7197
7198void
7199syms_of_process (void)
7200{
7201#ifdef subprocesses
7202
cd3520a4
JB
7203 DEFSYM (Qprocessp, "processp");
7204 DEFSYM (Qrun, "run");
7205 DEFSYM (Qstop, "stop");
7206 DEFSYM (Qsignal, "signal");
f388c88a
EZ
7207
7208 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7209 here again.
934e2a68 7210
f388c88a
EZ
7211 Qexit = intern_c_string ("exit");
7212 staticpro (&Qexit); */
934e2a68 7213
cd3520a4
JB
7214 DEFSYM (Qopen, "open");
7215 DEFSYM (Qclosed, "closed");
7216 DEFSYM (Qconnect, "connect");
7217 DEFSYM (Qfailed, "failed");
7218 DEFSYM (Qlisten, "listen");
7219 DEFSYM (Qlocal, "local");
7220 DEFSYM (Qipv4, "ipv4");
f388c88a 7221#ifdef AF_INET6
cd3520a4
JB
7222 DEFSYM (Qipv6, "ipv6");
7223#endif
7224 DEFSYM (Qdatagram, "datagram");
7225 DEFSYM (Qseqpacket, "seqpacket");
7226
7227 DEFSYM (QCport, ":port");
7228 DEFSYM (QCspeed, ":speed");
7229 DEFSYM (QCprocess, ":process");
7230
7231 DEFSYM (QCbytesize, ":bytesize");
7232 DEFSYM (QCstopbits, ":stopbits");
7233 DEFSYM (QCparity, ":parity");
7234 DEFSYM (Qodd, "odd");
7235 DEFSYM (Qeven, "even");
7236 DEFSYM (QCflowcontrol, ":flowcontrol");
7237 DEFSYM (Qhw, "hw");
7238 DEFSYM (Qsw, "sw");
7239 DEFSYM (QCsummary, ":summary");
7240
7241 DEFSYM (Qreal, "real");
7242 DEFSYM (Qnetwork, "network");
7243 DEFSYM (Qserial, "serial");
7244 DEFSYM (QCbuffer, ":buffer");
7245 DEFSYM (QChost, ":host");
7246 DEFSYM (QCservice, ":service");
7247 DEFSYM (QClocal, ":local");
7248 DEFSYM (QCremote, ":remote");
7249 DEFSYM (QCcoding, ":coding");
7250 DEFSYM (QCserver, ":server");
7251 DEFSYM (QCnowait, ":nowait");
7252 DEFSYM (QCsentinel, ":sentinel");
7253 DEFSYM (QClog, ":log");
7254 DEFSYM (QCnoquery, ":noquery");
7255 DEFSYM (QCstop, ":stop");
7256 DEFSYM (QCoptions, ":options");
7257 DEFSYM (QCplist, ":plist");
7258
7259 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
934e2a68 7260
f388c88a 7261 staticpro (&Vprocess_alist);
f388c88a 7262 staticpro (&deleted_pid_list);
934e2a68 7263
f388c88a 7264#endif /* subprocesses */
6720a7fb 7265
cd3520a4
JB
7266 DEFSYM (QCname, ":name");
7267 DEFSYM (QCtype, ":type");
7268
7269 DEFSYM (Qeuid, "euid");
7270 DEFSYM (Qegid, "egid");
7271 DEFSYM (Quser, "user");
7272 DEFSYM (Qgroup, "group");
7273 DEFSYM (Qcomm, "comm");
7274 DEFSYM (Qstate, "state");
7275 DEFSYM (Qppid, "ppid");
7276 DEFSYM (Qpgrp, "pgrp");
7277 DEFSYM (Qsess, "sess");
7278 DEFSYM (Qttname, "ttname");
7279 DEFSYM (Qtpgid, "tpgid");
7280 DEFSYM (Qminflt, "minflt");
7281 DEFSYM (Qmajflt, "majflt");
7282 DEFSYM (Qcminflt, "cminflt");
7283 DEFSYM (Qcmajflt, "cmajflt");
7284 DEFSYM (Qutime, "utime");
7285 DEFSYM (Qstime, "stime");
7286 DEFSYM (Qtime, "time");
7287 DEFSYM (Qcutime, "cutime");
7288 DEFSYM (Qcstime, "cstime");
7289 DEFSYM (Qctime, "ctime");
bf6b4923 7290#ifdef subprocesses
1aa8d505
SM
7291 DEFSYM (Qinternal_default_process_sentinel,
7292 "internal-default-process-sentinel");
7293 DEFSYM (Qinternal_default_process_filter,
7294 "internal-default-process-filter");
bf6b4923 7295#endif
cd3520a4
JB
7296 DEFSYM (Qpri, "pri");
7297 DEFSYM (Qnice, "nice");
7298 DEFSYM (Qthcount, "thcount");
7299 DEFSYM (Qstart, "start");
7300 DEFSYM (Qvsize, "vsize");
7301 DEFSYM (Qrss, "rss");
7302 DEFSYM (Qetime, "etime");
7303 DEFSYM (Qpcpu, "pcpu");
7304 DEFSYM (Qpmem, "pmem");
7305 DEFSYM (Qargs, "args");
9057ff80 7306
29208e82 7307 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
fb7ada5f 7308 doc: /* Non-nil means delete processes immediately when they exit.
f388c88a
EZ
7309A value of nil means don't delete them until `list-processes' is run. */);
7310
7311 delete_exited_processes = 1;
7312
462aa963 7313#ifdef subprocesses
29208e82 7314 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
f388c88a
EZ
7315 doc: /* Control type of device used to communicate with subprocesses.
7316Values are nil to use a pipe, or t or `pty' to use a pty.
7317The value has no effect if the system has no ptys or if all ptys are busy:
7318then a pipe is used in any case.
7319The value takes effect when `start-process' is called. */);
7320 Vprocess_connection_type = Qt;
7321
7322#ifdef ADAPTIVE_READ_BUFFERING
29208e82 7323 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
f388c88a
EZ
7324 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7325On some systems, when Emacs reads the output from a subprocess, the output data
7326is read in very small blocks, potentially resulting in very poor performance.
7327This behavior can be remedied to some extent by setting this variable to a
7328non-nil value, as it will automatically delay reading from such processes, to
7329allow them to produce more output before Emacs tries to read it.
7330If the value is t, the delay is reset after each write to the process; any other
7331non-nil value means that the delay is not reset on write.
7332The variable takes effect when `start-process' is called. */);
7333 Vprocess_adaptive_read_buffering = Qt;
7334#endif
7335
7336 defsubr (&Sprocessp);
7337 defsubr (&Sget_process);
7338 defsubr (&Sdelete_process);
7339 defsubr (&Sprocess_status);
7340 defsubr (&Sprocess_exit_status);
7341 defsubr (&Sprocess_id);
7342 defsubr (&Sprocess_name);
7343 defsubr (&Sprocess_tty_name);
7344 defsubr (&Sprocess_command);
7345 defsubr (&Sset_process_buffer);
7346 defsubr (&Sprocess_buffer);
7347 defsubr (&Sprocess_mark);
7348 defsubr (&Sset_process_filter);
7349 defsubr (&Sprocess_filter);
7350 defsubr (&Sset_process_sentinel);
7351 defsubr (&Sprocess_sentinel);
7352 defsubr (&Sset_process_window_size);
7353 defsubr (&Sset_process_inherit_coding_system_flag);
7354 defsubr (&Sset_process_query_on_exit_flag);
7355 defsubr (&Sprocess_query_on_exit_flag);
7356 defsubr (&Sprocess_contact);
7357 defsubr (&Sprocess_plist);
7358 defsubr (&Sset_process_plist);
f388c88a
EZ
7359 defsubr (&Sprocess_list);
7360 defsubr (&Sstart_process);
f388c88a
EZ
7361 defsubr (&Sserial_process_configure);
7362 defsubr (&Smake_serial_process);
f388c88a
EZ
7363 defsubr (&Sset_network_process_option);
7364 defsubr (&Smake_network_process);
7365 defsubr (&Sformat_network_address);
f388c88a 7366 defsubr (&Snetwork_interface_list);
f388c88a 7367 defsubr (&Snetwork_interface_info);
f388c88a
EZ
7368#ifdef DATAGRAM_SOCKETS
7369 defsubr (&Sprocess_datagram_address);
7370 defsubr (&Sset_process_datagram_address);
7371#endif
7372 defsubr (&Saccept_process_output);
7373 defsubr (&Sprocess_send_region);
7374 defsubr (&Sprocess_send_string);
7375 defsubr (&Sinterrupt_process);
7376 defsubr (&Skill_process);
7377 defsubr (&Squit_process);
7378 defsubr (&Sstop_process);
7379 defsubr (&Scontinue_process);
7380 defsubr (&Sprocess_running_child_p);
7381 defsubr (&Sprocess_send_eof);
7382 defsubr (&Ssignal_process);
7383 defsubr (&Swaiting_for_user_input_p);
7384 defsubr (&Sprocess_type);
1aa8d505
SM
7385 defsubr (&Sinternal_default_process_sentinel);
7386 defsubr (&Sinternal_default_process_filter);
f388c88a
EZ
7387 defsubr (&Sset_process_coding_system);
7388 defsubr (&Sprocess_coding_system);
7389 defsubr (&Sset_process_filter_multibyte);
7390 defsubr (&Sprocess_filter_multibyte_p);
7391
7392#endif /* subprocesses */
7393
6720a7fb 7394 defsubr (&Sget_buffer_process);
52a1b894 7395 defsubr (&Sprocess_inherit_coding_system_flag);
934e2a68 7396 defsubr (&Slist_system_processes);
a20878b6 7397 defsubr (&Sprocess_attributes);
6720a7fb 7398}