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