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