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