xref: /illumos-gate/usr/src/cmd/cmd-inet/usr.bin/pppd/main.c (revision 4f62a6570dcd50f97b2c01e95cbb683b3f9d7a7c)
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
5  * Use is subject to license terms.
6  *
7  * Permission to use, copy, modify, and distribute this software and its
8  * documentation is hereby granted, provided that the above copyright
9  * notice appears in all copies.
10  *
11  * SUN MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF
12  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
13  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT.  SUN SHALL NOT BE LIABLE FOR
15  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
16  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES
17  *
18  * Copyright (c) 1989 Carnegie Mellon University.
19  * All rights reserved.
20  *
21  * Redistribution and use in source and binary forms are permitted
22  * provided that the above copyright notice and this paragraph are
23  * duplicated in all such forms and that any documentation,
24  * advertising materials, and other materials related to such
25  * distribution and use acknowledge that the software was developed
26  * by Carnegie Mellon University.  The name of the
27  * University may not be used to endorse or promote products derived
28  * from this software without specific prior written permission.
29  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
31  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
32  */
33 /*
34  * Copyright (c) 2016 by Delphix. All rights reserved.
35  */
36 
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <signal.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <syslog.h>
45 #include <netdb.h>
46 #include <pwd.h>
47 #include <setjmp.h>
48 #include <sys/param.h>
49 #include <sys/types.h>
50 #include <sys/wait.h>
51 #include <sys/time.h>
52 #include <sys/resource.h>
53 #include <sys/stat.h>
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57 
58 #include "pppd.h"
59 #include "magic.h"
60 #include "fsm.h"
61 #include "lcp.h"
62 #include "ipcp.h"
63 #ifdef INET6
64 #include "ipv6cp.h"
65 #endif
66 #include "upap.h"
67 #include "chap.h"
68 #include "ccp.h"
69 #include "pathnames.h"
70 #include "patchlevel.h"
71 
72 #ifdef HAVE_MULTILINK
73 #include "tdb.h"
74 #endif
75 
76 #ifdef CBCP_SUPPORT
77 #include "cbcp.h"
78 #endif
79 
80 #ifdef IPX_CHANGE
81 #include "ipxcp.h"
82 #endif /* IPX_CHANGE */
83 #ifdef AT_CHANGE
84 #include "atcp.h"
85 #endif
86 
87 /* interface vars */
88 char ifname[32];		/* Interface name */
89 int ifunit = -1;		/* Interface unit number */
90 
91 char *progname;			/* Name of this program */
92 char hostname[MAXHOSTNAMELEN+1]; /* Our hostname */
93 static char pidfilename[MAXPATHLEN]; /* name of pid file */
94 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
95 char ppp_devnam[MAXPATHLEN];	/* name of PPP tty (maybe ttypx) */
96 static uid_t uid;		/* Our real user-id */
97 static int conn_running;	/* we have a [dis]connector running */
98 
99 int ttyfd;			/* Serial port file descriptor */
100 mode_t tty_mode = (mode_t)-1;	/* Original access permissions to tty */
101 int baud_rate;			/* Actual bits/second for serial device */
102 bool hungup;			/* terminal has been hung up */
103 bool privileged;		/* we're running as real uid root */
104 bool need_holdoff;		/* need holdoff period before restarting */
105 bool detached;			/* have detached from terminal */
106 struct stat devstat;		/* result of stat() on devnam */
107 bool prepass = 0;		/* doing prepass to find device name */
108 int devnam_fixed;		/* set while in options.ttyxx file */
109 volatile int status;		/* exit status for pppd */
110 int unsuccess;			/* # unsuccessful connection attempts */
111 int do_callback;		/* != 0 if we should do callback next */
112 int doing_callback;		/* != 0 if we are doing callback */
113 char *callback_script;		/* script for doing callback */
114 #ifdef HAVE_MULTILINK
115 TDB_CONTEXT *pppdb;		/* database for storing status etc. */
116 char db_key[32];
117 #endif
118 
119 /*
120  * For plug-in usage:
121  *
122  *	holdoff_hook - Can be used to change the demand-dial hold-off
123  *		time dynamically.  This is normally set by the
124  *		"holdoff" option, and is 30 seconds by default.
125  *
126  *	new_phase_hook - This is called for each change in the PPP
127  *		phase (per RFC 1661).  This can be used to log
128  *		progress.
129  *
130  *	check_options_hook - This is called before doing sys_init()
131  *		and allows the plugin to verify the selected options.
132  *
133  *	updown_script_hook - This is called with the proposed
134  *		command-line arguments for any of the
135  *		/etc/ppp/{ip,ipv6,ipx,auth}-{up,down} scripts before
136  *		fork/exec.  It can be used to add or change arguments.
137  *
138  *	device_pipe_hook - If this is set, then an extra fd (3) is
139  *		passed to the connect/disconnect script.  This extra
140  *		fd is the write side of a pipe, and the read side is
141  *		passed to this routine.  This can be used to pass
142  *		arbitrary data from the script back to pppd.
143  */
144 int (*holdoff_hook) __P((void)) = NULL;
145 int (*new_phase_hook) __P((int new, int old)) = NULL;
146 int (*check_options_hook) __P((uid_t uid)) = NULL;
147 int (*updown_script_hook) __P((const char ***argsp)) = NULL;
148 void (*device_pipe_hook) __P((int pipefd)) = NULL;
149 
150 static int fd_ppp = -1;		/* fd for talking PPP */
151 static int fd_loop;		/* fd for getting demand-dial packets */
152 static int pty_master;		/* fd for master side of pty */
153 int pty_slave = -1;		/* fd for slave side of pty */
154 static int real_ttyfd;		/* fd for actual serial port (not pty) */
155 
156 int phase;			/* where the link is at */
157 int kill_link;
158 int open_ccp_flag;
159 
160 static int waiting;		/* for input from peer or timer expiration */
161 static sigjmp_buf sigjmp;
162 
163 char **script_env;		/* Env. variable values for scripts */
164 int s_env_nalloc;		/* # words avail at script_env */
165 
166 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
167 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
168 u_char nak_buffer[PPP_MRU];	/* where we construct a nak packet */
169 
170 static int n_children;		/* # child processes still running */
171 static bool got_sigchld;	/* set if we have received a SIGCHLD */
172 static sigset_t main_sigmask;	/* signals blocked while dispatching */
173 
174 static bool locked;		/* lock() has succeeded */
175 static bool privopen;		/* don't lock, open device as root */
176 
177 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
178 
179 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
180 int ngroups;			/* How many groups valid in groups */
181 
182 static struct timeval start_time; /* Time when link was started. */
183 
184 struct pppd_stats link_stats;
185 int link_connect_time;
186 bool link_stats_valid;
187 
188 static pid_t charshunt_pid;	/* Process ID for charshunt */
189 
190 extern option_t general_options[];
191 extern option_t auth_options[];
192 
193 /*
194  * We maintain a list of child process pids and
195  * functions to call when they exit.
196  */
197 struct subprocess {
198     pid_t	pid;
199     char	*prog;
200     void	(*done) __P((void *, int));
201     void	*arg;
202     struct subprocess *next;
203 };
204 
205 static struct subprocess *children;
206 
207 /* Prototypes for procedures local to this file. */
208 
209 static void setup_signals __P((void));
210 static void create_pidfile __P((void));
211 static void create_linkpidfile __P((void));
212 static void cleanup __P((void));
213 static void close_tty __P((void));
214 static void get_input __P((void));
215 static void calltimeout __P((void));
216 static struct timeval *timeleft __P((struct timeval *));
217 static void kill_my_pg __P((int));
218 static void hup __P((int));
219 static void term __P((int));
220 static void chld __P((int));
221 static void toggle_debug __P((int));
222 static void open_ccp __P((int));
223 static void bad_signal __P((int));
224 static void holdoff_end __P((void *));
225 static int device_script __P((char *, int, int, int, char *));
226 static int reap_kids __P((int waitfor));
227 static void record_child __P((pid_t, char *, void (*) (void *, int), void *));
228 static int open_socket __P((char *));
229 static int start_charshunt __P((int, int));
230 static void charshunt_done __P((void *, int));
231 static void charshunt __P((int, int, char *));
232 static int record_write __P((FILE *, int code, u_char *buf, int nb,
233     struct timeval *));
234 static void final_reap __P((void));
235 
236 #ifdef HAVE_MULTILINK
237 static void update_db_entry __P((void));
238 static void add_db_key __P((const char *));
239 static void delete_db_key __P((const char *));
240 static void cleanup_db __P((void));
241 #endif
242 
243 int main __P((int, char *[]));
244 
245 #ifdef ultrix
246 #undef	O_NONBLOCK
247 #define	O_NONBLOCK	O_NDELAY
248 #endif
249 
250 #ifdef ULTRIX
251 #define setlogmask(x)	0
252 #endif
253 
254 /* Backward compatibility for Linux */
255 #ifndef RECMARK_TIMESTART
256 #define	RECMARK_STARTSEND	1
257 #define	RECMARK_STARTRECV	2
258 #define	RECMARK_ENDSEND		3
259 #define	RECMARK_ENDRECV		4
260 #define	RECMARK_TIMEDELTA32	5
261 #define	RECMARK_TIMEDELTA8	6
262 #define	RECMARK_TIMESTART	7
263 #endif
264 
265 /*
266  * PPP Data Link Layer "protocol" table.
267  * One entry per supported protocol.
268  * The last entry must be NULL.
269  */
270 struct protent *protocols[] = {
271     &lcp_protent,
272     &pap_protent,
273     &chap_protent,
274 #ifdef CBCP_SUPPORT
275     &cbcp_protent,
276 #endif
277     &ipcp_protent,
278 #ifdef INET6
279     &ipv6cp_protent,
280 #endif
281     &ccp_protent,
282 #ifdef IPX_CHANGE
283     &ipxcp_protent,
284 #endif
285 #ifdef AT_CHANGE
286     &atcp_protent,
287 #endif
288     NULL
289 };
290 
291 int
main(argc,argv)292 main(argc, argv)
293     int argc;
294     char *argv[];
295 {
296     int i, fdflags, t;
297     char *p, *connector;
298     struct passwd *pw;
299     struct timeval timo;
300     struct protent *protp;
301     struct stat statbuf;
302     char numbuf[16];
303 
304     ifname[0] = '\0';
305     new_phase(PHASE_INITIALIZE);
306 
307     /*
308      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
309      * This way we can close 0, 1, 2 in detach() without clobbering
310      * a fd that we are using.
311      */
312     if ((i = open(_PATH_DEVNULL, O_RDWR)) >= 0) {
313 	while (0 <= i && i <= 2)
314 	    i = dup(i);
315 	if (i >= 0)
316 	    (void) close(i);
317     }
318 
319     script_env = NULL;
320 
321     /* Initialize syslog facilities */
322     reopen_log();
323 
324     if (gethostname(hostname, MAXHOSTNAMELEN+1) < 0 ) {
325 	option_error("Couldn't get hostname: %m");
326 	exit(1);
327     }
328     hostname[MAXHOSTNAMELEN] = '\0';
329 
330     /* make sure we don't create world or group writable files. */
331     (void) umask(umask(0777) | 022);
332 
333     uid = getuid();
334     privileged = (uid == 0);
335     (void) slprintf(numbuf, sizeof(numbuf), "%d", uid);
336     script_setenv("ORIG_UID", numbuf, 0);
337 
338     ngroups = getgroups(NGROUPS_MAX, groups);
339 
340     /*
341      * Initialize magic number generator now so that protocols may
342      * use magic numbers in initialization.
343      */
344     magic_init();
345 
346     progname = *argv;
347     prepass = 0;
348     /*
349      * Initialize to the standard option set, then parse, in order, the
350      * system options file, the user's options file, the tty's options file,
351      * and the command line arguments.  At last, install the options declared
352      * by each protocol into the extra_option list.
353      */
354     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
355         (*protp->init)(0);
356 	if (protp->options != NULL) {
357 	    add_options(protp->options);
358 	}
359     }
360 
361     /*
362      * Install "generic" options into the extra_options list.
363      */
364     add_options(auth_options);
365     add_options(general_options);
366 
367     /* Install any system-specific options (or remove unusable ones) */
368     sys_options();
369 
370     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
371 	|| !options_from_user())
372 	exit(EXIT_OPTION_ERROR);
373 
374     /* scan command line and options files to find device name */
375     prepass = 1;
376     (void) parse_args(argc-1, argv+1);
377     prepass = 0;
378 
379     /*
380      * Work out the device name, if it hasn't already been specified.
381      */
382     using_pty = notty || ptycommand != NULL || pty_socket != NULL;
383     if (!using_pty && default_device && !direct_tty) {
384 	char *p;
385 
386 	if (!isatty(0) || (p = ttyname(0)) == NULL) {
387 	    option_error("no device specified and stdin is not a tty");
388 	    exit(EXIT_OPTION_ERROR);
389 	}
390 	(void) strlcpy(devnam, p, sizeof(devnam));
391 	if (stat(devnam, &devstat) < 0)
392 	    fatal("Couldn't stat default device %s: %m", devnam);
393     }
394 
395     /*
396      * Parse the tty options file and the command line.
397      * The per-tty options file should not change
398      * ptycommand, pty_socket, notty or devnam.
399      */
400     devnam_fixed = 1;
401     if (!using_pty && !direct_tty) {
402 	if (!options_for_tty())
403 	    exit(EXIT_OPTION_ERROR);
404     }
405 
406     devnam_fixed = 0;
407     if (!parse_args(argc-1, argv+1))
408 	exit(EXIT_OPTION_ERROR);
409 
410     /*
411      * Check that we are running as root.
412      */
413     if (geteuid() != 0) {
414 	option_error("must be root to run %s, since it is not setuid-root",
415 		     argv[0]);
416 	exit(EXIT_NOT_ROOT);
417     }
418 
419     if (!ppp_available()) {
420 	option_error(no_ppp_msg);
421 	exit(EXIT_NO_KERNEL_SUPPORT);
422     }
423 
424     /*
425      * Check that the options given are valid and consistent.
426      */
427     if (!sys_check_options())
428 	exit(EXIT_OPTION_ERROR);
429     auth_check_options();
430 #ifdef HAVE_MULTILINK
431     mp_check_options();
432 #endif
433     for (i = 0; (protp = protocols[i]) != NULL; ++i)
434 	if (protp->enabled_flag && protp->check_options != NULL)
435 	    (*protp->check_options)();
436     if (demand && (connect_script == NULL)) {
437 	option_error("connect script is required for demand-dialling\n");
438 	exit(EXIT_OPTION_ERROR);
439     }
440     if (updetach && (nodetach || demand)) {
441 	option_error("updetach cannot be used with %s",
442 	    nodetach ? "nodetach" : "demand");
443 	exit(EXIT_OPTION_ERROR);
444     }
445     /* default holdoff to 0 if no connect script has been given */
446     if ((connect_script == NULL) && !holdoff_specified)
447 	holdoff = 0;
448 
449     if (using_pty || direct_tty) {
450 	if (!default_device) {
451 	    option_error("%s option precludes specifying device name",
452 			 notty? "notty": "pty");
453 	    exit(EXIT_OPTION_ERROR);
454 	}
455 	if (ptycommand != NULL && (notty || direct_tty)) {
456 	    option_error("pty option is incompatible with notty option");
457 	    exit(EXIT_OPTION_ERROR);
458 	}
459 	if (pty_socket != NULL && (ptycommand != NULL || notty ||
460 	    direct_tty)) {
461 	    option_error("socket option is incompatible with pty and notty");
462 	    exit(EXIT_OPTION_ERROR);
463 	}
464 	default_device = notty || direct_tty;
465 	lockflag = 0;
466 	modem = 0;
467 	if (default_device && log_to_fd <= 1)
468 	    log_to_fd = -1;
469     } else {
470 	/*
471 	 * If the user has specified a device which is the same as
472 	 * the one on stdin, pretend they didn't specify any.
473 	 * If the device is already open read/write on stdin,
474 	 * we assume we don't need to lock it, and we can open it as root.
475 	 */
476 	if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
477 	    && statbuf.st_rdev == devstat.st_rdev) {
478 	    default_device = 1;
479 	    fdflags = fcntl(0, F_GETFL);
480 	    if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
481 		privopen = 1;
482 	}
483     }
484     if (default_device)
485 	nodetach = 1;
486 
487     /*
488      * Don't send log messages to the serial port, it tends to
489      * confuse the peer. :-)
490      */
491     if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
492 	&& S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
493 	log_to_fd = -1;
494     early_log = 0;
495 
496     if (debug)
497 	(void) setlogmask(LOG_UPTO(LOG_DEBUG));
498 
499     /*
500      * Initialize system-dependent stuff.
501      */
502     if (check_options_hook != NULL &&
503 	(*check_options_hook)(uid) == -1) {
504 	exit(EXIT_OPTION_ERROR);
505     }
506     sys_init(!devnam_info.priv && !privopen);
507 
508 #ifdef HAVE_MULTILINK
509     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
510     if (pppdb != NULL) {
511 	(void) slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
512 	update_db_entry();
513     } else {
514 	warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
515 	if (multilink) {
516 	    warn("Warning: disabling multilink");
517 	    multilink = 0;
518 	}
519     }
520 #endif
521 
522     /*
523      * Detach ourselves from the terminal, if required, and identify
524      * who is running us.  Printing to stderr stops here unless
525      * nodetach or updetach is set.
526      */
527     if (!nodetach && !updetach)
528 	detach();
529     p = getlogin();
530     if (p == NULL) {
531 	pw = getpwuid(uid);
532 	if (pw != NULL && pw->pw_name != NULL)
533 	    p = pw->pw_name;
534 	else
535 	    p = "(unknown)";
536     }
537     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
538 	   VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
539     script_setenv("PPPLOGNAME", p, 0);
540 
541     if (devnam[0] != '\0')
542 	script_setenv("DEVICE", devnam, 1);
543     (void) slprintf(numbuf, sizeof(numbuf), "%d", getpid());
544     script_setenv("PPPD_PID", numbuf, 1);
545 
546     setup_signals();
547 
548     waiting = 0;
549 
550     create_linkpidfile();
551 
552     /*
553      * If we're doing dial-on-demand, set up the interface now.
554      */
555     if (demand) {
556 	/*
557 	 * Open the loopback channel and set it up to be the ppp interface.
558 	 */
559 #ifdef HAVE_MULTILINK
560 	(void) tdb_writelock(pppdb);
561 #endif
562 	set_ifunit(1);
563 	fd_loop = open_ppp_loopback();
564 #ifdef HAVE_MULTILINK
565 	(void) tdb_writeunlock(pppdb);
566 #endif
567 
568 	/*
569 	 * Configure the interface and mark it up, etc.
570 	 */
571 	demand_conf();
572     }
573 
574     new_phase(PHASE_INITIALIZED);
575     do_callback = 0;
576     for (;;) {
577 
578 	need_holdoff = 1;
579 	ttyfd = -1;
580 	real_ttyfd = -1;
581 	status = EXIT_OK;
582 	++unsuccess;
583 	doing_callback = do_callback;
584 	do_callback = 0;
585 
586 	if (demand && !doing_callback) {
587 	    /*
588 	     * Don't do anything until we see some activity.
589 	     */
590 	    kill_link = 0;
591 	    new_phase(PHASE_DORMANT);
592 	    demand_unblock();
593 	    add_fd(fd_loop);
594 	    for (;;) {
595 		if (sigsetjmp(sigjmp, 1) == 0) {
596 		    (void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
597 		    if (kill_link || got_sigchld) {
598 			(void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
599 		    } else {
600 			waiting = 1;
601 			(void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
602 			wait_input(timeleft(&timo));
603 		    }
604 		}
605 		waiting = 0;
606 		calltimeout();
607 		if (kill_link) {
608 		    if (!persist)
609 			break;
610 		    kill_link = 0;
611 		}
612 		if (get_loop_output())
613 		    break;
614 		if (got_sigchld)
615 		    (void) reap_kids(0);
616 	    }
617 	    remove_fd(fd_loop);
618 	    if (kill_link && !persist)
619 		break;
620 
621 	    /*
622 	     * Now we want to bring up the link.
623 	     */
624 	    demand_block();
625 	    info("Starting link");
626 	}
627 
628 	new_phase(doing_callback ? PHASE_CALLINGBACK : PHASE_SERIALCONN);
629 
630 	/*
631 	 * Get a pty master/slave pair if the pty, notty, socket,
632 	 * or record options were specified.
633 	 */
634 	(void) strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
635 	pty_master = -1;
636 	pty_slave = -1;
637 	if (using_pty || record_file != NULL) {
638 	    if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
639 		error("Couldn't allocate pseudo-tty");
640 		status = EXIT_FATAL_ERROR;
641 		goto fail;
642 	    }
643 	    set_up_tty(pty_slave, 1);
644 	}
645 
646 	/*
647 	 * Lock the device if we've been asked to.
648 	 */
649 	status = EXIT_LOCK_FAILED;
650 	if (lockflag && !privopen && !direct_tty) {
651 	    if (lock(devnam) < 0)
652 		goto fail;
653 	    locked = 1;
654 	}
655 
656 	/*
657 	 * Open the serial device and set it up to be the ppp interface.
658 	 * First we open it in non-blocking mode so we can set the
659 	 * various termios flags appropriately.  If we aren't dialling
660 	 * out and we want to use the modem lines, we reopen it later
661 	 * in order to wait for the carrier detect signal from the modem.
662 	 */
663 	hungup = 0;
664 	kill_link = 0;
665 	connector = doing_callback? callback_script: connect_script;
666 	if (direct_tty) {
667 	    ttyfd = 0;
668 	} else if (devnam[0] != '\0') {
669 	    for (;;) {
670 		/* If the user specified the device name, become the
671 		   user before opening it. */
672 		int err;
673 		if (!devnam_info.priv && !privopen)
674 		    (void) seteuid(uid);
675 		if ((ttyfd = sys_extra_fd()) < 0)
676 		    ttyfd = open(devnam, O_NONBLOCK | O_RDWR);
677 		err = errno;
678 		if (!devnam_info.priv && !privopen)
679 		    (void) seteuid(0);
680 		if (ttyfd >= 0)
681 		    break;
682 		errno = err;
683 		if (err != EINTR) {
684 		    error("Failed to open %s: %m", devnam);
685 		    status = EXIT_OPEN_FAILED;
686 		}
687 		if (!persist || err != EINTR)
688 		    goto fail;
689 	    }
690 	    if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
691 		|| fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
692 		warn("Couldn't reset non-blocking mode on device: %m");
693 
694 	    /*
695 	     * Do the equivalent of `mesg n' to stop broadcast messages.
696 	     */
697 	    if (fstat(ttyfd, &statbuf) < 0
698 		|| fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
699 		warn("Couldn't restrict write permissions to %s: %m", devnam);
700 	    } else
701 		tty_mode = statbuf.st_mode;
702 
703 	    /*
704 	     * Set line speed, flow control, etc.
705 	     * If we have a non-null connection or initializer script,
706 	     * on most systems we set CLOCAL for now so that we can talk
707 	     * to the modem before carrier comes up.  But this has the
708 	     * side effect that we might miss it if CD drops before we
709 	     * get to clear CLOCAL below.  On systems where we can talk
710 	     * successfully to the modem with CLOCAL clear and CD down,
711 	     * we could clear CLOCAL at this point.
712 	     */
713 	    set_up_tty(ttyfd, ((connector != NULL && connector[0] != '\0')
714 			       || initializer != NULL));
715 	    real_ttyfd = ttyfd;
716 	}
717 
718 	/*
719 	 * If the pty, socket, notty and/or record option was specified,
720 	 * start up the character shunt now.
721 	 */
722 	status = EXIT_PTYCMD_FAILED;
723 	if (ptycommand != NULL) {
724 	    if (record_file != NULL) {
725 		int ipipe[2], opipe[2], ok;
726 
727 		if (pipe(ipipe) < 0 || pipe(opipe) < 0)
728 		    fatal("Couldn't create pipes for record option: %m");
729 		dbglog("starting charshunt for pty option");
730 		ok = device_script(ptycommand, opipe[0], ipipe[1], 1,
731 		    "record") == 0 && start_charshunt(ipipe[0], opipe[1]);
732 		(void) close(ipipe[0]);
733 		(void) close(ipipe[1]);
734 		(void) close(opipe[0]);
735 		(void) close(opipe[1]);
736 		if (!ok)
737 		    goto fail;
738 	    } else {
739 		if (device_script(ptycommand, pty_master, pty_master, 1,
740 		    "pty") < 0)
741 		    goto fail;
742 		ttyfd = pty_slave;
743 		(void) close(pty_master);
744 		pty_master = -1;
745 	    }
746 	} else if (pty_socket != NULL) {
747 	    int fd = open_socket(pty_socket);
748 	    if (fd < 0)
749 		goto fail;
750 	    dbglog("starting charshunt for socket option");
751 	    if (!start_charshunt(fd, fd))
752 		goto fail;
753 	} else if (notty) {
754 	    dbglog("starting charshunt for notty option");
755 	    if (!start_charshunt(0, 1))
756 		goto fail;
757 	} else if (record_file != NULL) {
758 	    dbglog("starting charshunt for record option");
759 	    if (!start_charshunt(ttyfd, ttyfd))
760 		goto fail;
761 	}
762 
763 	/* run connection script */
764 	if (((connector != NULL) && (connector[0] != '\0')) || initializer) {
765 	    if (real_ttyfd != -1) {
766 		/* XXX do this if doing_callback == CALLBACK_DIALIN? */
767 		if (!default_device && modem && !direct_tty) {
768 		    setdtr(real_ttyfd, 0);	/* in case modem is off hook */
769 		    (void) sleep(1);
770 		    setdtr(real_ttyfd, 1);
771 		}
772 	    }
773 
774 	    if ((initializer != NULL) && (initializer[0] != '\0')) {
775 		if (device_script(initializer, ttyfd, ttyfd, 0, "init") < 0) {
776 		    error("Initializer script failed");
777 		    status = EXIT_INIT_FAILED;
778 		    goto fail;
779 		}
780 		if (kill_link)
781 		    goto disconnect;
782 
783 		info("Serial port initialized.");
784 	    }
785 
786 	    if ((connector != NULL) && (connector[0] != '\0')) {
787 		if (device_script(connector, ttyfd, ttyfd, 0, "connect") < 0) {
788 		    error("Connect script failed");
789 		    status = EXIT_CONNECT_FAILED;
790 		    goto fail;
791 		}
792 		if (kill_link)
793 		    goto disconnect;
794 
795 		info("Serial connection established.");
796 	    }
797 
798 	    /*
799 	     * Clear CLOCAL if modem option -- we now have carrier
800 	     * established, and we should respect loss of carrier.
801 	     */
802 	    if (real_ttyfd != -1)
803 		set_up_tty(real_ttyfd, 0);
804 
805 	    if (doing_callback == CALLBACK_DIALIN)
806 		connector = NULL;
807 	}
808 
809 	/* reopen tty if necessary to wait for carrier */
810 	if (connector == NULL && modem && devnam[0] != '\0' && !direct_tty) {
811 	    for (;;) {
812 		if ((i = open(devnam, O_RDWR)) >= 0)
813 		    break;
814 		if (errno != EINTR) {
815 		    error("Failed to reopen %s: %m", devnam);
816 		    status = EXIT_OPEN_FAILED;
817 		}
818 		if (!persist || errno != EINTR || hungup || kill_link)
819 		    goto fail;
820 	    }
821 	    (void) close(i);
822 	}
823 
824 	(void) slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
825 	script_setenv("SPEED", numbuf, 0);
826 
827 	/* run welcome script, if any */
828 	if ((welcomer != NULL) && (welcomer[0] != '\0')) {
829 	    if (device_script(welcomer, ttyfd, ttyfd, 0, "welcome") < 0)
830 		warn("Welcome script failed");
831 	}
832 
833 	/* set up the serial device as a ppp interface */
834 #ifdef HAVE_MULTILINK
835 	(void) tdb_writelock(pppdb);
836 #endif
837 	fd_ppp = establish_ppp(ttyfd);
838 	if (fd_ppp < 0) {
839 #ifdef HAVE_MULTILINK
840 	    (void) tdb_writeunlock(pppdb);
841 #endif
842 	    status = EXIT_FATAL_ERROR;
843 	    goto disconnect;
844 	}
845 
846 	if (!demand && ifunit >= 0)
847 	    set_ifunit(1);
848 #ifdef HAVE_MULTILINK
849 	(void) tdb_writeunlock(pppdb);
850 #endif
851 
852 	/*
853 	 * Start opening the connection and wait for
854 	 * incoming events (reply, timeout, etc.).
855 	 */
856 	notice("Connect: %s <--> %s", ifname, ppp_devnam);
857 	(void) gettimeofday(&start_time, NULL);
858 	link_stats_valid = 0;
859 	script_unsetenv("CONNECT_TIME");
860 	script_unsetenv("BYTES_SENT");
861 	script_unsetenv("BYTES_RCVD");
862 	lcp_lowerup(0);
863 
864 	/* Mostly for accounting purposes */
865 	new_phase(PHASE_CONNECTED);
866 
867 	/*
868 	 * If we are initiating this connection, wait for a short
869 	 * time for something from the peer.  This can avoid bouncing
870 	 * our packets off its tty before it has set up the tty.
871 	 */
872 	add_fd(fd_ppp);
873 	if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
874 	    struct timeval t;
875 	    t.tv_sec = connect_delay / 1000;
876 	    t.tv_usec = connect_delay % 1000;
877 	    wait_input(&t);
878 	}
879 
880 	lcp_open(0);		/* Start protocol */
881 	open_ccp_flag = 0;
882 	status = EXIT_NEGOTIATION_FAILED;
883 	new_phase(PHASE_ESTABLISH);
884 	while (phase != PHASE_DEAD) {
885 	    if (sigsetjmp(sigjmp, 1) == 0) {
886 		(void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
887 		if (kill_link || open_ccp_flag || got_sigchld) {
888 		    (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
889 		} else {
890 		    waiting = 1;
891 		    (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
892 		    wait_input(timeleft(&timo));
893 		}
894 	    }
895 	    waiting = 0;
896 	    calltimeout();
897 	    get_input();
898 	    if (kill_link) {
899 		lcp_close(0, "User request");
900 		kill_link = 0;
901 	    }
902 	    if (open_ccp_flag) {
903 		if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
904 		    /* Uncloak ourselves. */
905 		    ccp_fsm[0].flags &= ~OPT_SILENT;
906 		    (*ccp_protent.open)(0);
907 		}
908 		open_ccp_flag = 0;
909 	    }
910 	    if (got_sigchld)
911 		(void) reap_kids(0);	/* Don't leave dead kids lying around */
912 	}
913 
914 	/*
915 	 * Print connect time and statistics.
916 	 */
917 	if (link_stats_valid) {
918 	    int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
919 	    info("Connect time %d.%d minutes.", t/10, t%10);
920 	    info("Sent %" PPP_COUNTER_F " bytes (%" PPP_COUNTER_F
921 		" packets), received %" PPP_COUNTER_F " bytes (%" PPP_COUNTER_F
922 		" packets).",
923 		 link_stats.bytes_out, link_stats.pkts_out,
924 		 link_stats.bytes_in, link_stats.pkts_in);
925 	}
926 
927 	/*
928 	 * Delete pid file before disestablishing ppp.  Otherwise it
929 	 * can happen that another pppd gets the same unit and then
930 	 * we delete its pid file.
931 	 */
932 	if (!demand) {
933 	    if (pidfilename[0] != '\0'
934 		&& unlink(pidfilename) < 0 && errno != ENOENT)
935 		warn("unable to delete pid file %s: %m", pidfilename);
936 	    pidfilename[0] = '\0';
937 	}
938 
939 	/*
940 	 * If we may want to bring the link up again, transfer
941 	 * the ppp unit back to the loopback.  Set the
942 	 * real serial device back to its normal mode of operation.
943 	 */
944 	remove_fd(fd_ppp);
945 	clean_check();
946 	if (demand)
947 	    restore_loop();
948 	disestablish_ppp(ttyfd);
949 	fd_ppp = -1;
950 	if (!hungup)
951 	    lcp_lowerdown(0);
952 	if (!demand)
953 	    script_unsetenv("IFNAME");
954 
955 	/*
956 	 * Run disconnector script, if requested.
957 	 * XXX we may not be able to do this if the line has hung up!
958 	 */
959     disconnect:
960 	if ((disconnect_script != NULL) && (disconnect_script[0] != '\0') &&
961 	    !hungup) {
962 	    new_phase(PHASE_DISCONNECT);
963 	    if (real_ttyfd >= 0)
964 		set_up_tty(real_ttyfd, 1);
965 	    if (device_script(disconnect_script, ttyfd, ttyfd, 0,
966 		"disconnect") < 0) {
967 		warn("disconnect script failed");
968 	    } else {
969 		info("Serial link disconnected.");
970 	    }
971 	}
972 
973     fail:
974 	if (pty_master >= 0)
975 	    (void) close(pty_master);
976 	if (pty_slave >= 0) {
977 	    (void) close(pty_slave);
978 	    pty_slave = -1;
979 	}
980 	if (real_ttyfd >= 0)
981 	    close_tty();
982 	if (locked) {
983 	    locked = 0;
984 	    unlock();
985 	}
986 
987 	if (!demand) {
988 	    if (pidfilename[0] != '\0'
989 		&& unlink(pidfilename) < 0 && errno != ENOENT)
990 		warn("unable to delete pid file %s: %m", pidfilename);
991 	    pidfilename[0] = '\0';
992 	}
993 
994 	if (!persist || (maxfail > 0 && unsuccess >= maxfail))
995 	    break;
996 
997 	kill_link = 0;
998 	if (demand)
999 	    demand_discard();
1000 	t = need_holdoff? holdoff: 0;
1001 	if (holdoff_hook != NULL)
1002 	    t = (*holdoff_hook)();
1003 	if (t > 0) {
1004 	    new_phase(PHASE_HOLDOFF);
1005 	    TIMEOUT(holdoff_end, NULL, t);
1006 	    do {
1007 		if (sigsetjmp(sigjmp, 1) == 0) {
1008 		    (void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
1009 		    if (kill_link || got_sigchld) {
1010 			(void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
1011 		    } else {
1012 			waiting = 1;
1013 			(void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
1014 			wait_input(timeleft(&timo));
1015 		    }
1016 		}
1017 		waiting = 0;
1018 		calltimeout();
1019 		if (kill_link) {
1020 		    kill_link = 0;
1021 		    new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
1022 		}
1023 		if (got_sigchld)
1024 		    (void) reap_kids(0);
1025 	    } while (phase == PHASE_HOLDOFF);
1026 	    if (!persist)
1027 		break;
1028 	}
1029     }
1030 
1031     /* Wait for scripts to finish */
1032     final_reap();
1033 
1034     die(status);
1035     return (0);
1036 }
1037 
1038 /*
1039  * setup_signals - initialize signal handling.
1040  */
1041 static void
setup_signals()1042 setup_signals()
1043 {
1044     struct sigaction sa;
1045 
1046     /*
1047      * Compute mask of all interesting signals and install signal handlers
1048      * for each.  Only one signal handler may be active at a time.  Therefore,
1049      * all other signals should be masked when any handler is executing.
1050      */
1051     (void) sigemptyset(&main_sigmask);
1052     (void) sigaddset(&main_sigmask, SIGHUP);
1053     (void) sigaddset(&main_sigmask, SIGINT);
1054     (void) sigaddset(&main_sigmask, SIGTERM);
1055     (void) sigaddset(&main_sigmask, SIGCHLD);
1056     (void) sigaddset(&main_sigmask, SIGUSR2);
1057 
1058 #define SIGNAL(s, handler)	if (1) { \
1059 	sa.sa_handler = handler; \
1060 	if (sigaction(s, &sa, NULL) < 0) \
1061 	    fatal("Couldn't establish signal handler (%d): %m", s); \
1062     } else ((void)0)
1063 
1064     sa.sa_mask = main_sigmask;
1065     sa.sa_flags = 0;
1066 /*CONSTANTCONDITION*/ SIGNAL(SIGHUP, hup);		/* Hangup */
1067 /*CONSTANTCONDITION*/ SIGNAL(SIGINT, term);		/* Interrupt */
1068 /*CONSTANTCONDITION*/ SIGNAL(SIGTERM, term);		/* Terminate */
1069 /*CONSTANTCONDITION*/ SIGNAL(SIGCHLD, chld);
1070 
1071 /*CONSTANTCONDITION*/ SIGNAL(SIGUSR1, toggle_debug);	/* Toggle debug flag */
1072 /*CONSTANTCONDITION*/ SIGNAL(SIGUSR2, open_ccp);	/* Reopen CCP */
1073 
1074     /*
1075      * Install a handler for other signals which would otherwise
1076      * cause pppd to exit without cleaning up.
1077      */
1078 /*CONSTANTCONDITION*/ SIGNAL(SIGALRM, bad_signal);
1079 /*CONSTANTCONDITION*/ SIGNAL(SIGQUIT, bad_signal);
1080 
1081 /* Do not hook any of these signals on Solaris; allow core dump instead */
1082 #ifndef SOL2
1083 /*CONSTANTCONDITION*/ SIGNAL(SIGABRT, bad_signal);
1084 /*CONSTANTCONDITION*/ SIGNAL(SIGFPE, bad_signal);
1085 /*CONSTANTCONDITION*/ SIGNAL(SIGILL, bad_signal);
1086 #ifndef DEBUG
1087 /*CONSTANTCONDITION*/ SIGNAL(SIGSEGV, bad_signal);
1088 #endif
1089 #ifdef SIGBUS
1090 /*CONSTANTCONDITION*/ SIGNAL(SIGBUS, bad_signal);
1091 #endif
1092 #ifdef SIGEMT
1093 /*CONSTANTCONDITION*/ SIGNAL(SIGEMT, bad_signal);
1094 #endif
1095 #ifdef SIGPOLL
1096 /*CONSTANTCONDITION*/ SIGNAL(SIGPOLL, bad_signal);
1097 #endif
1098 #ifdef SIGPROF
1099 /*CONSTANTCONDITION*/ SIGNAL(SIGPROF, bad_signal);
1100 #endif
1101 #ifdef SIGSYS
1102 /*CONSTANTCONDITION*/ SIGNAL(SIGSYS, bad_signal);
1103 #endif
1104 #ifdef SIGTRAP
1105 /*CONSTANTCONDITION*/ SIGNAL(SIGTRAP, bad_signal);
1106 #endif
1107 #ifdef SIGVTALRM
1108 /*CONSTANTCONDITION*/ SIGNAL(SIGVTALRM, bad_signal);
1109 #endif
1110 #ifdef SIGXCPU
1111 /*CONSTANTCONDITION*/ SIGNAL(SIGXCPU, bad_signal);
1112 #endif
1113 #ifdef SIGXFSZ
1114 /*CONSTANTCONDITION*/ SIGNAL(SIGXFSZ, bad_signal);
1115 #endif
1116 #endif
1117 
1118     /*
1119      * Apparently we can get a SIGPIPE when we call syslog, if
1120      * syslogd has died and been restarted.  Ignoring it seems
1121      * be sufficient.
1122      */
1123     (void) signal(SIGPIPE, SIG_IGN);
1124 }
1125 
1126 /*
1127  * set_ifunit - do things we need to do once we know which ppp
1128  * unit we are using.
1129  */
1130 void
set_ifunit(iskey)1131 set_ifunit(iskey)
1132     int iskey;
1133 {
1134     sys_ifname();
1135     info("Using interface %s", ifname);
1136     script_setenv("IFNAME", ifname, iskey);
1137     if (iskey) {
1138 	create_pidfile();	/* write pid to file */
1139 	create_linkpidfile();
1140     }
1141 }
1142 
1143 /*
1144  * detach - detach us from the controlling terminal.
1145  */
1146 void
detach()1147 detach()
1148 {
1149     pid_t pid;
1150     char numbuf[16];
1151 
1152     if (detached)
1153 	return;
1154     if ((pid = fork()) == (pid_t)-1) {
1155 	error("Couldn't detach (fork failed: %m)");
1156 	die(1);			/* or just return? */
1157     }
1158     if (pid != (pid_t)0) {
1159 	/* parent */
1160 	if (locked)
1161 	    (void) relock(pid);
1162 	exit(0);		/* parent dies */
1163     }
1164     (void) setsid();
1165 	/*
1166 	 * Fork again to relinquish session leadership. This is needed
1167 	 * to prevent the daemon from acquiring controlling terminal.
1168 	 */
1169     if ((pid = fork()) == (pid_t)-1) {
1170 	error("Couldn't detach (second fork failed: %m)");
1171 	die(1);			/* or just return? */
1172     }
1173     if (pid != (pid_t)0) {
1174 	/* parent */
1175 	if (locked)
1176 	    (void) relock(pid);
1177 	exit(0);		/* parent dies */
1178     }
1179     (void) chdir("/");
1180     (void) close(0);
1181     (void) close(1);
1182     (void) close(2);
1183     detached = 1;
1184     if (!log_to_file && !log_to_specific_fd)
1185 	log_to_fd = -1;
1186     /* update pid files if they have been written already */
1187     if (pidfilename[0] != '\0')
1188 	create_pidfile();
1189     if (linkpidfile[0] != '\0')
1190 	create_linkpidfile();
1191     (void) slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1192     script_setenv("PPPD_PID", numbuf, 1);
1193 }
1194 
1195 /*
1196  * reopen_log - (re)open our connection to syslog.
1197  */
1198 void
reopen_log()1199 reopen_log()
1200 {
1201 #ifdef ULTRIX
1202     openlog("pppd", LOG_PID);
1203 #else
1204     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1205     (void) setlogmask(LOG_UPTO(LOG_INFO));
1206 #endif
1207 }
1208 
1209 /*
1210  * Create a file containing our process ID.
1211  */
1212 static void
create_pidfile()1213 create_pidfile()
1214 {
1215     FILE *pidfile;
1216 
1217     (void) slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1218 	     _PATH_VARRUN, ifname);
1219     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1220 	(void) fprintf(pidfile, "%u\n", (unsigned)getpid());
1221 	(void) fclose(pidfile);
1222     } else {
1223 	error("Failed to create pid file %s: %m", pidfilename);
1224 	pidfilename[0] = '\0';
1225     }
1226 }
1227 
1228 static void
create_linkpidfile()1229 create_linkpidfile()
1230 {
1231     FILE *pidfile;
1232 
1233     if (linkname[0] == '\0')
1234 	return;
1235     script_setenv("LINKNAME", linkname, 1);
1236     (void) slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1237 	     _PATH_VARRUN, linkname);
1238     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1239 	(void) fprintf(pidfile, "%u\n", (unsigned)getpid());
1240 	if (ifname[0] != '\0')
1241 	    (void) fprintf(pidfile, "%s\n", ifname);
1242 	(void) fclose(pidfile);
1243     } else {
1244 	error("Failed to create pid file %s: %m", linkpidfile);
1245 	linkpidfile[0] = '\0';
1246     }
1247 }
1248 
1249 /*
1250  * holdoff_end - called via a timeout when the holdoff period ends.
1251  */
1252 /*ARGSUSED*/
1253 static void
holdoff_end(arg)1254 holdoff_end(arg)
1255     void *arg;
1256 {
1257     new_phase(PHASE_DORMANT);
1258 }
1259 
1260 /* List of protocol names, to make our messages a little more informative. */
1261 struct protocol_list {
1262     u_short	proto;
1263     const char	*name;
1264 } protocol_list[] = {
1265     { 0x21,	"IP" },
1266     { 0x23,	"OSI Network Layer" },
1267     { 0x25,	"Xerox NS IDP" },
1268     { 0x27,	"DECnet Phase IV" },
1269     { 0x29,	"Appletalk" },
1270     { 0x2b,	"Novell IPX" },
1271     { 0x2d,	"VJ compressed TCP/IP" },
1272     { 0x2f,	"VJ uncompressed TCP/IP" },
1273     { 0x31,	"Bridging PDU" },
1274     { 0x33,	"Stream Protocol ST-II" },
1275     { 0x35,	"Banyan Vines" },
1276     { 0x37,	"Old VJ compressed TCP/IP" },
1277     { 0x39,	"AppleTalk EDDP" },
1278     { 0x3b,	"AppleTalk SmartBuffered" },
1279     { 0x3d,	"Multilink" },
1280     { 0x3f,	"NetBIOS Frame" },
1281     { 0x41,	"Cisco LAN Extension" },
1282     { 0x43,	"Ascom Timeplex" },
1283     { 0x45,	"Fujitsu Link Backup and Load Balancing (LBLB)" },
1284     { 0x47,	"DCA Remote Lan" },
1285     { 0x49,	"Serial Data Transport Protocol (PPP-SDTP)" },
1286     { 0x4b,	"SNA over 802.2" },
1287     { 0x4d,	"SNA" },
1288     { 0x4f,	"IP6 Header Compression" },
1289     { 0x51,	"KNX Bridging" },
1290     { 0x53,	"Encrypted" },
1291     { 0x55,	"per-link encrypted" },
1292     { 0x57,	"IPv6" },
1293     { 0x59,	"PPP Muxing" },
1294     { 0x6f,	"Stampede Bridging" },
1295     { 0x73,	"MP+" },
1296     { 0xc1,	"STMF" },
1297     { 0xfb,	"per-link compressed" },
1298     { 0xfd,	"compressed datagram" },
1299     { 0x0201,	"802.1d Hello Packets" },
1300     { 0x0203,	"IBM Source Routing BPDU" },
1301     { 0x0205,	"DEC LANBridge100 Spanning Tree" },
1302     { 0x0207,	"Cisco Discovery Protocol" },
1303     { 0x0231,	"Luxcom" },
1304     { 0x0233,	"Sigma Network Systems" },
1305     { 0x0235,	"Apple Client Server Protocol" },
1306     { 0x0281,	"MPLS Unicast" },
1307     { 0x0283,	"MPLS Multicast" },
1308     { 0x0285,	"IEEE p1284.4" },
1309     { 0x0287,	"ETSI TETRA TNP1" },
1310     { 0x4021,	"Stacker LZS" },
1311     { 0x8021,	"Internet Protocol Control Protocol" },
1312     { 0x8023,	"OSI Network Layer Control Protocol" },
1313     { 0x8025,	"Xerox NS IDP Control Protocol" },
1314     { 0x8027,	"DECnet Phase IV Control Protocol" },
1315     { 0x8029,	"Appletalk Control Protocol" },
1316     { 0x802b,	"Novell IPX Control Protocol" },
1317     { 0x8031,	"Bridging Control Protocol" },
1318     { 0x8033,	"Stream Protocol Control Protocol" },
1319     { 0x8035,	"Banyan Vines Control Protocol" },
1320     { 0x803f,	"NetBIOS Frames Control Protocol" },
1321     { 0x8041,	"Cisco LAN Extension Control Protocol" },
1322     { 0x8043,	"Ascom Timeplex Control Protocol" },
1323     { 0x8045,	"Fujitsu LBLB Control Protocol" },
1324     { 0x8047,	"DCA Remote Lan Network Control Protocol (RLNCP)" },
1325     { 0x8049,	"Serial Data Control Protocol (PPP-SDCP)" },
1326     { 0x804b,	"SNA over 802.2 Control Protocol" },
1327     { 0x804d,	"SNA Control Protocol" },
1328     { 0x8051,	"KNX Bridging Control Protocol" },
1329     { 0x8053,	"Encryption Control Protocol" },
1330     { 0x8055,	"Per-link Encryption Control Protocol" },
1331     { 0x8057,	"IPv6 Control Protocol" },
1332     { 0x806f,	"Stampede Bridging Control Protocol" },
1333     { 0x80c1,	"STMF Control Protocol" },
1334     { 0x80fb,	"Per-link Compression Control Protocol" },
1335     { 0x80fd,	"Compression Control Protocol" },
1336     { 0x8207,	"Cisco Discovery Control Protocol" },
1337     { 0x8235,	"Apple Client Server Control Protocol" },
1338     { 0x8281,	"MPLS Control Protocol" },
1339     { 0x8287,	"ETSI TETRA TNP1 Control Protocol" },
1340     { 0xc021,	"Link Control Protocol" },
1341     { 0xc023,	"Password Authentication Protocol" },
1342     { 0xc025,	"Link Quality Report" },
1343     { 0xc027,	"Shiva Password Authentication Protocol" },
1344     { 0xc029,	"CallBack Control Protocol (CBCP)" },
1345     { 0xc02b,	"Bandwidth Allocation Control Protocol" },
1346     { 0xc02d,	"BAP" },
1347     { 0xc081,	"Container Control Protocol" },
1348     { 0xc223,	"Challenge Handshake Authentication Protocol" },
1349     { 0xc227,	"Extensible Authentication Protocol" },
1350     { 0xc281,	"Funk Proprietary Authentication Protocol" },
1351     { 0,	NULL },
1352 };
1353 
1354 /*
1355  * protocol_name - find a name for a PPP protocol.
1356  */
1357 const char *
protocol_name(proto)1358 protocol_name(proto)
1359     int proto;
1360 {
1361     struct protocol_list *lp;
1362 
1363     for (lp = protocol_list; lp->proto != 0; ++lp)
1364 	if (proto == lp->proto)
1365 	    return (lp->name);
1366     return (NULL);
1367 }
1368 
1369 static const char *phase_names[] = { PHASE__NAMES };
1370 
1371 const char *
phase_name(pval)1372 phase_name(pval)
1373     int pval;
1374 {
1375     static char buf[32];
1376 
1377     if (pval < 0 || pval >= Dim(phase_names)) {
1378 	(void) slprintf(buf, sizeof (buf), "unknown %d", pval);
1379 	return ((const char *)buf);
1380     }
1381     return (phase_names[pval]);
1382 }
1383 
1384 /*
1385  * get_input - called when incoming data is available.
1386  */
1387 static void
get_input()1388 get_input()
1389 {
1390     int len, i;
1391     u_char *p;
1392     u_short protocol;
1393     struct protent *protp;
1394     const char *pname;
1395 
1396     p = inpacket_buf;	/* point to beginning of packet buffer */
1397 
1398     len = read_packet(inpacket_buf);
1399     if (len < 0)
1400 	return;
1401 
1402     if (len == 0) {
1403 	notice("Modem hangup");
1404 	hungup = 1;
1405 	status = EXIT_HANGUP;
1406 	lcp_lowerdown(0);	/* serial link is no longer available */
1407 	link_terminated(0);
1408 	return;
1409     }
1410 
1411     if (debug /*&& (debugflags & DBG_INPACKET)*/)
1412 	dbglog("rcvd %P", p, len);
1413 
1414     if (len < PPP_HDRLEN) {
1415 	dbglog("Discarded short packet (%d < %d)", len, PPP_HDRLEN);
1416 	return;
1417     }
1418 
1419     p += 2;				/* Skip address and control */
1420     GETSHORT(protocol, p);
1421     len -= PPP_HDRLEN;
1422 
1423     pname = debug ? NULL : protocol_name(protocol);
1424 
1425     /*
1426      * Toss all non-LCP packets unless LCP is in Opened state and
1427      * discard non-authentication protocols if we're not yet
1428      * authenticated.
1429      */
1430     if ((protocol != PPP_LCP &&
1431 	(phase < PHASE_AUTHENTICATE || phase > PHASE_RUNNING)) ||
1432 	(phase <= PHASE_AUTHENTICATE &&
1433 	    !(protocol == PPP_LCP || protocol == PPP_LQR ||
1434 		protocol == PPP_PAP || protocol == PPP_CHAP))) {
1435 	    if (pname == NULL)
1436 		    dbglog("Discarded proto 0x%x in %s phase",
1437 			protocol, phase_name(phase));
1438 	    else
1439 		    dbglog("Discarded %s (0x%x) in %s phase",
1440 			pname, protocol, phase_name(phase));
1441 	return;
1442     }
1443 
1444     /*
1445      * Upcall the proper protocol input routine.
1446      */
1447     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1448 	if (protp->protocol == protocol && protp->enabled_flag) {
1449 	    (*protp->input)(0, p, len);
1450 	    return;
1451 	}
1452         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1453 	    && protp->datainput != NULL) {
1454 	    (*protp->datainput)(0, p, len);
1455 	    return;
1456 	}
1457     }
1458 
1459     if (debug) {
1460 	if (pname != NULL)
1461 	    warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1462 	else
1463 	    warn("Unsupported protocol 0x%x received", protocol);
1464     }
1465     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1466 }
1467 
1468 /*
1469  * new_phase - signal the start of a new phase of pppd's operation.
1470  */
1471 void
new_phase(p)1472 new_phase(p)
1473     int p;
1474 {
1475     if (new_phase_hook != NULL)
1476 	(*new_phase_hook)(p, phase);
1477     phase = p;
1478 }
1479 
1480 /*
1481  * die - clean up state and exit with the specified status.
1482  */
1483 void
die(status)1484 die(status)
1485     int status;
1486 {
1487     cleanup();
1488     if (phase != PHASE_EXIT) {
1489 	syslog(LOG_INFO, "Exit.");
1490 	new_phase(PHASE_EXIT);
1491     }
1492     exit(status);
1493 }
1494 
1495 /*
1496  * cleanup - restore anything which needs to be restored before we exit
1497  */
1498 static void
cleanup()1499 cleanup()
1500 {
1501     sys_cleanup();  /* XXX: Need to check if this is okay after close_tty */
1502 
1503     if (fd_ppp >= 0) {
1504 	fd_ppp = -1;
1505 	disestablish_ppp(ttyfd);
1506     }
1507     if (real_ttyfd >= 0)
1508 	close_tty();
1509 
1510     if (pidfilename[0] != '\0' && unlink(pidfilename) < 0 && errno != ENOENT)
1511 	warn("unable to delete pid file %s: %m", pidfilename);
1512     pidfilename[0] = '\0';
1513     if (linkpidfile[0] != '\0' && unlink(linkpidfile) < 0 && errno != ENOENT)
1514 	warn("unable to delete pid file %s: %m", linkpidfile);
1515     linkpidfile[0] = '\0';
1516 
1517     if (locked) {
1518 	locked = 0;
1519 	unlock();
1520     }
1521 
1522 #ifdef HAVE_MULTILINK
1523     if (pppdb != NULL) {
1524 	cleanup_db();
1525 	pppdb = NULL;
1526     }
1527 #endif
1528 }
1529 
1530 /*
1531  * close_tty - restore the terminal device and close it.
1532  */
1533 static void
close_tty()1534 close_tty()
1535 {
1536     int fd = real_ttyfd;
1537 
1538     real_ttyfd = -1;
1539 
1540     /* drop dtr to hang up */
1541     if (!default_device && modem) {
1542 	setdtr(fd, 0);
1543 	/*
1544 	 * This sleep is in case the serial port has CLOCAL set by default,
1545 	 * and consequently will reassert DTR when we close the device.
1546 	 */
1547 	(void) sleep(1);
1548     }
1549 
1550     restore_tty(fd);
1551 
1552     if (tty_mode != (mode_t) -1) {
1553 	if (fchmod(fd, tty_mode) != 0) {
1554 	    /* XXX if devnam is a symlink, this will change the link */
1555 	    if (chmod(devnam, tty_mode) != 0) {
1556 		error("Unable to chmod file %s: %m", devnam);
1557 	    }
1558 	}
1559     }
1560 
1561     (void) close(fd);
1562 }
1563 
1564 /*
1565  * update_link_stats - get stats at link termination.
1566  */
1567 void
update_link_stats(u)1568 update_link_stats(u)
1569     int u;
1570 {
1571     struct timeval now;
1572     char numbuf[32];
1573 
1574     if (gettimeofday(&now, NULL) >= 0) {
1575 	link_connect_time = now.tv_sec - start_time.tv_sec;
1576 	(void) slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1577 	script_setenv("CONNECT_TIME", numbuf, 0);
1578     } else {
1579 	link_connect_time = 0;
1580     }
1581 
1582     if (get_ppp_stats(u, &link_stats)) {
1583 	(void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1584 	    link_stats.bytes_out);
1585 	script_setenv("BYTES_SENT", numbuf, 0);
1586 	(void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1587 	    link_stats.bytes_in);
1588 	script_setenv("BYTES_RCVD", numbuf, 0);
1589 	(void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1590 	    link_stats.pkts_in);
1591 	script_setenv("PKTS_RCVD", numbuf, 0);
1592 	(void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1593 	    link_stats.pkts_out);
1594 	script_setenv("PKTS_SENT", numbuf, 0);
1595 	link_stats_valid = 1;
1596     }
1597 }
1598 
1599 
1600 struct	callout {
1601     struct timeval	c_time;		/* time at which to call routine */
1602     void		*c_arg;		/* argument to routine */
1603     void		(*c_func) __P((void *)); /* routine */
1604     struct		callout *c_next;
1605 };
1606 
1607 static struct callout *callout = NULL;	/* Callout list */
1608 static struct timeval timenow;		/* Current time */
1609 
1610 /*
1611  * timeout - Schedule a timeout.
1612  *
1613  * Note that this timeout takes the number of seconds, NOT hz (as in
1614  * the kernel).
1615  */
1616 void
1617 timeout(func, arg, time)
1618     void (*func) __P((void *));
1619     void *arg;
1620     int time;
1621 {
1622     struct callout *newp, *p, **pp;
1623 
1624     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1625 
1626     /*
1627      * Allocate timeout.
1628      */
1629     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1630 	novm("callout structure for timeout.");
1631     newp->c_arg = arg;
1632     newp->c_func = func;
1633     (void) gettimeofday(&timenow, NULL);
1634     newp->c_time.tv_sec = timenow.tv_sec + time;
1635     newp->c_time.tv_usec = timenow.tv_usec;
1636 
1637     /*
1638      * Find correct place and link it in.
1639      */
1640     for (pp = &callout; (p = *pp) != NULL; pp = &p->c_next)
1641 	if (newp->c_time.tv_sec < p->c_time.tv_sec
1642 	    || (newp->c_time.tv_sec == p->c_time.tv_sec
1643 		&& newp->c_time.tv_usec < p->c_time.tv_usec))
1644 	    break;
1645     newp->c_next = p;
1646     *pp = newp;
1647 }
1648 
1649 
1650 /*
1651  * untimeout - Unschedule a timeout.
1652  */
1653 void
1654 untimeout(func, arg)
1655     void (*func) __P((void *));
1656     void *arg;
1657 {
1658     struct callout **copp, *freep;
1659 
1660     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1661 
1662     /*
1663      * Find first matching timeout and remove it from the list.
1664      */
1665     for (copp = &callout; (freep = *copp) != NULL; copp = &freep->c_next)
1666 	if (freep->c_func == func && freep->c_arg == arg) {
1667 	    *copp = freep->c_next;
1668 	    free((char *) freep);
1669 	    break;
1670 	}
1671 }
1672 
1673 
1674 /*
1675  * calltimeout - Call any timeout routines which are now due.
1676  */
1677 static void
calltimeout()1678 calltimeout()
1679 {
1680     struct callout *p;
1681 
1682     while (callout != NULL) {
1683 	p = callout;
1684 
1685 	if (gettimeofday(&timenow, NULL) < 0)
1686 	    fatal("Failed to get time of day: %m");
1687 	if (!(p->c_time.tv_sec < timenow.tv_sec
1688 	      || (p->c_time.tv_sec == timenow.tv_sec
1689 		  && p->c_time.tv_usec <= timenow.tv_usec)))
1690 	    break;		/* no, it's not time yet */
1691 
1692 	callout = p->c_next;
1693 	(*p->c_func)(p->c_arg);
1694 
1695 	free((char *) p);
1696     }
1697 }
1698 
1699 
1700 /*
1701  * timeleft - return the length of time until the next timeout is due.
1702  */
1703 static struct timeval *
timeleft(tvp)1704 timeleft(tvp)
1705     struct timeval *tvp;
1706 {
1707     if (callout == NULL)
1708 	return (NULL);
1709 
1710     (void) gettimeofday(&timenow, NULL);
1711     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1712     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1713     if (tvp->tv_usec < 0) {
1714 	tvp->tv_usec += 1000000;
1715 	tvp->tv_sec -= 1;
1716     }
1717     if (tvp->tv_sec < 0)
1718 	tvp->tv_sec = tvp->tv_usec = 0;
1719 
1720     return (tvp);
1721 }
1722 
1723 
1724 /*
1725  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1726  */
1727 static void
kill_my_pg(sig)1728 kill_my_pg(sig)
1729     int sig;
1730 {
1731     struct sigaction act, oldact;
1732     sigset_t mask;
1733 
1734     BZERO(&act, sizeof (act));
1735     act.sa_handler = SIG_IGN;
1736     (void) sigemptyset(&mask);
1737     (void) sigaddset(&mask, sig);
1738     /*
1739      * Ignore signal 'sig' temporarily, before finally re-activating the
1740      * original handler.  We need to do it in the following sequence, since
1741      * otherwise the signal handler for 'sig' will be called forever.
1742      */
1743     if (sigaction(sig, &act, &oldact) < 0) {
1744 	fatal("kill_my_pg: couldn't establish signal handler (%d): %m", sig);
1745     }
1746     (void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
1747     /*
1748      * Send signal 'sig' to all processes whose process group ID is equal
1749      * to the process group ID of the sender.
1750      */
1751     (void) kill(0, sig);
1752     if (sigaction(sig, &oldact, NULL) < 0) {
1753 	fatal("kill_my_pg: couldn't establish signal handler (%d): %m", sig);
1754     }
1755 }
1756 
1757 
1758 /*
1759  * hup - Catch SIGHUP signal.
1760  *
1761  * Indicates that the physical layer has been disconnected.
1762  * We don't rely on this indication; if the user has sent this
1763  * signal, we just take the link down.
1764  */
1765 static void
hup(sig)1766 hup(sig)
1767     int sig;
1768 {
1769     info("Hangup (SIGHUP)");
1770     kill_link = 1;
1771     if (status != EXIT_HANGUP)
1772 	status = EXIT_USER_REQUEST;
1773     if (conn_running > 0)
1774 	/* Send the signal to the [dis]connector process(es) also */
1775 	kill_my_pg(sig);
1776     if (charshunt_pid)
1777 	(void) kill(charshunt_pid, sig);
1778     if (waiting)
1779 	siglongjmp(sigjmp, 1);
1780 }
1781 
1782 
1783 /*
1784  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1785  *
1786  * Indicates that we should initiate a graceful disconnect and exit.
1787  */
1788 /*ARGSUSED*/
1789 static void
term(sig)1790 term(sig)
1791     int sig;
1792 {
1793     info("Terminating on signal %d.", sig);
1794     persist = 0;		/* don't try to restart */
1795     kill_link = 1;
1796     status = EXIT_USER_REQUEST;
1797     if (conn_running > 0)
1798 	/* Send the signal to the [dis]connector process(es) also */
1799 	kill_my_pg(sig);
1800     if (charshunt_pid)
1801 	(void) kill(charshunt_pid, sig);
1802     if (waiting)
1803 	siglongjmp(sigjmp, 1);
1804 }
1805 
1806 
1807 /*
1808  * chld - Catch SIGCHLD signal.
1809  * Sets a flag so we will call reap_kids in the mainline.
1810  */
1811 /*ARGSUSED*/
1812 static void
chld(sig)1813 chld(sig)
1814     int sig;
1815 {
1816     got_sigchld = 1;
1817     if (waiting)
1818 	siglongjmp(sigjmp, 1);
1819 }
1820 
1821 /*
1822  * toggle_debug - Catch SIGUSR1 signal.
1823  *
1824  * Toggle debug flag.
1825  */
1826 /*ARGSUSED*/
1827 static void
toggle_debug(sig)1828 toggle_debug(sig)
1829     int sig;
1830 {
1831     if (debug) {
1832 	print_ncpstate(0, NULL);
1833 	dbglog("debug logging disabled");
1834 	(void) setlogmask(LOG_UPTO(LOG_WARNING));
1835 	debug = 0;
1836     } else {
1837 	(void) setlogmask(LOG_UPTO(LOG_DEBUG));
1838 	dbglog("debug logging enabled");
1839 	print_ncpstate(0, NULL);
1840 	debug = 1;
1841     }
1842 }
1843 
1844 
1845 /*
1846  * open_ccp - Catch SIGUSR2 signal.
1847  *
1848  * Try to (re)negotiate compression.
1849  */
1850 /*ARGSUSED*/
1851 static void
open_ccp(sig)1852 open_ccp(sig)
1853     int sig;
1854 {
1855     open_ccp_flag = 1;
1856     if (waiting)
1857 	siglongjmp(sigjmp, 1);
1858 }
1859 
1860 
1861 /*
1862  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1863  */
1864 static void
bad_signal(sig)1865 bad_signal(sig)
1866     int sig;
1867 {
1868     static int crashed = 0;
1869 
1870     if (crashed)
1871 	_exit(127);
1872     crashed = 1;
1873     error("Fatal signal %d", sig);
1874     if (conn_running > 0)
1875 	kill_my_pg(SIGTERM);
1876     if (charshunt_pid)
1877 	(void) kill(charshunt_pid, SIGTERM);
1878     die(127);
1879 }
1880 
1881 
1882 /*
1883  * device_script - run a program to talk to the serial device
1884  * (e.g. to run the connector or disconnector script).
1885  */
1886 static int
device_script(program,in,out,dont_wait,optname)1887 device_script(program, in, out, dont_wait, optname)
1888     char *program;
1889     int in, out;
1890     int dont_wait;
1891     char *optname;
1892 {
1893     pid_t pid;
1894     int status = -1;
1895     int errfd;
1896     int envpipe[2];
1897 
1898     envpipe[0] = envpipe[1] = -1;
1899     if (!dont_wait && device_pipe_hook != NULL && pipe(envpipe) == -1) {
1900 	error("Cannot create pipe for child: %m");
1901 	return (-1);
1902     }
1903 
1904     ++conn_running;
1905     pid = fork();
1906 
1907     if (pid == (pid_t)-1) {
1908 	--conn_running;
1909 	error("Failed to create child process: %m");
1910 	return (-1);
1911     }
1912 
1913     if (pid == (pid_t)0) {
1914 	sys_close();
1915 	closelog();
1916 	if (envpipe[0] >= 0) {
1917 	    if (envpipe[1] <= 2)
1918 		envpipe[1] = dup(envpipe[1]);
1919 	    (void) close(envpipe[0]);
1920 	}
1921 	if (in == 2) {
1922 	    /* aargh!!! */
1923 	    int newin = dup(in);
1924 	    if (in == out)
1925 		out = newin;
1926 	    in = newin;
1927 	} else if (out == 2) {
1928 	    out = dup(out);
1929 	}
1930 	if (log_to_fd >= 0) {
1931 	    if (log_to_fd != 2) {
1932 		if (dup2(log_to_fd, 2) < 0)
1933 		    error("dup2(log_to_fd, STDERR) failed: %m");
1934 	    }
1935 	} else {
1936 	    (void) close(2);
1937 	    errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1938 	    if (errfd >= 0 && errfd != 2) {
1939 		if (dup2(errfd, 2) < 0)
1940 		    error("dup2(errfd, STDERR) failed: %m");
1941 		(void) close(errfd);
1942 	    }
1943 	}
1944 	if (in != 0) {
1945 	    if (out == 0)
1946 		out = dup(out);
1947 	    if (dup2(in, 0) < 0)
1948 		error("dup2(in, STDIN) failed: %m");
1949 	}
1950 	if (out != 1) {
1951 	    if (dup2(out, 1) < 0)
1952 		error("dup2(out, STDOUT) failed: %m");
1953 	}
1954 	if (envpipe[0] >= 0 && dup2(envpipe[1], 3) < 0)
1955 	    error("dup2(pipe, pipeout) failed: %m");
1956 	if (real_ttyfd > 2)
1957 	    (void) close(real_ttyfd);
1958 	if (pty_master > 2)
1959 	    (void) close(pty_master);
1960 	if (pty_slave > 2) {
1961 	    (void) close(pty_slave);
1962 	    pty_slave = -1;
1963 	}
1964 	(void) setuid(uid);
1965 	if (getuid() != uid) {
1966 	    error("setuid failed");
1967 	    exit(1);
1968 	}
1969 	(void) setgid(getgid());
1970 	if (script_env != NULL) {
1971 	    while (*script_env != NULL) {
1972 		if (putenv(*script_env) == -1)
1973 		    warn("unable to set %s for %s: %m", *script_env, program);
1974 		script_env++;
1975 	    }
1976 	}
1977 	(void) execl("/bin/sh", "sh", "-c", program, (char *)0);
1978 	error("could not exec /bin/sh: %m");
1979 	exit(99);
1980 	/* NOTREACHED */
1981     }
1982 
1983     if (debug)
1984 	dbglog("%s option: '%s' started (pid %d)", optname, program, pid);
1985     if (dont_wait) {
1986 	record_child(pid, program, NULL, NULL);
1987 	status = 0;
1988     } else {
1989 	if (envpipe[0] >= 0) {
1990 	    (void) close(envpipe[1]);
1991 	    (*device_pipe_hook)(envpipe[0]);
1992 	}
1993 	while (waitpid(pid, &status, 0) < 0) {
1994 	    if (errno == EINTR)
1995 		continue;
1996 	    fatal("error waiting for (dis)connection process: %m");
1997 	}
1998 	if (envpipe[0] >= 0)
1999 	    (void) close(envpipe[0]);
2000 	--conn_running;
2001     }
2002 
2003     return (status == 0 ? 0 : -1);
2004 }
2005 
2006 
2007 /*
2008  * run-program - execute a program with given arguments,
2009  * but don't wait for it.
2010  * If the program can't be executed, logs an error unless
2011  * must_exist is 0 and the program file doesn't exist.
2012  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
2013  * or isn't an executable plain file, or the process ID of the child.
2014  * If done != NULL, (*done)(arg, int) will be called later (within
2015  * reap_kids) if this routine returns value > 0.
2016  */
2017 pid_t
run_program(prog,args,must_exist,done,arg)2018 run_program(prog, args, must_exist, done, arg)
2019     char *prog;
2020     char **args;
2021     int must_exist;
2022     void (*done) __P((void *arg, int status));
2023     void *arg;
2024 {
2025     pid_t pid;
2026     struct stat sbuf;
2027     int retv;
2028 
2029     /*
2030      * First check if the file exists and is executable.
2031      * We don't use access() because that would use the
2032      * real user-id, which might not be root, and the script
2033      * might be accessible only to root.
2034      */
2035     errno = EINVAL;
2036     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
2037 	|| (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
2038 	if (must_exist || errno != ENOENT)
2039 	    warn("Can't execute %s: %m", prog);
2040 	return (0);
2041     }
2042 
2043     if (updown_script_hook != NULL) {
2044 	retv = (*updown_script_hook)((const char ***)&args);
2045 	if (retv == -1) {
2046 	    return (-1);
2047 	}
2048     }
2049 
2050     pid = fork();
2051     if (pid == (pid_t)-1) {
2052 	error("Failed to create child process for %s: %m", prog);
2053 	return (-1);
2054     }
2055     if (pid == (pid_t)0) {
2056 	int new_fd;
2057 
2058 	/* Leave the current location */
2059 	(void) setsid();	/* No controlling tty. */
2060 	(void) umask (S_IRWXG|S_IRWXO);
2061 	(void) chdir ("/");	/* no current directory. */
2062 	(void) setuid(0);	/* set real UID = root */
2063 	(void) setgid(getegid());
2064 
2065 	/* Ensure that nothing of our device environment is inherited. */
2066 	sys_close();
2067 	closelog();
2068 	(void) close(0);
2069 	(void) close(1);
2070 	(void) close(2);
2071 	(void) close(ttyfd);  /* tty interface to the ppp device */
2072 	if (real_ttyfd >= 0)
2073 	    (void) close(real_ttyfd);
2074 
2075         /* Don't pass handles to the PPP device, even by accident. */
2076 	new_fd = open (_PATH_DEVNULL, O_RDWR);
2077 	if (new_fd >= 0) {
2078 	    if (new_fd != 0) {
2079 	        if (dup2(new_fd, 0) < 0) /* stdin <- /dev/null */
2080 		    error("dup2(/dev/null, STDIN) failed: %m");
2081 		(void) close(new_fd);
2082 	    }
2083 	    if (dup2(0, 1) < 0) /* stdout -> /dev/null */
2084 		error("dup2(/dev/null, STDOUT) failed: %m");
2085 	    if (dup2(0, 2) < 0) /* stderr -> /dev/null */
2086 		error("dup2(/dev/null, STDERR) failed: %m");
2087 	}
2088 
2089 #ifdef BSD
2090 	/* Force the priority back to zero if pppd is running higher. */
2091 	if (setpriority (PRIO_PROCESS, 0, 0) < 0)
2092 	    warn("can't reset priority to 0: %m");
2093 #endif
2094 
2095 	/* SysV recommends a second fork at this point. */
2096 
2097 	/* run the program */
2098 	(void) execve(prog, args, script_env);
2099 	if (must_exist || errno != ENOENT) {
2100 	    /* have to reopen the log, there's nowhere else
2101 	       for the message to go. */
2102 	    reopen_log();
2103 	    syslog(LOG_ERR, "Can't execute %s: %m", prog);
2104 	    closelog();
2105 	}
2106 	_exit(-1);
2107     }
2108 
2109     if (debug)
2110 	dbglog("Script %s started (pid %d)", prog, pid);
2111     record_child(pid, prog, done, arg);
2112 
2113     return (pid);
2114 }
2115 
2116 
2117 /*
2118  * record_child - add a child process to the list for reap_kids
2119  * to use.
2120  */
2121 static void
record_child(pid,prog,done,arg)2122 record_child(pid, prog, done, arg)
2123     pid_t pid;
2124     char *prog;
2125     void (*done) __P((void *, int));
2126     void *arg;
2127 {
2128     struct subprocess *chp;
2129 
2130     ++n_children;
2131 
2132     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
2133     if (chp == NULL) {
2134 	warn("losing track of %s process", prog);
2135     } else {
2136 	chp->pid = pid;
2137 	chp->prog = prog;
2138 	chp->done = done;
2139 	chp->arg = arg;
2140 	chp->next = children;
2141 	children = chp;
2142     }
2143 }
2144 
2145 
2146 /*
2147  * reap_kids - get status from any dead child processes,
2148  * and log a message for abnormal terminations.
2149  */
2150 static int
reap_kids(waitfor)2151 reap_kids(waitfor)
2152     int waitfor;
2153 {
2154     pid_t pid;
2155     int status, i;
2156     struct subprocess *chp, **prevp;
2157 
2158     got_sigchld = 0;
2159     if (n_children == 0)
2160 	return (0);
2161 
2162     /*CONSTANTCONDITION*/
2163     while (1) {
2164 	pid = waitpid(-1, &status, (waitfor ? 0 : WNOHANG));
2165 	if (pid == 0) {
2166 	    break;	/* return 0 */
2167 	} else if (pid == -1) {
2168 	    if (errno == EINTR)
2169 		continue;
2170 	    if (errno != ECHILD)
2171 		error("Error waiting for child process: %m");
2172 	    return (-1);
2173 	} else {
2174 	    for (prevp = &children; (chp = *prevp) != NULL;
2175 		prevp = &chp->next) {
2176 		if (chp->pid == pid) {
2177 		    --n_children;
2178 		    *prevp = chp->next;
2179 		    break;
2180 		}
2181 	    }
2182 	    if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
2183 		i = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
2184 		warn("Child process %s (pid %d) %s with signal %d (%s)",
2185 		    (chp != NULL ? chp->prog : "??"), pid,
2186 		    (WIFSIGNALED(status) ? "terminated" : "stopped"),
2187 		    i, signal_name(i));
2188 	    } else if (debug) {
2189 		dbglog("Child process %s finished (pid %d), status = %d",
2190 		       (chp != NULL ? chp->prog: "??"), pid,
2191 		    WEXITSTATUS(status));
2192 	    }
2193 	    if ((chp != NULL) && (chp->done != NULL))
2194 		(*chp->done)(chp->arg, status);
2195 	    if (chp != NULL)
2196 		free(chp);
2197 	}
2198     }
2199     return (0);
2200 }
2201 
2202 /*
2203  * infanticide - timeout while waiting for child process.
2204  */
2205 /*ARGSUSED*/
2206 static void
infanticide(sig)2207 infanticide(sig)
2208     int sig;
2209 {
2210     struct subprocess *chp;
2211     static int runcount = 0;
2212 
2213     if (runcount < 2) {
2214 	for (chp = children; chp != NULL; chp = chp->next)
2215 	    (void) kill(chp->pid, runcount == 0 ? SIGTERM : SIGKILL);
2216     } else {
2217 	kill_my_pg(SIGTERM);
2218 	/* Quit and hope for the best. */
2219 	n_children = 0;
2220     }
2221     runcount++;
2222 }
2223 
2224 /*
2225  * Perform final wait before exiting.
2226  */
2227 static void
final_reap()2228 final_reap()
2229 {
2230     struct sigaction sa;
2231     struct subprocess *chp;
2232 
2233     if (n_children > 0 && debug) {
2234 	dbglog("Waiting for %d child processes...", n_children);
2235 	for (chp = children; chp != NULL; chp = chp->next)
2236 	    dbglog("  pid %d: %s", chp->pid, chp->prog);
2237     }
2238     BZERO(&sa, sizeof (sa));
2239 /*CONSTANTCONDITION*/ SIGNAL(SIGALRM, infanticide);
2240     while (n_children > 0) {
2241 	(void) alarm(7);
2242 	if (reap_kids(1) < 0)
2243 	    break;
2244     }
2245     (void) alarm(0);
2246 }
2247 
2248 /*
2249  * novm - log an error message saying we ran out of memory, and die.
2250  */
2251 void
novm(msg)2252 novm(msg)
2253     char *msg;
2254 {
2255     fatal("Virtual memory exhausted allocating %s\n", msg);
2256 }
2257 
2258 /*
2259  * script_setenv - set an environment variable value to be used
2260  * for scripts that we run (e.g. ip-up, auth-up, etc.)
2261  */
2262 void
script_setenv(var,value,iskey)2263 script_setenv(var, value, iskey)
2264     const char *var;
2265     const char *value;
2266     int iskey;
2267 {
2268     size_t varl = strlen(var);
2269     size_t vl = varl + strlen(value) + 2;
2270     int i;
2271     char *p, *newstring;
2272 
2273     /*
2274      * XXX: Can we assert that a tdb write lock is held here ?  It appears that
2275      *	    Linux's use of tdb is not safe.
2276      */
2277     newstring = (char *) malloc(vl+1);
2278     if (newstring == NULL) {
2279 	novm("script environment string");
2280 	return;
2281     }
2282     *newstring++ = iskey;
2283     (void) slprintf(newstring, vl, "%s=%s", var, value);
2284 
2285     /* check if this variable is already set */
2286     if (script_env != NULL) {
2287 	for (i = 0; (p = script_env[i]) != NULL; ++i) {
2288 	    if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
2289 #ifdef HAVE_MULTILINK
2290 		if (p[-1] != '\0' && pppdb != NULL)
2291 		    delete_db_key(p);
2292 #endif
2293 		free(p-1);
2294 		script_env[i] = newstring;
2295 #ifdef HAVE_MULTILINK
2296 		if (iskey && pppdb != NULL)
2297 		    add_db_key(newstring);
2298 		update_db_entry();
2299 #endif
2300 		return;
2301 	    }
2302 	}
2303     } else {
2304 	/* no space allocated for script env. ptrs. yet */
2305 	i = 0;
2306 	script_env = (char **) malloc(16 * sizeof(char *));
2307 	if (script_env == NULL) {
2308 	    novm("script environment variable.");
2309 	    return;
2310 	}
2311 	s_env_nalloc = 16;
2312     }
2313 
2314     /* reallocate script_env with more space if needed */
2315     if (i + 1 >= s_env_nalloc) {
2316 	int new_n = i + 17;
2317 	char **newenv = (char **) realloc((void *)script_env,
2318 					  new_n * sizeof(char *));
2319 	if (newenv == NULL) {
2320 	    novm("expanded script environment variable.");
2321 	    return;
2322 	}
2323 	script_env = newenv;
2324 	s_env_nalloc = new_n;
2325     }
2326 
2327     script_env[i] = newstring;
2328     script_env[i+1] = NULL;
2329 
2330 #ifdef HAVE_MULTILINK
2331     if (pppdb != NULL) {
2332 	if (iskey)
2333 	    add_db_key(newstring);
2334 	update_db_entry();
2335     }
2336 #endif
2337 }
2338 
2339 /*
2340  * script_unsetenv - remove a variable from the environment
2341  * for scripts.
2342  */
2343 void
script_unsetenv(var)2344 script_unsetenv(var)
2345     const char *var;
2346 {
2347     int vl = strlen(var);
2348     int i;
2349     char *p;
2350 
2351     /*
2352      * XXX: Can we assert that a tdb write lock is held here ?  It appears that
2353      *	    Linux's use of tdb is not safe.
2354      */
2355     if (script_env == NULL)
2356 	return;
2357     for (i = 0; (p = script_env[i]) != NULL; ++i) {
2358 	if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2359 #ifdef HAVE_MULTILINK
2360 	    if (p[-1] != '\0' && pppdb != NULL)
2361 		delete_db_key(p);
2362 #endif
2363 	    free(p-1);
2364 	    while ((script_env[i] = script_env[i+1]) != NULL)
2365 		++i;
2366 	    break;
2367 	}
2368     }
2369 #ifdef HAVE_MULTILINK
2370     if ((pppdb != NULL) && (p != NULL))
2371 	update_db_entry();
2372 #endif
2373 }
2374 
2375 /*
2376  * script_getenv - find a variable in the script environment.
2377  */
2378 const char *
script_getenv(var)2379 script_getenv(var)
2380     const char *var;
2381 {
2382     int vl = strlen(var);
2383     int i;
2384     char *p;
2385 
2386     if (script_env == NULL)
2387 	return (NULL);
2388     for (i = 0; (p = script_env[i]) != NULL; ++i) {
2389 	if (strncmp(p, var, vl) == 0 && p[vl] == '=')
2390 	    return ((const char *)p+vl+1);
2391     }
2392     return (NULL);
2393 }
2394 
2395 #ifdef HAVE_MULTILINK
2396 /*
2397  * update_db_entry - update our entry in the database.
2398  */
2399 static void
update_db_entry()2400 update_db_entry()
2401 {
2402     TDB_DATA key, dbuf;
2403     int vlen, i;
2404     char *p, *q, *vbuf;
2405 
2406     if (script_env == NULL)
2407 	return;
2408     /*
2409      * vlen needs to be initialized as 1, or otherwise, the last string
2410      * is truncated by slprintf.
2411      */
2412     vlen = 1;
2413     for (i = 0; (p = script_env[i]) != NULL; ++i)
2414 	vlen += strlen(p) + 1;
2415     vbuf = malloc(vlen);
2416     if (vbuf == NULL)
2417 	novm("database entry");
2418     q = vbuf;
2419     for (i = 0; (p = script_env[i]) != NULL; ++i)
2420 	q += slprintf(q, vbuf + vlen - q, "%s;", p);
2421 
2422     key.dptr = db_key;
2423     key.dsize = strlen(db_key);
2424     dbuf.dptr = vbuf;
2425     dbuf.dsize = vlen;
2426     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2427 	error("tdb_store failed: %s", tdb_error(pppdb));
2428 }
2429 
2430 /*
2431  * add_db_key - add a key that we can use to look up our database entry.
2432  */
2433 static void
add_db_key(str)2434 add_db_key(str)
2435     const char *str;
2436 {
2437     TDB_DATA key, dbuf;
2438 
2439     key.dptr = (char *) str;
2440     key.dsize = strlen(str);
2441     dbuf.dptr = db_key;
2442     dbuf.dsize = strlen(db_key);
2443     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2444 	error("tdb_store key failed: %s", tdb_error(pppdb));
2445 }
2446 
2447 /*
2448  * delete_db_key - delete a key for looking up our database entry.
2449  */
2450 static void
delete_db_key(str)2451 delete_db_key(str)
2452     const char *str;
2453 {
2454     TDB_DATA key;
2455 
2456     key.dptr = (char *) str;
2457     key.dsize = strlen(str);
2458     (void) tdb_delete(pppdb, key);
2459 }
2460 
2461 /*
2462  * cleanup_db - delete all the entries we put in the database.
2463  */
2464 static void
cleanup_db()2465 cleanup_db()
2466 {
2467     TDB_DATA key;
2468     int i;
2469     char *p;
2470 
2471     key.dptr = db_key;
2472     key.dsize = strlen(db_key);
2473     (void) tdb_delete(pppdb, key);
2474     for (i = 0; (p = script_env[i]) != NULL; ++i)
2475 	if (p[-1] != '\0')
2476 	    delete_db_key(p);
2477 }
2478 #endif /* HAVE_MULTILINK */
2479 
2480 /*
2481  * open_socket - establish a stream socket connection to the nominated
2482  * host and port.
2483  * XXX: Need IPv6 support for those systems that support it (use getaddrinfo),
2484  *	but requires portability changes.
2485  */
2486 static int
open_socket(dest)2487 open_socket(dest)
2488     char *dest;
2489 {
2490     char *sep, *endp = NULL;
2491     int sock;
2492     int port = -1;
2493     u_int32_t host;
2494     struct hostent *hent = NULL;
2495     struct sockaddr_in sad;
2496     struct servent *se;
2497 
2498     /* parse host:port and resolve host to an IP address */
2499     sep = strchr(dest, ':');
2500     if (sep != NULL) {
2501 	se = getservbyname((const char *)sep+1, "tcp");
2502 	if (se != NULL) {
2503 	    port = ntohs(se->s_port);
2504 	} else {
2505 	    port = strtol(sep+1, &endp, 10);
2506 	    if (endp == sep+1 || *endp != '\0') {
2507 		error("Can't parse host:port for socket destination");
2508 		return (-1);
2509 	    }
2510 	}
2511     }
2512     if (port < 0 || port > 65535 || sep == dest) {
2513 	error("Can't parse host:port for socket destination");
2514 	return (-1);
2515     }
2516     *sep = '\0';
2517     host = inet_addr(dest);
2518     if (host == (u_int32_t) -1) {
2519 	hent = gethostbyname(dest);
2520 	if (hent == NULL) {
2521 	    error("%s: unknown host in socket option", dest);
2522 	    *sep = ':';
2523 	    return (-1);
2524 	}
2525 	BCOPY(hent->h_addr_list[0], &host, sizeof(host));
2526 	hent->h_addr_list++;
2527     }
2528     *sep = ':';
2529 
2530     for (;;) {
2531 	/* get a socket and connect it to the other end */
2532 	sock = socket(PF_INET, SOCK_STREAM, 0);
2533 	if (sock < 0) {
2534 	    error("Can't create socket: %m");
2535 	    return (-1);
2536 	}
2537 	BZERO(&sad, sizeof(sad));
2538 	sad.sin_family = AF_INET;
2539 	sad.sin_port = htons(port);
2540 	sad.sin_addr.s_addr = host;
2541 	if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) >= 0) {
2542 	    break;  /* return sock file descriptor */
2543 	}
2544 	if ((hent != NULL) && (hent->h_addr_list != NULL)) {
2545 	    BCOPY(hent->h_addr_list[0], &host, sizeof(host));
2546 	    hent->h_addr_list++;
2547 	    (void) close(sock);
2548 	    continue;
2549 	}
2550 	error("Can't connect to %s: %m", dest);
2551 	(void) close(sock);
2552 	return (-1);
2553     }
2554     return (sock);
2555 }
2556 
2557 /*
2558  * print_ncpstate - prints out current NCP state.
2559  *
2560  * We're normally called from SIGUSR1 here, but this is safe because
2561  * these signals are blocked unless we're idle waiting for events.
2562  * There's no need to otherwise lock the data structures referenced.
2563  */
2564 void
print_ncpstate(unit,strptr)2565 print_ncpstate(unit, strptr)
2566     int unit;
2567     FILE *strptr;
2568 {
2569     struct protent *protp;
2570     int i;
2571 
2572     (void) flprintf(strptr, "In %s phase\n", phase_name(phase));
2573     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
2574 	if (protp->print_stat != NULL)
2575 	    (*protp->print_stat)(unit, strptr);
2576     }
2577     sys_print_state(strptr);
2578 }
2579 
2580 /*
2581  * start_charshunt - create a child process to run the character shunt.
2582  */
2583 static int
start_charshunt(ifd,ofd)2584 start_charshunt(ifd, ofd)
2585     int ifd, ofd;
2586 {
2587     pid_t cpid;
2588 
2589     cpid = fork();
2590     if (cpid == (pid_t)-1) {
2591 	error("Can't fork process for character shunt: %m");
2592 	return (0);
2593     }
2594     if (cpid == (pid_t)0) {
2595 	/* child */
2596 	(void) close(pty_slave);
2597 	pty_slave = -1;
2598 	(void) setgid(getgid());
2599 	(void) setuid(uid);
2600 	if (getuid() != uid)
2601 	    fatal("setuid failed");
2602 	if (!nodetach)
2603 	    log_to_fd = -1;
2604 	charshunt(ifd, ofd, record_file);
2605 	exit(0);
2606     }
2607     charshunt_pid = cpid;
2608     (void) close(pty_master);
2609     pty_master = -1;
2610     ttyfd = pty_slave;
2611     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2612     return (1);
2613 }
2614 
2615 /*ARGSUSED*/
2616 static void
charshunt_done(arg,status)2617 charshunt_done(arg, status)
2618     void *arg;
2619     int status;
2620 {
2621     charshunt_pid = (pid_t)0;
2622 }
2623 
2624 static void
reportme(int signo)2625 reportme(int signo)
2626 {
2627     dbglog("charshunt taking signal %d", signo);
2628     exit(1);
2629 }
2630 
2631 /*
2632  * charshunt - the character shunt, which passes characters between
2633  * the pty master side and the serial port (or stdin/stdout).
2634  * This runs as the user (not as root).
2635  * (We assume ofd >= ifd which is true the way this gets called. :-).
2636  */
2637 static void
charshunt(ifd,ofd,record_file)2638 charshunt(ifd, ofd, record_file)
2639     int ifd, ofd;
2640     char *record_file;
2641 {
2642     int n, nfds;
2643     fd_set ready, writey;
2644     u_char *ibufp, *obufp;
2645     int nibuf, nobuf;
2646     int flags;
2647     struct timeval lasttime;
2648     FILE *recordf = NULL;
2649     int ilevel, olevel, max_level;
2650     struct timeval levelt, tout, *top;
2651 
2652     /*
2653      * Reset signal handlers.
2654      */
2655     (void) signal(SIGHUP, SIG_IGN);		/* Hangup */
2656     (void) signal(SIGINT, reportme);		/* Interrupt */
2657     (void) signal(SIGTERM, reportme);		/* Terminate */
2658     (void) signal(SIGCHLD, reportme);
2659     (void) signal(SIGUSR1, reportme);
2660     (void) signal(SIGUSR2, reportme);
2661     (void) signal(SIGABRT, reportme);
2662     (void) signal(SIGALRM, reportme);
2663     (void) signal(SIGFPE, reportme);
2664     (void) signal(SIGILL, reportme);
2665     (void) signal(SIGPIPE, reportme);
2666     (void) signal(SIGQUIT, reportme);
2667 #ifndef DEBUG
2668     (void) signal(SIGSEGV, reportme);
2669 #endif
2670 #ifdef SIGBUS
2671     (void) signal(SIGBUS, reportme);
2672 #endif
2673 #ifdef SIGEMT
2674     (void) signal(SIGEMT, reportme);
2675 #endif
2676 #ifdef SIGPOLL
2677     (void) signal(SIGPOLL, reportme);
2678 #endif
2679 #ifdef SIGPROF
2680     (void) signal(SIGPROF, reportme);
2681 #endif
2682 #ifdef SIGSYS
2683     (void) signal(SIGSYS, reportme);
2684 #endif
2685 #ifdef SIGTRAP
2686     (void) signal(SIGTRAP, reportme);
2687 #endif
2688 #ifdef SIGVTALRM
2689     (void) signal(SIGVTALRM, reportme);
2690 #endif
2691 #ifdef SIGXCPU
2692     (void) signal(SIGXCPU, reportme);
2693 #endif
2694 #ifdef SIGXFSZ
2695     (void) signal(SIGXFSZ, reportme);
2696 #endif
2697 
2698     /*
2699      * Open the record file if required.
2700      */
2701     if (record_file != NULL) {
2702 	recordf = fopen(record_file, "a");
2703 	if (recordf == NULL)
2704 	    error("Couldn't create record file %s: %m", record_file);
2705     }
2706 
2707     /* set all the fds to non-blocking mode */
2708     flags = fcntl(pty_master, F_GETFL);
2709     if (flags == -1
2710 	|| fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2711 	warn("couldn't set pty master to nonblock: %m");
2712     flags = fcntl(ifd, F_GETFL);
2713     if (flags == -1
2714 	|| fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2715 	warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2716     if (ofd != ifd) {
2717 	flags = fcntl(ofd, F_GETFL);
2718 	if (flags == -1
2719 	    || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2720 	    warn("couldn't set stdout to nonblock: %m");
2721     }
2722 
2723     nibuf = nobuf = 0;
2724     ibufp = obufp = NULL;
2725 
2726     ilevel = olevel = 0;
2727     (void) gettimeofday(&levelt, NULL);
2728     if (max_data_rate) {
2729 	max_level = max_data_rate / 10;
2730 	if (max_level < MAXLEVELMINSIZE)
2731 	    max_level = MAXLEVELMINSIZE;
2732     } else
2733 	max_level = sizeof(inpacket_buf) + 1;
2734 
2735     nfds = (ofd > pty_master? ofd: pty_master) + 1;
2736     if (recordf != NULL) {
2737 	(void) gettimeofday(&lasttime, NULL);
2738 	(void) putc(RECMARK_TIMESTART, recordf);	/* put start marker */
2739 	(void) putc(lasttime.tv_sec >> 24, recordf);
2740 	(void) putc(lasttime.tv_sec >> 16, recordf);
2741 	(void) putc(lasttime.tv_sec >> 8, recordf);
2742 	(void) putc(lasttime.tv_sec, recordf);
2743 	lasttime.tv_usec = 0;
2744     }
2745 
2746     while (nibuf != 0 || nobuf != 0 || ofd >= 0 || pty_master >= 0) {
2747 	top = 0;
2748 	tout.tv_sec = 0;
2749 	tout.tv_usec = 10000;
2750 	FD_ZERO(&ready);
2751 	FD_ZERO(&writey);
2752 	if (nibuf != 0) {
2753 	    if (ilevel >= max_level)
2754 		top = &tout;
2755 	    else if (pty_master >= 0)
2756 		FD_SET(pty_master, &writey);
2757 	} else if (ifd >= 0)
2758 	    FD_SET(ifd, &ready);
2759 	if (nobuf != 0) {
2760 	    if (olevel >= max_level)
2761 		top = &tout;
2762 	    else if (ofd >= 0)
2763 		FD_SET(ofd, &writey);
2764 	} else {
2765 	    /* Don't read from pty if it's gone or it has closed. */
2766 	    if (pty_master >= 0 && ofd >= 0)
2767 		FD_SET(pty_master, &ready);
2768 	}
2769 	if (select(nfds, &ready, &writey, NULL, top) < 0) {
2770 	    if (errno != EINTR)
2771 		fatal("select");
2772 	    continue;
2773 	}
2774 	if (max_data_rate) {
2775 	    double dt;
2776 	    int nbt;
2777 	    struct timeval now;
2778 
2779 	    (void) gettimeofday(&now, NULL);
2780 	    dt = (now.tv_sec - levelt.tv_sec
2781 		  + (now.tv_usec - levelt.tv_usec) / 1e6);
2782 	    nbt = (int)(dt * max_data_rate);
2783 	    ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2784 	    olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2785 	    levelt = now;
2786 	} else
2787 	    ilevel = olevel = 0;
2788 	if (FD_ISSET(ifd, &ready)) {
2789 	    ibufp = inpacket_buf;
2790 	    nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2791 	    if (nibuf < 0 && errno == EIO)
2792 		nibuf = 0;
2793 	    if (nibuf < 0 || pty_master == -1) {
2794 		if (errno != EINTR && errno != EAGAIN) {
2795 		    error("Error reading standard input: %m");
2796 		    break;
2797 		}
2798 		nibuf = 0;
2799 	    } else if (nibuf == 0) {
2800 		/* end of file from stdin */
2801 		(void) close(pty_master);
2802 		pty_master = -1;
2803 		(void) close(ifd);
2804 		ifd = -1;
2805 		if (recordf)
2806 		    if (!record_write(recordf, RECMARK_ENDRECV, NULL, 0,
2807 			&lasttime))
2808 			recordf = NULL;
2809 	    } else {
2810 		FD_SET(pty_master, &writey);
2811 		if (recordf)
2812 		    if (!record_write(recordf, RECMARK_STARTRECV, ibufp, nibuf,
2813 			&lasttime))
2814 			recordf = NULL;
2815 	    }
2816 	}
2817 	if (ofd >= 0 && pty_master >= 0 && FD_ISSET(pty_master, &ready)) {
2818 	    obufp = outpacket_buf;
2819 	    nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2820 	    if (nobuf < 0 && errno == EIO)
2821 		nobuf = 0;
2822 	    if (nobuf < 0 || ofd == -1) {
2823 		if (!(errno == EINTR || errno == EAGAIN)) {
2824 		    error("Error reading pseudo-tty master: %m");
2825 		    break;
2826 		}
2827 		nobuf = 0;
2828 	    } else if (nobuf == 0) {
2829 		/* end of file from the pty - slave side has closed */
2830 		nibuf = 0;
2831 		(void) close(ofd);
2832 		ofd = -1;
2833 		if (recordf)
2834 		    if (!record_write(recordf, RECMARK_ENDSEND, NULL, 0,
2835 			&lasttime))
2836 			recordf = NULL;
2837 	    } else {
2838 		FD_SET(ofd, &writey);
2839 		if (recordf)
2840 		    if (!record_write(recordf, RECMARK_STARTSEND, obufp, nobuf,
2841 			&lasttime))
2842 			recordf = NULL;
2843 	    }
2844 	}
2845 	if (ofd == -1)
2846 	    nobuf = 0;
2847 	else if (FD_ISSET(ofd, &writey)) {
2848 	    n = nobuf;
2849 	    if (olevel + n > max_level)
2850 		n = max_level - olevel;
2851 	    n = write(ofd, obufp, n);
2852 	    if (n < 0) {
2853 		if (errno == EIO) {
2854 		    (void) close(ofd);
2855 		    ofd = -1;
2856 		    nobuf = 0;
2857 		} else if (errno != EAGAIN && errno != EINTR) {
2858 		    error("Error writing standard output: %m");
2859 		    break;
2860 		}
2861 	    } else {
2862 		obufp += n;
2863 		nobuf -= n;
2864 		olevel += n;
2865 	    }
2866 	}
2867 	if (pty_master == -1)
2868 	    nibuf = 0;
2869 	else if (FD_ISSET(pty_master, &writey)) {
2870 	    n = nibuf;
2871 	    if (ilevel + n > max_level)
2872 		n = max_level - ilevel;
2873 	    n = write(pty_master, ibufp, n);
2874 	    if (n < 0) {
2875 		if (errno == EAGAIN || errno == EINTR)
2876 		    continue;
2877 		if (errno != EIO) {
2878 		    error("Error writing pseudo-tty master: %m");
2879 		    break;
2880 		}
2881 		(void) close(pty_master);
2882 		pty_master = -1;
2883 		nibuf = 0;
2884 	    } else {
2885 		ibufp += n;
2886 		nibuf -= n;
2887 		ilevel += n;
2888 	    }
2889 	}
2890     }
2891     exit(0);
2892 }
2893 
2894 static int
record_write(f,code,buf,nb,tp)2895 record_write(f, code, buf, nb, tp)
2896     FILE *f;
2897     int code;
2898     u_char *buf;
2899     int nb;
2900     struct timeval *tp;
2901 {
2902     struct timeval now;
2903     int diff;
2904 
2905     (void) gettimeofday(&now, NULL);
2906     now.tv_usec /= 100000;	/* actually 1/10 s, not usec now */
2907     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2908     if (diff > 0) {
2909 	if (diff > 255) {
2910 	    (void) putc(RECMARK_TIMEDELTA32, f);
2911 	    (void) putc(diff >> 24, f);
2912 	    (void) putc(diff >> 16, f);
2913 	    (void) putc(diff >> 8, f);
2914 	    (void) putc(diff, f);
2915 	} else {
2916 	    (void) putc(RECMARK_TIMEDELTA8, f);
2917 	    (void) putc(diff, f);
2918 	}
2919 	*tp = now;
2920     }
2921     (void) putc(code, f);
2922     if (buf != NULL) {
2923 	(void) putc(nb >> 8, f);
2924 	(void) putc(nb, f);
2925 	(void) fwrite(buf, nb, 1, f);
2926     }
2927     (void) fflush(f);
2928     if (ferror(f)) {
2929 	error("Error writing record file: %m");
2930 	return (0);
2931     }
2932     return (1);
2933 }
2934