1/*	$NetBSD: tty.c,v 1.5 2021/01/09 16:39:28 christos Exp $	*/
2
3/*
4 * tty.c - code for handling serial ports in pppd.
5 *
6 * Copyright (C) 2000-2004 Paul Mackerras. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 *
15 * 2. The name(s) of the authors of this software must not be used to
16 *    endorse or promote products derived from this software without
17 *    prior written permission.
18 *
19 * 3. Redistributions of any form whatsoever must retain the following
20 *    acknowledgment:
21 *    "This product includes software developed by Paul Mackerras
22 *     <paulus@samba.org>".
23 *
24 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
25 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
26 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
27 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
28 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
29 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
30 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
31 *
32 * Portions derived from main.c, which is:
33 *
34 * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 *
40 * 1. Redistributions of source code must retain the above copyright
41 *    notice, this list of conditions and the following disclaimer.
42 *
43 * 2. Redistributions in binary form must reproduce the above copyright
44 *    notice, this list of conditions and the following disclaimer in
45 *    the documentation and/or other materials provided with the
46 *    distribution.
47 *
48 * 3. The name "Carnegie Mellon University" must not be used to
49 *    endorse or promote products derived from this software without
50 *    prior written permission. For permission or any legal
51 *    details, please contact
52 *      Office of Technology Transfer
53 *      Carnegie Mellon University
54 *      5000 Forbes Avenue
55 *      Pittsburgh, PA  15213-3890
56 *      (412) 268-4387, fax: (412) 268-7395
57 *      tech-transfer@andrew.cmu.edu
58 *
59 * 4. Redistributions of any form whatsoever must retain the following
60 *    acknowledgment:
61 *    "This product includes software developed by Computing Services
62 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
63 *
64 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
65 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
66 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
67 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
69 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
70 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
73#include <sys/cdefs.h>
74__RCSID("$NetBSD: tty.c,v 1.5 2021/01/09 16:39:28 christos Exp $");
75
76#include <stdio.h>
77#include <ctype.h>
78#include <stdlib.h>
79#include <string.h>
80#include <termios.h>
81#include <unistd.h>
82#include <signal.h>
83#include <errno.h>
84#include <fcntl.h>
85#include <syslog.h>
86#include <netdb.h>
87#include <utmp.h>
88#include <pwd.h>
89#include <sys/param.h>
90#include <sys/types.h>
91#include <sys/wait.h>
92#include <sys/time.h>
93#include <sys/resource.h>
94#include <sys/stat.h>
95#include <sys/socket.h>
96#include <netinet/in.h>
97#include <arpa/inet.h>
98
99#include "pppd.h"
100#include "fsm.h"
101#include "lcp.h"
102
103void tty_process_extra_options(void);
104void tty_check_options(void);
105int  connect_tty(void);
106void disconnect_tty(void);
107void tty_close_fds(void);
108void cleanup_tty(void);
109void tty_do_send_config(int, u_int32_t, int, int);
110
111static int setdevname(char *, char **, int);
112static int setspeed(char *, char **, int);
113static int setxonxoff(char **);
114static int setescape(char **);
115static void printescape(option_t *, void (*)(void *, char *,...),void *);
116static void finish_tty(void);
117static int start_charshunt(int, int);
118static void stop_charshunt(void *, int);
119static void charshunt_done(void *);
120static void charshunt(int, int, char *);
121static int record_write(FILE *, int code, u_char *buf, int nb,
122			struct timeval *);
123static int open_socket(char *);
124static void maybe_relock(void *, int);
125
126static int pty_master;		/* fd for master side of pty */
127static int pty_slave;		/* fd for slave side of pty */
128static int real_ttyfd;		/* fd for actual serial port (not pty) */
129static int ttyfd;		/* Serial port file descriptor */
130static char speed_str[16];	/* Serial port speed as string */
131
132mode_t tty_mode = (mode_t)-1;	/* Original access permissions to tty */
133int baud_rate;			/* Actual bits/second for serial device */
134char *callback_script;		/* script for doing callback */
135int charshunt_pid;		/* Process ID for charshunt */
136int locked;			/* lock() has succeeded */
137struct stat devstat;		/* result of stat() on devnam */
138
139/* option variables */
140int	crtscts = 0;		/* Use hardware flow control */
141int	stop_bits = 1;		/* Number of serial port stop bits */
142bool	modem = 1;		/* Use modem control lines */
143int	inspeed = 0;		/* Input/Output speed requested */
144bool	lockflag = 0;		/* Create lock file to lock the serial dev */
145char	*initializer = NULL;	/* Script to initialize physical link */
146char	*connect_script = NULL;	/* Script to establish physical link */
147char	*disconnect_script = NULL; /* Script to disestablish physical link */
148char	*welcomer = NULL;	/* Script to run after phys link estab. */
149char	*ptycommand = NULL;	/* Command to run on other side of pty */
150bool	notty = 0;		/* Stdin/out is not a tty */
151char	*record_file = NULL;	/* File to record chars sent/received */
152int	max_data_rate;		/* max bytes/sec through charshunt */
153bool	sync_serial = 0;	/* Device is synchronous serial device */
154char	*pty_socket = NULL;	/* Socket to connect to pty */
155int	using_pty = 0;		/* we're allocating a pty as the device */
156
157extern uid_t uid;
158extern int kill_link;
159extern int asked_to_quit;
160extern int got_sigterm;
161
162/* XXX */
163extern int privopen;		/* don't lock, open device as root */
164
165u_int32_t xmit_accm[8];		/* extended transmit ACCM */
166
167/* option descriptors */
168option_t tty_options[] = {
169    /* device name must be first, or change connect_tty() below! */
170    { "device name", o_wild, (void *) &setdevname,
171      "Serial port device name",
172      OPT_DEVNAM | OPT_PRIVFIX | OPT_NOARG  | OPT_A2STRVAL | OPT_STATIC,
173      devnam},
174
175    { "tty speed", o_wild, (void *) &setspeed,
176      "Baud rate for serial port",
177      OPT_PRIO | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC, speed_str },
178
179    { "lock", o_bool, &lockflag,
180      "Lock serial device with UUCP-style lock file", OPT_PRIO | 1 },
181    { "nolock", o_bool, &lockflag,
182      "Don't lock serial device", OPT_PRIOSUB | OPT_PRIV },
183
184    { "init", o_string, &initializer,
185      "A program to initialize the device", OPT_PRIO | OPT_PRIVFIX },
186
187    { "connect", o_string, &connect_script,
188      "A program to set up a connection", OPT_PRIO | OPT_PRIVFIX },
189
190    { "disconnect", o_string, &disconnect_script,
191      "Program to disconnect serial device", OPT_PRIO | OPT_PRIVFIX },
192
193    { "welcome", o_string, &welcomer,
194      "Script to welcome client", OPT_PRIO | OPT_PRIVFIX },
195
196    { "pty", o_string, &ptycommand,
197      "Script to run on pseudo-tty master side",
198      OPT_PRIO | OPT_PRIVFIX | OPT_DEVNAM },
199
200    { "notty", o_bool, &notty,
201      "Input/output is not a tty", OPT_DEVNAM | 1 },
202
203    { "socket", o_string, &pty_socket,
204      "Send and receive over socket, arg is host:port",
205      OPT_PRIO | OPT_DEVNAM },
206
207    { "record", o_string, &record_file,
208      "Record characters sent/received to file", OPT_PRIO },
209
210    { "crtscts", o_int, &crtscts,
211      "Set hardware (RTS/CTS) flow control",
212      OPT_PRIO | OPT_NOARG | OPT_VAL(1) },
213    { "cdtrcts", o_int, &crtscts,
214      "Set alternate hardware (DTR/CTS) flow control",
215      OPT_PRIOSUB | OPT_NOARG | OPT_VAL(2) },
216    { "nocrtscts", o_int, &crtscts,
217      "Disable hardware flow control",
218      OPT_PRIOSUB | OPT_NOARG | OPT_VAL(-1) },
219    { "-crtscts", o_int, &crtscts,
220      "Disable hardware flow control",
221      OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
222    { "nocdtrcts", o_int, &crtscts,
223      "Disable hardware flow control",
224      OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
225    { "xonxoff", o_special_noarg, (void *)setxonxoff,
226      "Set software (XON/XOFF) flow control", OPT_PRIOSUB },
227    { "stop-bits", o_int, &stop_bits,
228      "Number of stop bits in serial port",
229      OPT_PRIO | OPT_PRIVFIX | OPT_LIMITS, NULL, 2, 1 },
230
231    { "modem", o_bool, &modem,
232      "Use modem control lines", OPT_PRIO | 1 },
233    { "local", o_bool, &modem,
234      "Don't use modem control lines", OPT_PRIOSUB | 0 },
235
236    { "sync", o_bool, &sync_serial,
237      "Use synchronous HDLC serial encoding", 1 },
238
239    { "datarate", o_int, &max_data_rate,
240      "Maximum data rate in bytes/sec (with pty, notty or record option)",
241      OPT_PRIO },
242
243    { "escape", o_special, (void *)setescape,
244      "List of character codes to escape on transmission",
245      OPT_A2PRINTER, (void *)printescape },
246
247    { NULL }
248};
249
250
251struct channel tty_channel = {
252	tty_options,
253	&tty_process_extra_options,
254	&tty_check_options,
255	&connect_tty,
256	&disconnect_tty,
257	&tty_establish_ppp,
258	&tty_disestablish_ppp,
259	&tty_do_send_config,
260	&tty_recv_config,
261	&cleanup_tty,
262	&tty_close_fds
263};
264
265/*
266 * setspeed - Set the serial port baud rate.
267 * If doit is 0, the call is to check whether this option is
268 * potentially a speed value.
269 */
270static int
271setspeed(char *arg, char **argv, int doit)
272{
273	char *ptr;
274	int spd;
275
276	spd = strtol(arg, &ptr, 0);
277	if (ptr == arg || *ptr != 0 || spd == 0)
278		return 0;
279	if (doit) {
280		inspeed = spd;
281		slprintf(speed_str, sizeof(speed_str), "%d", spd);
282	}
283	return 1;
284}
285
286
287/*
288 * setdevname - Set the device name.
289 * If doit is 0, the call is to check whether this option is
290 * potentially a device name.
291 */
292static int
293setdevname(char *cp, char **argv, int doit)
294{
295	struct stat statbuf;
296	char dev[MAXPATHLEN];
297
298	if (*cp == 0)
299		return 0;
300
301	if (*cp != '/') {
302		strlcpy(dev, "/dev/", sizeof(dev));
303		strlcat(dev, cp, sizeof(dev));
304		cp = dev;
305	}
306
307	/*
308	 * Check if there is a character device by this name.
309	 */
310	if (stat(cp, &statbuf) < 0) {
311		if (!doit)
312			return errno != ENOENT;
313		option_error("Couldn't stat %s: %m", cp);
314		return 0;
315	}
316	if (!S_ISCHR(statbuf.st_mode)) {
317		if (doit)
318			option_error("%s is not a character device", cp);
319		return 0;
320	}
321
322	if (doit) {
323		strlcpy(devnam, cp, sizeof(devnam));
324		devstat = statbuf;
325		default_device = 0;
326	}
327
328	return 1;
329}
330
331static int
332setxonxoff(char **argv)
333{
334	lcp_wantoptions[0].asyncmap |= 0x000A0000;	/* escape ^S and ^Q */
335	lcp_wantoptions[0].neg_asyncmap = 1;
336
337	crtscts = -2;
338	return 1;
339}
340
341/*
342 * setescape - add chars to the set we escape on transmission.
343 */
344static int
345setescape(char **argv)
346{
347    int n, ret;
348    char *p, *endp;
349
350    p = *argv;
351    ret = 1;
352    while (*p) {
353	n = strtol(p, &endp, 16);
354	if (p == endp) {
355	    option_error("escape parameter contains invalid hex number '%s'",
356			 p);
357	    return 0;
358	}
359	p = endp;
360	if (n < 0 || n == 0x5E || n > 0xFF) {
361	    option_error("can't escape character 0x%x", n);
362	    ret = 0;
363	} else
364	    xmit_accm[n >> 5] |= 1 << (n & 0x1F);
365	while (*p == ',' || *p == ' ')
366	    ++p;
367    }
368    lcp_allowoptions[0].asyncmap = xmit_accm[0];
369    return ret;
370}
371
372static void
373printescape(option_t *opt, void (*printer)(void *, char *, ...), void *arg)
374{
375	int n;
376	int first = 1;
377
378	for (n = 0; n < 256; ++n) {
379		if (n == 0x7d)
380			n += 2;		/* skip 7d, 7e */
381		if (xmit_accm[n >> 5] & (1 << (n & 0x1f))) {
382			if (!first)
383				printer(arg, ",");
384			else
385				first = 0;
386			printer(arg, "%x", n);
387		}
388	}
389	if (first)
390		printer(arg, "oops # nothing escaped");
391}
392
393/*
394 * tty_init - do various tty-related initializations.
395 */
396void tty_init(void)
397{
398    add_notifier(&pidchange, maybe_relock, 0);
399    the_channel = &tty_channel;
400    xmit_accm[3] = 0x60000000;
401}
402
403/*
404 * tty_process_extra_options - work out which tty device we are using
405 * and read its options file.
406 */
407void tty_process_extra_options(void)
408{
409	using_pty = notty || ptycommand != NULL || pty_socket != NULL;
410	if (using_pty)
411		return;
412	if (default_device) {
413		char *p;
414		if (!isatty(0) || (p = ttyname(0)) == NULL) {
415			option_error("no device specified and stdin is not a tty");
416			exit(EXIT_OPTION_ERROR);
417		}
418		strlcpy(devnam, p, sizeof(devnam));
419		if (stat(devnam, &devstat) < 0)
420			fatal("Couldn't stat default device %s: %m", devnam);
421	}
422
423
424	/*
425	 * Parse the tty options file.
426	 * The per-tty options file should not change
427	 * ptycommand, pty_socket, notty or devnam.
428	 * options_for_tty doesn't override options set on the command line,
429	 * except for some privileged options.
430	 */
431	if (!options_for_tty())
432		exit(EXIT_OPTION_ERROR);
433}
434
435/*
436 * tty_check_options - do consistency checks on the options we were given.
437 */
438void
439tty_check_options(void)
440{
441	struct stat statbuf;
442	int fdflags;
443
444	if (demand && notty) {
445		option_error("demand-dialling is incompatible with notty");
446		exit(EXIT_OPTION_ERROR);
447	}
448	if (demand && connect_script == 0 && ptycommand == NULL
449	    && pty_socket == NULL) {
450		option_error("connect script is required for demand-dialling\n");
451		exit(EXIT_OPTION_ERROR);
452	}
453	/* default holdoff to 0 if no connect script has been given */
454	if (connect_script == 0 && !holdoff_specified)
455		holdoff = 0;
456
457	if (using_pty) {
458		if (!default_device) {
459			option_error("%s option precludes specifying device name",
460				     pty_socket? "socket": notty? "notty": "pty");
461			exit(EXIT_OPTION_ERROR);
462		}
463		if (ptycommand != NULL && notty) {
464			option_error("pty option is incompatible with notty option");
465			exit(EXIT_OPTION_ERROR);
466		}
467		if (pty_socket != NULL && (ptycommand != NULL || notty)) {
468			option_error("socket option is incompatible with pty and notty");
469			exit(EXIT_OPTION_ERROR);
470		}
471		default_device = notty;
472		lockflag = 0;
473		modem = 0;
474		if (notty && log_to_fd <= 1)
475			log_to_fd = -1;
476	} else {
477		/*
478		 * If the user has specified a device which is the same as
479		 * the one on stdin, pretend they didn't specify any.
480		 * If the device is already open read/write on stdin,
481		 * we assume we don't need to lock it, and we can open it
482		 * as root.
483		 */
484		if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
485		    && statbuf.st_rdev == devstat.st_rdev) {
486			default_device = 1;
487			fdflags = fcntl(0, F_GETFL);
488			if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
489				privopen = 1;
490		}
491	}
492	if (default_device)
493		nodetach = 1;
494
495	/*
496	 * Don't send log messages to the serial port, it tends to
497	 * confuse the peer. :-)
498	 */
499	if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
500	    && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
501		log_to_fd = -1;
502}
503
504/*
505 * connect_tty - get the serial port ready to start doing PPP.
506 * That is, open the serial port, set its speed and mode, and run
507 * the connector and/or welcomer.
508 */
509int connect_tty(void)
510{
511	char *connector;
512	int fdflags;
513#ifndef __linux__
514	struct stat statbuf;
515#endif
516	char numbuf[16];
517
518	/*
519	 * Get a pty master/slave pair if the pty, notty, socket,
520	 * or record options were specified.
521	 */
522	strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
523	pty_master = -1;
524	pty_slave = -1;
525	real_ttyfd = -1;
526	if (using_pty || record_file != NULL) {
527		if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
528			error("Couldn't allocate pseudo-tty");
529			status = EXIT_FATAL_ERROR;
530			return -1;
531		}
532		set_up_tty(pty_slave, 1);
533	}
534
535	/*
536	 * Lock the device if we've been asked to.
537	 */
538	status = EXIT_LOCK_FAILED;
539	if (lockflag && !privopen) {
540		if (lock(devnam) < 0)
541			goto errret;
542		locked = 1;
543	}
544
545	/*
546	 * Open the serial device and set it up to be the ppp interface.
547	 * First we open it in non-blocking mode so we can set the
548	 * various termios flags appropriately.  If we aren't dialling
549	 * out and we want to use the modem lines, we reopen it later
550	 * in order to wait for the carrier detect signal from the modem.
551	 */
552	got_sigterm = 0;
553	connector = doing_callback? callback_script: connect_script;
554	if (devnam[0] != 0) {
555		for (;;) {
556			/* If the user specified the device name, become the
557			   user before opening it. */
558			int err, prio;
559
560			prio = privopen? OPRIO_ROOT: tty_options[0].priority;
561			if (prio < OPRIO_ROOT && seteuid(uid) == -1) {
562				error("Unable to drop privileges before opening %s: %m\n",
563				      devnam);
564				status = EXIT_OPEN_FAILED;
565				goto errret;
566			}
567			real_ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
568			err = errno;
569			if (prio < OPRIO_ROOT && seteuid(0) == -1)
570				fatal("Unable to regain privileges");
571			if (real_ttyfd >= 0)
572				break;
573			errno = err;
574			if (err != EINTR) {
575				error("Failed to open %s: %m", devnam);
576				status = EXIT_OPEN_FAILED;
577			}
578			if (!persist || err != EINTR)
579				goto errret;
580		}
581		ttyfd = real_ttyfd;
582		if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
583		    || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
584			warn("Couldn't reset non-blocking mode on device: %m");
585
586#ifndef __linux__
587		/*
588		 * Linux 2.4 and above blocks normal writes to the tty
589		 * when it is in PPP line discipline, so this isn't needed.
590		 */
591		/*
592		 * Do the equivalent of `mesg n' to stop broadcast messages.
593		 */
594		if (fstat(ttyfd, &statbuf) < 0
595		    || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
596			warn("Couldn't restrict write permissions to %s: %m", devnam);
597		} else
598			tty_mode = statbuf.st_mode;
599#endif /* __linux__ */
600
601		/*
602		 * Set line speed, flow control, etc.
603		 * If we have a non-null connection or initializer script,
604		 * on most systems we set CLOCAL for now so that we can talk
605		 * to the modem before carrier comes up.  But this has the
606		 * side effect that we might miss it if CD drops before we
607		 * get to clear CLOCAL below.  On systems where we can talk
608		 * successfully to the modem with CLOCAL clear and CD down,
609		 * we could clear CLOCAL at this point.
610		 */
611		set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
612				   || initializer != NULL));
613	}
614
615	/*
616	 * If the pty, socket, notty and/or record option was specified,
617	 * start up the character shunt now.
618	 */
619	status = EXIT_PTYCMD_FAILED;
620	if (ptycommand != NULL) {
621		if (record_file != NULL) {
622			int ipipe[2], opipe[2], ok;
623
624			if (pipe(ipipe) < 0 || pipe(opipe) < 0)
625				fatal("Couldn't create pipes for record option: %m");
626
627			/* don't leak these to the ptycommand */
628			(void) fcntl(ipipe[0], F_SETFD, FD_CLOEXEC);
629			(void) fcntl(opipe[1], F_SETFD, FD_CLOEXEC);
630
631			ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
632				&& start_charshunt(ipipe[0], opipe[1]);
633			close(ipipe[0]);
634			close(ipipe[1]);
635			close(opipe[0]);
636			close(opipe[1]);
637			if (!ok)
638				goto errret;
639		} else {
640			if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
641				goto errret;
642		}
643	} else if (pty_socket != NULL) {
644		int fd = open_socket(pty_socket);
645		if (fd < 0)
646			goto errret;
647		if (!start_charshunt(fd, fd))
648			goto errret;
649		close(fd);
650	} else if (notty) {
651		if (!start_charshunt(0, 1))
652			goto errret;
653		dup2(fd_devnull, 0);
654		dup2(fd_devnull, 1);
655		if (log_to_fd == 1)
656			log_to_fd = -1;
657		if (log_to_fd != 2)
658			dup2(fd_devnull, 2);
659	} else if (record_file != NULL) {
660		int fd = dup(ttyfd);
661		if (!start_charshunt(fd, fd))
662			goto errret;
663	}
664
665	if (using_pty || record_file != NULL) {
666		ttyfd = pty_slave;
667		close(pty_master);
668		pty_master = -1;
669	}
670
671	/* run connection script */
672	if ((connector && connector[0]) || initializer) {
673		if (real_ttyfd != -1) {
674			/* XXX do this if doing_callback == CALLBACK_DIALIN? */
675			if (!default_device && modem) {
676				setdtr(real_ttyfd, 0);	/* in case modem is off hook */
677				sleep(1);
678				setdtr(real_ttyfd, 1);
679			}
680		}
681
682		if (initializer && initializer[0]) {
683			if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
684				error("Initializer script failed");
685				status = EXIT_INIT_FAILED;
686				goto errretf;
687			}
688			if (got_sigterm) {
689				disconnect_tty();
690				goto errretf;
691			}
692			info("Serial port initialized.");
693		}
694
695		if (connector && connector[0]) {
696			if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
697				error("Connect script failed");
698				status = EXIT_CONNECT_FAILED;
699				goto errretf;
700			}
701			if (got_sigterm) {
702				disconnect_tty();
703				goto errretf;
704			}
705			info("Serial connection established.");
706		}
707
708		/* set line speed, flow control, etc.;
709		   clear CLOCAL if modem option */
710		if (real_ttyfd != -1)
711			set_up_tty(real_ttyfd, 0);
712
713		if (doing_callback == CALLBACK_DIALIN)
714			connector = NULL;
715	}
716
717	/* reopen tty if necessary to wait for carrier */
718	if (connector == NULL && modem && devnam[0] != 0) {
719		int i;
720		for (;;) {
721			if ((i = open(devnam, O_RDWR)) >= 0)
722				break;
723			if (errno != EINTR) {
724				error("Failed to reopen %s: %m", devnam);
725				status = EXIT_OPEN_FAILED;
726			}
727			if (!persist || errno != EINTR || hungup || got_sigterm)
728				goto errret;
729		}
730		close(i);
731	}
732
733	slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
734	script_setenv("SPEED", numbuf, 0);
735
736	/* run welcome script, if any */
737	if (welcomer && welcomer[0]) {
738		if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
739			warn("Welcome script failed");
740	}
741
742	/*
743	 * If we are initiating this connection, wait for a short
744	 * time for something from the peer.  This can avoid bouncing
745	 * our packets off his tty before he has it set up.
746	 */
747	if (connector != NULL || ptycommand != NULL || pty_socket != NULL)
748		listen_time = connect_delay;
749
750	return ttyfd;
751
752 errretf:
753	if (real_ttyfd >= 0)
754		tcflush(real_ttyfd, TCIOFLUSH);
755 errret:
756	if (pty_master >= 0) {
757		close(pty_master);
758		pty_master = -1;
759	}
760	ttyfd = -1;
761	if (got_sigterm)
762		asked_to_quit = 1;
763	return -1;
764}
765
766
767void disconnect_tty(void)
768{
769	if (disconnect_script == NULL || hungup)
770		return;
771	if (real_ttyfd >= 0)
772		set_up_tty(real_ttyfd, 1);
773	if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
774		warn("disconnect script failed");
775	} else {
776		info("Serial link disconnected.");
777	}
778	stop_charshunt(NULL, 0);
779}
780
781void tty_close_fds(void)
782{
783	if (pty_slave >= 0)
784		close(pty_slave);
785	if (real_ttyfd >= 0) {
786		close(real_ttyfd);
787		real_ttyfd = -1;
788	}
789	/* N.B. ttyfd will == either pty_slave or real_ttyfd */
790}
791
792void cleanup_tty(void)
793{
794	if (real_ttyfd >= 0)
795		finish_tty();
796	tty_close_fds();
797	if (locked) {
798		unlock();
799		locked = 0;
800	}
801}
802
803/*
804 * tty_do_send_config - set transmit-side PPP configuration.
805 * We set the extended transmit ACCM here as well.
806 */
807void
808tty_do_send_config(int mtu, u_int32_t accm, int pcomp, int accomp)
809{
810	tty_set_xaccm(xmit_accm);
811	tty_send_config(mtu, accm, pcomp, accomp);
812}
813
814/*
815 * finish_tty - restore the terminal device to its original settings
816 */
817static void
818finish_tty(void)
819{
820	/* drop dtr to hang up */
821	if (!default_device && modem) {
822		setdtr(real_ttyfd, 0);
823		/*
824		 * This sleep is in case the serial port has CLOCAL set by default,
825		 * and consequently will reassert DTR when we close the device.
826		 */
827		sleep(1);
828	}
829
830	restore_tty(real_ttyfd);
831
832#ifndef __linux__
833	if (tty_mode != (mode_t) -1) {
834		if (fchmod(real_ttyfd, tty_mode) != 0)
835			error("Couldn't restore tty permissions");
836	}
837#endif /* __linux__ */
838
839	close(real_ttyfd);
840	real_ttyfd = -1;
841}
842
843/*
844 * maybe_relock - our PID has changed, maybe update the lock file.
845 */
846static void
847maybe_relock(void *arg, int pid)
848{
849    if (locked)
850	relock(pid);
851}
852
853/*
854 * open_socket - establish a stream socket connection to the nominated
855 * host and port.
856 */
857static int
858open_socket(char *dest)
859{
860    char *sep, *endp = NULL;
861    int sock, port = -1;
862    u_int32_t host;
863    struct hostent *hent;
864    struct sockaddr_in sad;
865
866    /* parse host:port and resolve host to an IP address */
867    sep = strchr(dest, ':');
868    if (sep != NULL)
869	port = strtol(sep+1, &endp, 10);
870    if (port < 0 || endp == sep+1 || sep == dest) {
871	error("Can't parse host:port for socket destination");
872	return -1;
873    }
874    *sep = 0;
875    host = inet_addr(dest);
876    if (host == (u_int32_t) -1) {
877	hent = gethostbyname(dest);
878	if (hent == NULL) {
879	    error("%s: unknown host in socket option", dest);
880	    *sep = ':';
881	    return -1;
882	}
883	host = *(u_int32_t *)(hent->h_addr_list[0]);
884    }
885    *sep = ':';
886
887    /* get a socket and connect it to the other end */
888    sock = socket(PF_INET, SOCK_STREAM, 0);
889    if (sock < 0) {
890	error("Can't create socket: %m");
891	return -1;
892    }
893    memset(&sad, 0, sizeof(sad));
894    sad.sin_family = AF_INET;
895    sad.sin_port = htons(port);
896    sad.sin_addr.s_addr = host;
897    if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
898	error("Can't connect to %s: %m", dest);
899	close(sock);
900	return -1;
901    }
902
903    return sock;
904}
905
906
907/*
908 * start_charshunt - create a child process to run the character shunt.
909 */
910static int
911start_charshunt(int ifd, int ofd)
912{
913    int cpid;
914
915    cpid = safe_fork(ifd, ofd, (log_to_fd >= 0? log_to_fd: 2));
916    if (cpid == -1) {
917	error("Can't fork process for character shunt: %m");
918	return 0;
919    }
920    if (cpid == 0) {
921	/* child */
922	reopen_log();
923	if (!nodetach)
924	    log_to_fd = -1;
925	else if (log_to_fd >= 0)
926	    log_to_fd = 2;
927	setgid(getgid());
928	setuid(uid);
929	if (getuid() != uid)
930	    fatal("setuid failed");
931	charshunt(0, 1, record_file);
932	exit(0);
933    }
934    charshunt_pid = cpid;
935    record_child(cpid, "pppd (charshunt)", charshunt_done, NULL, 1);
936    return 1;
937}
938
939static void
940charshunt_done(void *arg)
941{
942	charshunt_pid = 0;
943}
944
945static void
946stop_charshunt(void *arg, int sig)
947{
948	if (charshunt_pid)
949		kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
950}
951
952/*
953 * charshunt - the character shunt, which passes characters between
954 * the pty master side and the serial port (or stdin/stdout).
955 * This runs as the user (not as root).
956 * (We assume ofd >= ifd which is true the way this gets called. :-).
957 */
958static void
959charshunt(int ifd, int ofd, char *record_file)
960{
961    int n, nfds;
962    fd_set ready, writey;
963    u_char *ibufp, *obufp;
964    int nibuf, nobuf;
965    int flags;
966    int pty_readable, stdin_readable;
967    struct timeval lasttime;
968    FILE *recordf = NULL;
969    int ilevel, olevel, max_level;
970    struct timeval levelt, tout, *top;
971    extern u_char inpacket_buf[];
972
973    /*
974     * Reset signal handlers.
975     */
976    signal(SIGHUP, SIG_IGN);		/* Hangup */
977    signal(SIGINT, SIG_DFL);		/* Interrupt */
978    signal(SIGTERM, SIG_DFL);		/* Terminate */
979    signal(SIGCHLD, SIG_DFL);
980    signal(SIGUSR1, SIG_DFL);
981    signal(SIGUSR2, SIG_DFL);
982    signal(SIGABRT, SIG_DFL);
983    signal(SIGALRM, SIG_DFL);
984    signal(SIGFPE, SIG_DFL);
985    signal(SIGILL, SIG_DFL);
986    signal(SIGPIPE, SIG_DFL);
987    signal(SIGQUIT, SIG_DFL);
988    signal(SIGSEGV, SIG_DFL);
989#ifdef SIGBUS
990    signal(SIGBUS, SIG_DFL);
991#endif
992#ifdef SIGEMT
993    signal(SIGEMT, SIG_DFL);
994#endif
995#ifdef SIGPOLL
996    signal(SIGPOLL, SIG_DFL);
997#endif
998#ifdef SIGPROF
999    signal(SIGPROF, SIG_DFL);
1000#endif
1001#ifdef SIGSYS
1002    signal(SIGSYS, SIG_DFL);
1003#endif
1004#ifdef SIGTRAP
1005    signal(SIGTRAP, SIG_DFL);
1006#endif
1007#ifdef SIGVTALRM
1008    signal(SIGVTALRM, SIG_DFL);
1009#endif
1010#ifdef SIGXCPU
1011    signal(SIGXCPU, SIG_DFL);
1012#endif
1013#ifdef SIGXFSZ
1014    signal(SIGXFSZ, SIG_DFL);
1015#endif
1016
1017    /*
1018     * Check that the fds won't overrun the fd_sets
1019     */
1020    if (ifd >= FD_SETSIZE || ofd >= FD_SETSIZE || pty_master >= FD_SETSIZE)
1021	fatal("internal error: file descriptor too large (%d, %d, %d)",
1022	      ifd, ofd, pty_master);
1023
1024    /*
1025     * Open the record file if required.
1026     */
1027    if (record_file != NULL) {
1028	recordf = fopen(record_file, "a");
1029	if (recordf == NULL)
1030	    error("Couldn't create record file %s: %m", record_file);
1031    }
1032
1033    /* set all the fds to non-blocking mode */
1034    flags = fcntl(pty_master, F_GETFL);
1035    if (flags == -1
1036	|| fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1037	warn("couldn't set pty master to nonblock: %m");
1038    flags = fcntl(ifd, F_GETFL);
1039    if (flags == -1
1040	|| fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1041	warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1042    if (ofd != ifd) {
1043	flags = fcntl(ofd, F_GETFL);
1044	if (flags == -1
1045	    || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1046	    warn("couldn't set stdout to nonblock: %m");
1047    }
1048
1049    nibuf = nobuf = 0;
1050    ibufp = obufp = NULL;
1051    pty_readable = stdin_readable = 1;
1052
1053    ilevel = olevel = 0;
1054    get_time(&levelt);
1055    if (max_data_rate) {
1056	max_level = max_data_rate / 10;
1057	if (max_level < 100)
1058	    max_level = 100;
1059    } else
1060	max_level = PPP_MRU + PPP_HDRLEN + 1;
1061
1062    nfds = (ofd > pty_master? ofd: pty_master) + 1;
1063    if (recordf != NULL) {
1064	gettimeofday(&lasttime, NULL);
1065	putc(7, recordf);	/* put start marker */
1066	putc(lasttime.tv_sec >> 24, recordf);
1067	putc(lasttime.tv_sec >> 16, recordf);
1068	putc(lasttime.tv_sec >> 8, recordf);
1069	putc(lasttime.tv_sec, recordf);
1070	lasttime.tv_usec = 0;
1071    }
1072
1073    while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1074	top = 0;
1075	tout.tv_sec = 0;
1076	tout.tv_usec = 10000;
1077	FD_ZERO(&ready);
1078	FD_ZERO(&writey);
1079	if (nibuf != 0) {
1080	    if (ilevel >= max_level)
1081		top = &tout;
1082	    else
1083		FD_SET(pty_master, &writey);
1084	} else if (stdin_readable)
1085	    FD_SET(ifd, &ready);
1086	if (nobuf != 0) {
1087	    if (olevel >= max_level)
1088		top = &tout;
1089	    else
1090		FD_SET(ofd, &writey);
1091	} else if (pty_readable)
1092	    FD_SET(pty_master, &ready);
1093	if (select(nfds, &ready, &writey, NULL, top) < 0) {
1094	    if (errno != EINTR)
1095		fatal("select");
1096	    continue;
1097	}
1098	if (max_data_rate) {
1099	    double dt;
1100	    int nbt;
1101	    struct timeval now;
1102
1103	    get_time(&now);
1104	    dt = (now.tv_sec - levelt.tv_sec
1105		  + (now.tv_usec - levelt.tv_usec) / 1e6);
1106	    nbt = (int)(dt * max_data_rate);
1107	    ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
1108	    olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
1109	    levelt = now;
1110	} else
1111	    ilevel = olevel = 0;
1112	if (FD_ISSET(ifd, &ready)) {
1113	    ibufp = inpacket_buf;
1114	    nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
1115	    if (nibuf < 0 && errno == EIO)
1116		nibuf = 0;
1117	    if (nibuf < 0) {
1118		if (!(errno == EINTR || errno == EAGAIN)) {
1119		    error("Error reading standard input: %m");
1120		    break;
1121		}
1122		nibuf = 0;
1123	    } else if (nibuf == 0) {
1124		/* end of file from stdin */
1125		stdin_readable = 0;
1126		if (recordf)
1127		    if (!record_write(recordf, 4, NULL, 0, &lasttime))
1128			recordf = NULL;
1129	    } else {
1130		FD_SET(pty_master, &writey);
1131		if (recordf)
1132		    if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1133			recordf = NULL;
1134	    }
1135	}
1136	if (FD_ISSET(pty_master, &ready)) {
1137	    obufp = outpacket_buf;
1138	    nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
1139	    if (nobuf < 0 && errno == EIO)
1140		nobuf = 0;
1141	    if (nobuf < 0) {
1142		if (!(errno == EINTR || errno == EAGAIN)) {
1143		    error("Error reading pseudo-tty master: %m");
1144		    break;
1145		}
1146		nobuf = 0;
1147	    } else if (nobuf == 0) {
1148		/* end of file from the pty - slave side has closed */
1149		pty_readable = 0;
1150		stdin_readable = 0;	/* pty is not writable now */
1151		nibuf = 0;
1152		close(ofd);
1153		if (recordf)
1154		    if (!record_write(recordf, 3, NULL, 0, &lasttime))
1155			recordf = NULL;
1156	    } else {
1157		FD_SET(ofd, &writey);
1158		if (recordf)
1159		    if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1160			recordf = NULL;
1161	    }
1162	} else if (!stdin_readable)
1163	    pty_readable = 0;
1164	if (FD_ISSET(ofd, &writey)) {
1165	    n = nobuf;
1166	    if (olevel + n > max_level)
1167		n = max_level - olevel;
1168	    n = write(ofd, obufp, n);
1169	    if (n < 0) {
1170		if (errno == EIO) {
1171		    pty_readable = 0;
1172		    nobuf = 0;
1173		} else if (errno != EAGAIN && errno != EINTR) {
1174		    error("Error writing standard output: %m");
1175		    break;
1176		}
1177	    } else {
1178		obufp += n;
1179		nobuf -= n;
1180		olevel += n;
1181	    }
1182	}
1183	if (FD_ISSET(pty_master, &writey)) {
1184	    n = nibuf;
1185	    if (ilevel + n > max_level)
1186		n = max_level - ilevel;
1187	    n = write(pty_master, ibufp, n);
1188	    if (n < 0) {
1189		if (errno == EIO) {
1190		    stdin_readable = 0;
1191		    nibuf = 0;
1192		} else if (errno != EAGAIN && errno != EINTR) {
1193		    error("Error writing pseudo-tty master: %m");
1194		    break;
1195		}
1196	    } else {
1197		ibufp += n;
1198		nibuf -= n;
1199		ilevel += n;
1200	    }
1201	}
1202    }
1203    exit(0);
1204}
1205
1206static int
1207record_write(FILE *f, int code, u_char *buf, int nb, struct timeval *tp)
1208{
1209    struct timeval now;
1210    int diff;
1211
1212    gettimeofday(&now, NULL);
1213    now.tv_usec /= 100000;	/* actually 1/10 s, not usec now */
1214    diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1215    if (diff > 0) {
1216	if (diff > 255) {
1217	    putc(5, f);
1218	    putc(diff >> 24, f);
1219	    putc(diff >> 16, f);
1220	    putc(diff >> 8, f);
1221	    putc(diff, f);
1222	} else {
1223	    putc(6, f);
1224	    putc(diff, f);
1225	}
1226	*tp = now;
1227    }
1228    putc(code, f);
1229    if (buf != NULL) {
1230	putc(nb >> 8, f);
1231	putc(nb, f);
1232	fwrite(buf, nb, 1, f);
1233    }
1234    fflush(f);
1235    if (ferror(f)) {
1236	error("Error writing record file: %m");
1237	return 0;
1238    }
1239    return 1;
1240}
1241