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