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