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