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