main.c revision 1.21
1/*	$OpenBSD: main.c,v 1.21 1998/01/17 20:30:25 millert Exp $	*/
2
3/*
4 * main.c - Point-to-Point Protocol main module
5 *
6 * Copyright (c) 1989 Carnegie Mellon University.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms are permitted
10 * provided that the above copyright notice and this paragraph are
11 * duplicated in all such forms and that any documentation,
12 * advertising materials, and other materials related to such
13 * distribution and use acknowledge that the software was developed
14 * by Carnegie Mellon University.  The name of the
15 * University may not be used to endorse or promote products derived
16 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
19 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 */
21
22#ifndef lint
23#if 0
24static char rcsid[] = "Id: main.c,v 1.43 1997/11/27 06:09:20 paulus Exp $";
25#else
26static char rcsid[] = "$OpenBSD: main.c,v 1.21 1998/01/17 20:30:25 millert Exp $";
27#endif
28#endif
29
30#include <stdio.h>
31#include <ctype.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35#include <signal.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <syslog.h>
39#include <netdb.h>
40#include <utmp.h>
41#include <pwd.h>
42#include <sys/param.h>
43#include <sys/types.h>
44#include <sys/wait.h>
45#include <sys/time.h>
46#include <sys/resource.h>
47#include <sys/stat.h>
48#include <sys/socket.h>
49#include <net/if.h>
50
51#include "pppd.h"
52#include "magic.h"
53#include "fsm.h"
54#include "lcp.h"
55#include "ipcp.h"
56#include "upap.h"
57#include "chap.h"
58#include "ccp.h"
59#include "pathnames.h"
60#include "patchlevel.h"
61
62#ifdef CBCP_SUPPORT
63#include "cbcp.h"
64#endif
65
66#if defined(SUNOS4)
67extern char *strerror();
68#endif
69
70#ifdef IPX_CHANGE
71#include "ipxcp.h"
72#endif /* IPX_CHANGE */
73#ifdef AT_CHANGE
74#include "atcp.h"
75#endif
76
77/* interface vars */
78char ifname[IFNAMSIZ];		/* Interface name */
79int ifunit;			/* Interface unit number */
80
81char *progname;			/* Name of this program */
82char hostname[MAXNAMELEN];	/* Our hostname */
83static char pidfilename[MAXPATHLEN];	/* name of pid file */
84static char default_devnam[MAXPATHLEN];	/* name of default device */
85static pid_t pid;		/* Our pid */
86static uid_t uid;		/* Our real user-id */
87static int conn_running;	/* we have a [dis]connector running */
88
89int ttyfd = -1;			/* Serial port file descriptor */
90mode_t tty_mode = -1;		/* Original access permissions to tty */
91int baud_rate;			/* Actual bits/second for serial device */
92int hungup;			/* terminal has been hung up */
93int privileged;			/* we're running as real uid root */
94int need_holdoff;		/* need holdoff period before restarting */
95
96int phase;			/* where the link is at */
97int kill_link;
98int open_ccp_flag;
99int redirect_stderr;		/* Connector's stderr should go to file */
100
101u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
102u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
103
104static int n_children;		/* # child processes still running */
105
106static int locked;		/* lock() has succeeded */
107
108char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
109
110/* Prototypes for procedures local to this file. */
111
112static void cleanup __P((void));
113static void close_tty __P((void));
114static void get_input __P((void));
115static void calltimeout __P((void));
116static struct timeval *timeleft __P((struct timeval *));
117static void kill_my_pg __P((int));
118static void hup __P((int));
119static void term __P((int));
120static void chld __P((int));
121static void toggle_debug __P((int));
122static void open_ccp __P((int));
123static void bad_signal __P((int));
124static void holdoff_end __P((void *));
125static int device_script __P((char *, int, int));
126static void reap_kids __P((void));
127static void pr_log __P((void *, char *, ...));
128
129extern	char	*ttyname __P((int));
130extern	char	*getlogin __P((void));
131int main __P((int, char *[]));
132
133#ifdef ultrix
134#undef	O_NONBLOCK
135#define	O_NONBLOCK	O_NDELAY
136#endif
137
138#ifdef ULTRIX
139#define setlogmask(x)
140#endif
141
142/*
143 * PPP Data Link Layer "protocol" table.
144 * One entry per supported protocol.
145 * The last entry must be NULL.
146 */
147struct protent *protocols[] = {
148    &lcp_protent,
149    &pap_protent,
150    &chap_protent,
151#ifdef CBCP_SUPPORT
152    &cbcp_protent,
153#endif
154    &ipcp_protent,
155    &ccp_protent,
156#ifdef IPX_CHANGE
157    &ipxcp_protent,
158#endif
159#ifdef AT_CHANGE
160    &atcp_protent,
161#endif
162    NULL
163};
164
165int
166main(argc, argv)
167    int argc;
168    char *argv[];
169{
170    int i, fdflags;
171    struct sigaction sa;
172    FILE *pidfile;
173    char *p;
174    struct passwd *pw;
175    struct timeval timo;
176    sigset_t mask;
177    struct protent *protp;
178    struct stat statbuf;
179
180    phase = PHASE_INITIALIZE;
181    p = ttyname(0);
182    if (p)
183	strcpy(devnam, p);
184    strcpy(default_devnam, devnam);
185
186    /* Initialize syslog facilities */
187#ifdef ULTRIX
188    openlog("pppd", LOG_PID);
189#else
190    openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
191    setlogmask(LOG_UPTO(LOG_INFO));
192#endif
193
194    if (gethostname(hostname, MAXNAMELEN) < 0 ) {
195	option_error("Couldn't get hostname: %m");
196	die(1);
197    }
198    hostname[MAXNAMELEN-1] = 0;
199
200    uid = getuid();
201    privileged = uid == 0;
202
203    /*
204     * Initialize to the standard option set, then parse, in order,
205     * the system options file, the user's options file,
206     * the tty's options file, and the command line arguments.
207     */
208    for (i = 0; (protp = protocols[i]) != NULL; ++i)
209	(*protp->init)(0);
210
211    progname = *argv;
212
213    if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
214	|| !options_from_user())
215	exit(1);
216    scan_args(argc-1, argv+1);	/* look for tty name on command line */
217    if (!options_for_tty()
218	|| !parse_args(argc-1, argv+1))
219	exit(1);
220
221    /*
222     * Check that we are running as root.
223     */
224    if (geteuid() != 0) {
225	option_error("must be root to run %s, since it is not setuid-root",
226		     argv[0]);
227	die(1);
228    }
229
230    if (!ppp_available()) {
231	option_error(no_ppp_msg);
232	exit(1);
233    }
234
235    /*
236     * Check that the options given are valid and consistent.
237     */
238    sys_check_options();
239    auth_check_options();
240    for (i = 0; (protp = protocols[i]) != NULL; ++i)
241	if (protp->check_options != NULL)
242	    (*protp->check_options)();
243    if (demand && connector == 0) {
244	option_error("connect script required for demand-dialling\n");
245	exit(1);
246    }
247
248    /*
249     * If the user has specified the default device name explicitly,
250     * pretend they hadn't.
251     */
252    if (!default_device && strcmp(devnam, default_devnam) == 0)
253	default_device = 1;
254    redirect_stderr = !nodetach || default_device;
255
256    /*
257     * Initialize system-dependent stuff and magic number package.
258     */
259    sys_init();
260    magic_init();
261    if (debug)
262	setlogmask(LOG_UPTO(LOG_DEBUG));
263
264    /*
265     * Detach ourselves from the terminal, if required,
266     * and identify who is running us.
267     */
268    if (!default_device && !nodetach && daemon(0, 0) < 0) {
269	perror("Couldn't detach from controlling terminal");
270	exit(1);
271    }
272    pid = getpid();
273    p = getlogin();
274    if (p == NULL) {
275	pw = getpwuid(uid);
276	if (pw != NULL && pw->pw_name != NULL)
277	    p = pw->pw_name;
278	else
279	    p = "(unknown)";
280    }
281    syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
282	   VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
283
284    /*
285     * Compute mask of all interesting signals and install signal handlers
286     * for each.  Only one signal handler may be active at a time.  Therefore,
287     * all other signals should be masked when any handler is executing.
288     */
289    sigemptyset(&mask);
290    sigaddset(&mask, SIGHUP);
291    sigaddset(&mask, SIGINT);
292    sigaddset(&mask, SIGTERM);
293    sigaddset(&mask, SIGCHLD);
294
295#define SIGNAL(s, handler)	{ \
296	sa.sa_handler = handler; \
297	if (sigaction(s, &sa, NULL) < 0) { \
298	    syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
299	    die(1); \
300	} \
301    }
302
303    sa.sa_mask = mask;
304    sa.sa_flags = 0;
305    SIGNAL(SIGHUP, hup);		/* Hangup */
306    SIGNAL(SIGINT, term);		/* Interrupt */
307    SIGNAL(SIGTERM, term);		/* Terminate */
308    SIGNAL(SIGCHLD, chld);
309
310    SIGNAL(SIGUSR1, toggle_debug);	/* Toggle debug flag */
311    SIGNAL(SIGUSR2, open_ccp);		/* Reopen CCP */
312
313    /*
314     * Install a handler for other signals which would otherwise
315     * cause pppd to exit without cleaning up.
316     */
317    SIGNAL(SIGABRT, bad_signal);
318    SIGNAL(SIGALRM, bad_signal);
319    SIGNAL(SIGFPE, bad_signal);
320    SIGNAL(SIGILL, bad_signal);
321    SIGNAL(SIGPIPE, bad_signal);
322    SIGNAL(SIGQUIT, bad_signal);
323    SIGNAL(SIGSEGV, bad_signal);
324#ifdef SIGBUS
325    SIGNAL(SIGBUS, bad_signal);
326#endif
327#ifdef SIGEMT
328    SIGNAL(SIGEMT, bad_signal);
329#endif
330#ifdef SIGPOLL
331    SIGNAL(SIGPOLL, bad_signal);
332#endif
333#ifdef SIGPROF
334    SIGNAL(SIGPROF, bad_signal);
335#endif
336#ifdef SIGSYS
337    SIGNAL(SIGSYS, bad_signal);
338#endif
339#ifdef SIGTRAP
340    SIGNAL(SIGTRAP, bad_signal);
341#endif
342#ifdef SIGVTALRM
343    SIGNAL(SIGVTALRM, bad_signal);
344#endif
345#ifdef SIGXCPU
346    SIGNAL(SIGXCPU, bad_signal);
347#endif
348#ifdef SIGXFSZ
349    SIGNAL(SIGXFSZ, bad_signal);
350#endif
351
352    /*
353     * Apparently we can get a SIGPIPE when we call syslog, if
354     * syslogd has died and been restarted.  Ignoring it seems
355     * be sufficient.
356     */
357    signal(SIGPIPE, SIG_IGN);
358
359    /*
360     * If we're doing dial-on-demand, set up the interface now.
361     */
362    if (demand) {
363	/*
364	 * Open the loopback channel and set it up to be the ppp interface.
365	 */
366	open_ppp_loopback();
367
368	syslog(LOG_INFO, "Using interface ppp%d", ifunit);
369	(void) sprintf(ifname, "ppp%d", ifunit);
370
371	/* write pid to file */
372	(void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
373	if ((pidfile = fopen(pidfilename, "w")) != NULL) {
374	    fprintf(pidfile, "%d\n", pid);
375	    (void) fclose(pidfile);
376	} else {
377	    syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
378	    pidfilename[0] = 0;
379	}
380
381	/*
382	 * Configure the interface and mark it up, etc.
383	 */
384	demand_conf();
385    }
386
387    for (;;) {
388
389	need_holdoff = 1;
390
391	if (demand) {
392	    /*
393	     * Don't do anything until we see some activity.
394	     */
395	    phase = PHASE_DORMANT;
396	    kill_link = 0;
397	    demand_unblock();
398	    for (;;) {
399		wait_loop_output(timeleft(&timo));
400		calltimeout();
401		if (kill_link) {
402		    if (!persist)
403			die(0);
404		    kill_link = 0;
405		}
406		if (get_loop_output())
407		    break;
408		reap_kids();
409	    }
410
411	    /*
412	     * Now we want to bring up the link.
413	     */
414	    demand_block();
415	    syslog(LOG_INFO, "Starting link");
416	}
417
418	/*
419	 * Lock the device if we've been asked to.
420	 */
421	if (lockflag && !default_device) {
422	    if (lock(devnam) < 0)
423		goto fail;
424	    locked = 1;
425	}
426
427	/*
428	 * Open the serial device and set it up to be the ppp interface.
429	 * First we open it in non-blocking mode so we can set the
430	 * various termios flags appropriately.  If we aren't dialling
431	 * out and we want to use the modem lines, we reopen it later
432	 * in order to wait for the carrier detect signal from the modem.
433	 */
434	while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
435	    if (errno != EINTR)
436		syslog(LOG_ERR, "Failed to open %s: %m", devnam);
437	    if (!persist || errno != EINTR)
438		goto fail;
439	}
440	if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
441	    || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
442	    syslog(LOG_WARNING,
443		   "Couldn't reset non-blocking mode on device: %m");
444
445	hungup = 0;
446	kill_link = 0;
447
448	/*
449	 * Do the equivalent of `mesg n' to stop broadcast messages.
450	 */
451	if (fstat(ttyfd, &statbuf) < 0
452	    || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
453	    syslog(LOG_WARNING,
454		   "Couldn't restrict write permissions to %s: %m", devnam);
455	} else
456	    tty_mode = statbuf.st_mode;
457
458	/* run connection script */
459	if (connector && connector[0]) {
460	    MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
461
462	    /*
463	     * Set line speed, flow control, etc.
464	     * On most systems we set CLOCAL for now so that we can talk
465	     * to the modem before carrier comes up.  But this has the
466	     * side effect that we might miss it if CD drops before we
467	     * get to clear CLOCAL below.  On systems where we can talk
468	     * successfully to the modem with CLOCAL clear and CD down,
469	     * we can clear CLOCAL at this point.
470	     */
471	    set_up_tty(ttyfd, (modem_chat == 0));
472
473	    /* drop dtr to hang up in case modem is off hook */
474	    if (!default_device && modem) {
475		setdtr(ttyfd, FALSE);
476		sleep(1);
477		setdtr(ttyfd, TRUE);
478	    }
479
480	    if (device_script(connector, ttyfd, ttyfd) < 0) {
481		syslog(LOG_ERR, "Connect script failed");
482		setdtr(ttyfd, FALSE);
483		goto fail;
484	    }
485
486	    syslog(LOG_INFO, "Serial connection established.");
487	    sleep(1);		/* give it time to set up its terminal */
488	}
489
490	/* clear CLOCAL if modem option set and we set CLOCAL above */
491	if (modem && !modem_chat)
492		set_up_tty(ttyfd, 0);
493
494	/* reopen tty if necessary to wait for carrier */
495	if (connector == NULL && modem) {
496	    while ((i = open(devnam, O_RDWR)) < 0) {
497		if (errno != EINTR)
498		    syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
499		if (!persist || errno != EINTR || hungup || kill_link)
500		    goto fail;
501	    }
502	    close(i);
503	}
504
505	/* run welcome script, if any */
506	if (welcomer && welcomer[0]) {
507	    if (device_script(welcomer, ttyfd, ttyfd) < 0)
508		syslog(LOG_WARNING, "Welcome script failed");
509	}
510
511	/* set up the serial device as a ppp interface */
512	establish_ppp(ttyfd);
513
514	if (!demand) {
515
516	    syslog(LOG_INFO, "Using interface ppp%d", ifunit);
517	    (void) sprintf(ifname, "ppp%d", ifunit);
518
519	    /* write pid to file */
520	    (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
521	    if ((pidfile = fopen(pidfilename, "w")) != NULL) {
522		fprintf(pidfile, "%d\n", pid);
523		(void) fclose(pidfile);
524	    } else {
525		syslog(LOG_ERR, "Failed to create pid file %s: %m",
526		       pidfilename);
527		pidfilename[0] = 0;
528	    }
529	}
530
531	/*
532	 * Start opening the connection and wait for
533	 * incoming events (reply, timeout, etc.).
534	 */
535	syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
536	lcp_lowerup(0);
537	lcp_open(0);		/* Start protocol */
538	for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
539	    wait_input(timeleft(&timo));
540	    calltimeout();
541	    get_input();
542	    if (kill_link) {
543		lcp_close(0, "User request");
544		kill_link = 0;
545	    }
546	    if (open_ccp_flag) {
547		if (phase == PHASE_NETWORK) {
548		    ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
549		    (*ccp_protent.open)(0);
550		}
551		open_ccp_flag = 0;
552	    }
553	    reap_kids();	/* Don't leave dead kids lying around */
554	}
555
556	/*
557	 * If we may want to bring the link up again, transfer
558	 * the ppp unit back to the loopback.  Set the
559	 * real serial device back to its normal mode of operation.
560	 */
561	clean_check();
562	if (demand)
563	    restore_loop();
564	disestablish_ppp(ttyfd);
565
566	/*
567	 * Run disconnector script, if requested.
568	 * XXX we may not be able to do this if the line has hung up!
569	 */
570	if (disconnector && !hungup) {
571	    set_up_tty(ttyfd, 1);
572	    if (device_script(disconnector, ttyfd, ttyfd) < 0) {
573		syslog(LOG_WARNING, "disconnect script failed");
574	    } else {
575		syslog(LOG_INFO, "Serial link disconnected.");
576	    }
577	}
578
579    fail:
580	if (ttyfd >= 0)
581	    close_tty();
582	if (locked) {
583	    unlock();
584	    locked = 0;
585	}
586
587	if (!demand) {
588	    if (pidfilename[0] != 0
589		&& unlink(pidfilename) < 0 && errno != ENOENT)
590		syslog(LOG_WARNING, "unable to delete pid file: %m");
591	    pidfilename[0] = 0;
592	}
593
594	if (!persist)
595	    die(1);
596
597	if (demand)
598	    demand_discard();
599	if (holdoff > 0 && need_holdoff) {
600	    phase = PHASE_HOLDOFF;
601	    TIMEOUT(holdoff_end, NULL, holdoff);
602	    do {
603		wait_time(timeleft(&timo));
604		calltimeout();
605		if (kill_link) {
606		    if (!persist)
607			die(0);
608		    kill_link = 0;
609		    phase = PHASE_DORMANT; /* allow signal to end holdoff */
610		}
611		reap_kids();
612	    } while (phase == PHASE_HOLDOFF);
613	}
614    }
615
616    die(0);
617    return 0;
618}
619
620/*
621 * holdoff_end - called via a timeout when the holdoff period ends.
622 */
623static void
624holdoff_end(arg)
625    void *arg;
626{
627    phase = PHASE_DORMANT;
628}
629
630/*
631 * get_input - called when incoming data is available.
632 */
633static void
634get_input()
635{
636    int len, i;
637    u_char *p;
638    u_short protocol;
639    struct protent *protp;
640
641    p = inpacket_buf;	/* point to beginning of packet buffer */
642
643    len = read_packet(inpacket_buf);
644    if (len < 0)
645	return;
646
647    if (len == 0) {
648	syslog(LOG_NOTICE, "Modem hangup");
649	hungup = 1;
650	lcp_lowerdown(0);	/* serial link is no longer available */
651	link_terminated(0);
652	return;
653    }
654
655    if (debug /*&& (debugflags & DBG_INPACKET)*/)
656	log_packet(p, len, "rcvd ", LOG_DEBUG);
657
658    if (len < PPP_HDRLEN) {
659	MAINDEBUG((LOG_INFO, "io(): Received short packet."));
660	return;
661    }
662
663    p += 2;				/* Skip address and control */
664    GETSHORT(protocol, p);
665    len -= PPP_HDRLEN;
666
667    /*
668     * Toss all non-LCP packets unless LCP is OPEN.
669     */
670    if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
671	MAINDEBUG((LOG_INFO,
672		   "get_input: Received non-LCP packet when LCP not open."));
673	return;
674    }
675
676    /*
677     * Until we get past the authentication phase, toss all packets
678     * except LCP, LQR and authentication packets.
679     */
680    if (phase <= PHASE_AUTHENTICATE
681	&& !(protocol == PPP_LCP || protocol == PPP_LQR
682	|| protocol == PPP_PAP || protocol == PPP_CHAP)) {
683	MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
684		   protocol, phase));
685	return;
686    }
687
688    /*
689     * Upcall the proper protocol input routine.
690     */
691    for (i = 0; (protp = protocols[i]) != NULL; ++i) {
692	if (protp->protocol == protocol && protp->enabled_flag) {
693	    (*protp->input)(0, p, len);
694	    return;
695	}
696	if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
697	    && protp->datainput != NULL) {
698	    (*protp->datainput)(0, p, len);
699	    return;
700	}
701    }
702
703    if (debug)
704    	syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
705    lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
706}
707
708
709/*
710 * quit - Clean up state and exit (with an error indication).
711 */
712void
713quit()
714{
715    die(1);
716}
717
718/*
719 * die - like quit, except we can specify an exit status.
720 */
721void
722die(status)
723    int status;
724{
725    cleanup();
726    syslog(LOG_INFO, "Exit.");
727    exit(status);
728}
729
730/*
731 * cleanup - restore anything which needs to be restored before we exit
732 */
733/* ARGSUSED */
734static void
735cleanup()
736{
737    sys_cleanup();
738
739    if (ttyfd >= 0)
740	close_tty();
741
742    if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
743	syslog(LOG_WARNING, "unable to delete pid file: %m");
744    pidfilename[0] = 0;
745
746    if (locked)
747	unlock();
748}
749
750/*
751 * close_tty - restore the terminal device and close it.
752 */
753static void
754close_tty()
755{
756    disestablish_ppp(ttyfd);
757
758    /* drop dtr to hang up */
759    if (modem) {
760	setdtr(ttyfd, FALSE);
761	/*
762	 * This sleep is in case the serial port has CLOCAL set by default,
763	 * and consequently will reassert DTR when we close the device.
764	 */
765	sleep(1);
766    }
767
768    restore_tty(ttyfd);
769
770    if (tty_mode != (mode_t) -1)
771	chmod(devnam, tty_mode);
772
773    close(ttyfd);
774    ttyfd = -1;
775}
776
777
778struct	callout {
779    struct timeval	c_time;		/* time at which to call routine */
780    void		*c_arg;		/* argument to routine */
781    void		(*c_func) __P((void *)); /* routine */
782    struct		callout *c_next;
783};
784
785static struct callout *callout = NULL;	/* Callout list */
786static struct timeval timenow;		/* Current time */
787
788/*
789 * timeout - Schedule a timeout.
790 *
791 * Note that this timeout takes the number of seconds, NOT hz (as in
792 * the kernel).
793 */
794void
795timeout(func, arg, time)
796    void (*func) __P((void *));
797    void *arg;
798    int time;
799{
800    struct callout *newp, *p, **pp;
801
802    MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
803	       (long) func, (long) arg, time));
804
805    /*
806     * Allocate timeout.
807     */
808    if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
809	syslog(LOG_ERR, "Out of memory in timeout()!");
810	die(1);
811    }
812    newp->c_arg = arg;
813    newp->c_func = func;
814    gettimeofday(&timenow, NULL);
815    newp->c_time.tv_sec = timenow.tv_sec + time;
816    newp->c_time.tv_usec = timenow.tv_usec;
817
818    /*
819     * Find correct place and link it in.
820     */
821    for (pp = &callout; (p = *pp); pp = &p->c_next)
822	if (newp->c_time.tv_sec < p->c_time.tv_sec
823	    || (newp->c_time.tv_sec == p->c_time.tv_sec
824		&& newp->c_time.tv_usec < p->c_time.tv_sec))
825	    break;
826    newp->c_next = p;
827    *pp = newp;
828}
829
830
831/*
832 * untimeout - Unschedule a timeout.
833 */
834void
835untimeout(func, arg)
836    void (*func) __P((void *));
837    void *arg;
838{
839    struct callout **copp, *freep;
840
841    MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
842
843    /*
844     * Find first matching timeout and remove it from the list.
845     */
846    for (copp = &callout; (freep = *copp); copp = &freep->c_next)
847	if (freep->c_func == func && freep->c_arg == arg) {
848	    *copp = freep->c_next;
849	    (void) free((char *) freep);
850	    break;
851	}
852}
853
854
855/*
856 * calltimeout - Call any timeout routines which are now due.
857 */
858static void
859calltimeout()
860{
861    struct callout *p;
862
863    while (callout != NULL) {
864	p = callout;
865
866	if (gettimeofday(&timenow, NULL) < 0) {
867	    syslog(LOG_ERR, "Failed to get time of day: %m");
868	    die(1);
869	}
870	if (!(p->c_time.tv_sec < timenow.tv_sec
871	      || (p->c_time.tv_sec == timenow.tv_sec
872		  && p->c_time.tv_usec <= timenow.tv_usec)))
873	    break;		/* no, it's not time yet */
874
875	callout = p->c_next;
876	(*p->c_func)(p->c_arg);
877
878	free((char *) p);
879    }
880}
881
882
883/*
884 * timeleft - return the length of time until the next timeout is due.
885 */
886static struct timeval *
887timeleft(tvp)
888    struct timeval *tvp;
889{
890    if (callout == NULL)
891	return NULL;
892
893    gettimeofday(&timenow, NULL);
894    tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
895    tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
896    if (tvp->tv_usec < 0) {
897	tvp->tv_usec += 1000000;
898	tvp->tv_sec -= 1;
899    }
900    if (tvp->tv_sec < 0)
901	tvp->tv_sec = tvp->tv_usec = 0;
902
903    return tvp;
904}
905
906
907/*
908 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
909 */
910static void
911kill_my_pg(sig)
912    int sig;
913{
914    struct sigaction act, oldact;
915
916    act.sa_handler = SIG_IGN;
917    act.sa_flags = 0;
918    kill(0, sig);
919    sigaction(sig, &act, &oldact);
920    sigaction(sig, &oldact, NULL);
921}
922
923
924/*
925 * hup - Catch SIGHUP signal.
926 *
927 * Indicates that the physical layer has been disconnected.
928 * We don't rely on this indication; if the user has sent this
929 * signal, we just take the link down.
930 */
931static void
932hup(sig)
933    int sig;
934{
935    syslog(LOG_INFO, "Hangup (SIGHUP)");
936    kill_link = 1;
937    if (conn_running)
938	/* Send the signal to the [dis]connector process(es) also */
939	kill_my_pg(sig);
940}
941
942
943/*
944 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
945 *
946 * Indicates that we should initiate a graceful disconnect and exit.
947 */
948/*ARGSUSED*/
949static void
950term(sig)
951    int sig;
952{
953    syslog(LOG_INFO, "Terminating on signal %d.", sig);
954    persist = 0;		/* don't try to restart */
955    kill_link = 1;
956    if (conn_running)
957	/* Send the signal to the [dis]connector process(es) also */
958	kill_my_pg(sig);
959}
960
961
962/*
963 * chld - Catch SIGCHLD signal.
964 * Calls reap_kids to get status for any dead kids.
965 */
966static void
967chld(sig)
968    int sig;
969{
970    int save_errno = errno;
971
972    reap_kids();
973    errno = save_errno;
974}
975
976
977/*
978 * toggle_debug - Catch SIGUSR1 signal.
979 *
980 * Toggle debug flag.
981 */
982/*ARGSUSED*/
983static void
984toggle_debug(sig)
985    int sig;
986{
987    debug = !debug;
988    if (debug) {
989	setlogmask(LOG_UPTO(LOG_DEBUG));
990    } else {
991	setlogmask(LOG_UPTO(LOG_WARNING));
992    }
993}
994
995
996/*
997 * open_ccp - Catch SIGUSR2 signal.
998 *
999 * Try to (re)negotiate compression.
1000 */
1001/*ARGSUSED*/
1002static void
1003open_ccp(sig)
1004    int sig;
1005{
1006    open_ccp_flag = 1;
1007}
1008
1009
1010/*
1011 * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1012 */
1013static void
1014bad_signal(sig)
1015    int sig;
1016{
1017    syslog(LOG_ERR, "Fatal signal %d", sig);
1018    if (conn_running)
1019	kill_my_pg(SIGTERM);
1020    die(1);
1021}
1022
1023
1024/*
1025 * device_script - run a program to connect or disconnect the
1026 * serial device.
1027 */
1028static int
1029device_script(program, in, out)
1030    char *program;
1031    int in, out;
1032{
1033    int pid;
1034    int status;
1035    int errfd;
1036
1037    conn_running = 1;
1038    pid = fork();
1039
1040    if (pid < 0) {
1041	conn_running = 0;
1042	syslog(LOG_ERR, "Failed to create child process: %m");
1043	die(1);
1044    }
1045
1046    if (pid == 0) {
1047	sys_close();
1048	closelog();
1049	if (in == out) {
1050	    if (in != 0) {
1051		dup2(in, 0);
1052		close(in);
1053	    }
1054	    dup2(0, 1);
1055	} else {
1056	    if (out == 0)
1057		out = dup(out);
1058	    if (in != 0) {
1059		dup2(in, 0);
1060		close(in);
1061	    }
1062	    if (out != 1) {
1063		dup2(out, 1);
1064		close(out);
1065	    }
1066	}
1067	if (redirect_stderr) {
1068	    close(2);
1069	    errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
1070	    if (errfd >= 0 && errfd != 2) {
1071		dup2(errfd, 2);
1072		close(errfd);
1073	    }
1074	}
1075	/* revoke privs */
1076	seteuid(getuid());
1077	setuid(getuid());
1078	setegid(getgid());
1079	setgid(getgid());
1080	execl("/bin/sh", "sh", "-c", program, (char *)0);
1081	syslog(LOG_ERR, "could not exec /bin/sh: %m");
1082	_exit(99);
1083	/* NOTREACHED */
1084    }
1085
1086    while (waitpid(pid, &status, 0) < 0) {
1087	if (errno == EINTR)
1088	    continue;
1089	syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1090	die(1);
1091    }
1092    conn_running = 0;
1093
1094    return (status == 0 ? 0 : -1);
1095}
1096
1097
1098/*
1099 * run-program - execute a program with given arguments,
1100 * but don't wait for it.
1101 * If the program can't be executed, logs an error unless
1102 * must_exist is 0 and the program file doesn't exist.
1103 */
1104int
1105run_program(prog, args, must_exist)
1106    char *prog;
1107    char **args;
1108    int must_exist;
1109{
1110    int pid;
1111    char *nullenv[1];
1112
1113    pid = fork();
1114    if (pid == -1) {
1115	syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1116	return -1;
1117    }
1118    if (pid == 0) {
1119	int new_fd;
1120
1121	/* Leave the current location */
1122	(void) setsid();    /* No controlling tty. */
1123	(void) umask (S_IRWXG|S_IRWXO);
1124	(void) chdir ("/"); /* no current directory. */
1125	setuid(geteuid());
1126	setgid(getegid());
1127
1128	/* Ensure that nothing of our device environment is inherited. */
1129	sys_close();
1130	closelog();
1131	close (0);
1132	close (1);
1133	close (2);
1134	close (ttyfd);  /* tty interface to the ppp device */
1135
1136	/* Don't pass handles to the PPP device, even by accident. */
1137	new_fd = open (_PATH_DEVNULL, O_RDWR);
1138	if (new_fd >= 0) {
1139	    if (new_fd != 0) {
1140		dup2  (new_fd, 0); /* stdin <- /dev/null */
1141		close (new_fd);
1142	    }
1143	    dup2 (0, 1); /* stdout -> /dev/null */
1144	    dup2 (0, 2); /* stderr -> /dev/null */
1145	}
1146
1147#ifdef BSD
1148	/* Force the priority back to zero if pppd is running higher. */
1149	if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1150	    syslog (LOG_WARNING, "can't reset priority to 0: %m");
1151#endif
1152
1153	/* SysV recommends a second fork at this point. */
1154
1155	/* run the program; give it a null environment */
1156	nullenv[0] = NULL;
1157	execve(prog, args, nullenv);
1158	if (must_exist || errno != ENOENT)
1159	    syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1160	_exit(-1);
1161    }
1162    MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1163    ++n_children;
1164    return 0;
1165}
1166
1167
1168/*
1169 * reap_kids - get status from any dead child processes,
1170 * and log a message for abnormal terminations.
1171 */
1172static void
1173reap_kids()
1174{
1175    int pid, status;
1176
1177    if (n_children == 0)
1178	return;
1179    if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1180	if (errno != ECHILD)
1181	    syslog(LOG_ERR, "Error waiting for child process: %m");
1182	return;
1183    }
1184    if (pid > 0) {
1185	--n_children;
1186	if (WIFSIGNALED(status)) {
1187	    syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1188		   pid, WTERMSIG(status));
1189	}
1190    }
1191}
1192
1193
1194/*
1195 * log_packet - format a packet and log it.
1196 */
1197
1198char line[256];			/* line to be logged accumulated here */
1199char *linep;
1200
1201void
1202log_packet(p, len, prefix, level)
1203    u_char *p;
1204    int len;
1205    char *prefix;
1206    int level;
1207{
1208    strcpy(line, prefix);
1209    linep = line + strlen(line);
1210    format_packet(p, len, pr_log, NULL);
1211    if (linep != line)
1212	syslog(level, "%s", line);
1213}
1214
1215/*
1216 * format_packet - make a readable representation of a packet,
1217 * calling `printer(arg, format, ...)' to output it.
1218 */
1219void
1220format_packet(p, len, printer, arg)
1221    u_char *p;
1222    int len;
1223    void (*printer) __P((void *, char *, ...));
1224    void *arg;
1225{
1226    int i, n;
1227    u_short proto;
1228    u_char x;
1229    struct protent *protp;
1230
1231    if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1232	p += 2;
1233	GETSHORT(proto, p);
1234	len -= PPP_HDRLEN;
1235	for (i = 0; (protp = protocols[i]) != NULL; ++i)
1236	    if (proto == protp->protocol)
1237		break;
1238	if (protp != NULL) {
1239	    printer(arg, "[%s", protp->name);
1240	    n = (*protp->printpkt)(p, len, printer, arg);
1241	    printer(arg, "]");
1242	    p += n;
1243	    len -= n;
1244	} else {
1245	    printer(arg, "[proto=0x%x]", proto);
1246	}
1247    }
1248
1249    for (; len > 0; --len) {
1250	GETCHAR(x, p);
1251	printer(arg, " %.2x", x);
1252    }
1253}
1254
1255static void
1256pr_log __V((void *arg, char *fmt, ...))
1257{
1258    int n;
1259    va_list pvar;
1260    char buf[256];
1261
1262#ifdef __STDC__
1263    va_start(pvar, fmt);
1264#else
1265    void *arg;
1266    char *fmt;
1267    va_start(pvar);
1268    arg = va_arg(pvar, void *);
1269    fmt = va_arg(pvar, char *);
1270#endif
1271
1272    vsprintf(buf, fmt, pvar);
1273    va_end(pvar);
1274
1275    n = strlen(buf);
1276    if (linep + n + 1 > line + sizeof(line)) {
1277	syslog(LOG_DEBUG, "%s", line);
1278	linep = line;
1279    }
1280    strcpy(linep, buf);
1281    linep += n;
1282}
1283
1284/*
1285 * print_string - print a readable representation of a string using
1286 * printer.
1287 */
1288void
1289print_string(p, len, printer, arg)
1290    char *p;
1291    int len;
1292    void (*printer) __P((void *, char *, ...));
1293    void *arg;
1294{
1295    int c;
1296
1297    printer(arg, "\"");
1298    for (; len > 0; --len) {
1299	c = *p++;
1300	if (' ' <= c && c <= '~') {
1301	    if (c == '\\' || c == '"')
1302		printer(arg, "\\");
1303	    printer(arg, "%c", c);
1304	} else {
1305	    switch (c) {
1306	    case '\n':
1307		printer(arg, "\\n");
1308		break;
1309	    case '\r':
1310		printer(arg, "\\r");
1311		break;
1312	    case '\t':
1313		printer(arg, "\\t");
1314		break;
1315	    default:
1316		printer(arg, "\\%.3o", c);
1317	    }
1318	}
1319    }
1320    printer(arg, "\"");
1321}
1322
1323/*
1324 * novm - log an error message saying we ran out of memory, and die.
1325 */
1326void
1327novm(msg)
1328    char *msg;
1329{
1330    syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1331    die(1);
1332}
1333
1334/*
1335 * fmtmsg - format a message into a buffer.  Like sprintf except we
1336 * also specify the length of the output buffer, and we handle
1337 * %r (recursive format), %m (error message) and %I (IP address) formats.
1338 * Doesn't do floating-point formats.
1339 * Returns the number of chars put into buf.
1340 */
1341int
1342fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1343{
1344    va_list args;
1345    int n;
1346
1347#ifdef __STDC__
1348    va_start(args, fmt);
1349#else
1350    char *buf;
1351    int buflen;
1352    char *fmt;
1353    va_start(args);
1354    buf = va_arg(args, char *);
1355    buflen = va_arg(args, int);
1356    fmt = va_arg(args, char *);
1357#endif
1358    n = vfmtmsg(buf, buflen, fmt, args);
1359    va_end(args);
1360    return n;
1361}
1362
1363/*
1364 * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1365 */
1366#define OUTCHAR(c)	(buflen > 0? (--buflen, *buf++ = (c)): 0)
1367
1368int
1369vfmtmsg(buf, buflen, fmt, args)
1370    char *buf;
1371    int buflen;
1372    char *fmt;
1373    va_list args;
1374{
1375    int c, i, n;
1376    int width, prec, fillch;
1377    int base, len, neg, quoted;
1378    unsigned long val = 0;
1379    char *str, *f, *buf0;
1380    unsigned char *p;
1381    char num[32];
1382    time_t t;
1383    static char hexchars[] = "0123456789abcdef";
1384
1385    buf0 = buf;
1386    --buflen;
1387    while (buflen > 0) {
1388	for (f = fmt; *f != '%' && *f != 0; ++f)
1389	    ;
1390	if (f > fmt) {
1391	    len = f - fmt;
1392	    if (len > buflen)
1393		len = buflen;
1394	    memcpy(buf, fmt, len);
1395	    buf += len;
1396	    buflen -= len;
1397	    fmt = f;
1398	}
1399	if (*fmt == 0)
1400	    break;
1401	c = *++fmt;
1402	width = prec = 0;
1403	fillch = ' ';
1404	if (c == '0') {
1405	    fillch = '0';
1406	    c = *++fmt;
1407	}
1408	if (c == '*') {
1409	    width = va_arg(args, int);
1410	    c = *++fmt;
1411	} else {
1412	    while (isdigit(c)) {
1413		width = width * 10 + c - '0';
1414		c = *++fmt;
1415	    }
1416	}
1417	if (c == '.') {
1418	    c = *++fmt;
1419	    if (c == '*') {
1420		prec = va_arg(args, int);
1421		c = *++fmt;
1422	    } else {
1423		while (isdigit(c)) {
1424		    prec = prec * 10 + c - '0';
1425		    c = *++fmt;
1426		}
1427	    }
1428	}
1429	str = 0;
1430	base = 0;
1431	neg = 0;
1432	++fmt;
1433	switch (c) {
1434	case 'd':
1435	    i = va_arg(args, int);
1436	    if (i < 0) {
1437		neg = 1;
1438		val = -i;
1439	    } else
1440		val = i;
1441	    base = 10;
1442	    break;
1443	case 'o':
1444	    val = va_arg(args, unsigned int);
1445	    base = 8;
1446	    break;
1447	case 'x':
1448	    val = va_arg(args, unsigned int);
1449	    base = 16;
1450	    break;
1451	case 'p':
1452	    val = (unsigned long) va_arg(args, void *);
1453	    base = 16;
1454	    neg = 2;
1455	    break;
1456	case 's':
1457	    str = va_arg(args, char *);
1458	    break;
1459	case 'c':
1460	    num[0] = va_arg(args, int);
1461	    num[1] = 0;
1462	    str = num;
1463	    break;
1464	case 'm':
1465	    str = strerror(errno);
1466	    break;
1467	case 'I':
1468	    str = ip_ntoa(va_arg(args, u_int32_t));
1469	    break;
1470	case 'r':
1471	    f = va_arg(args, char *);
1472#ifndef __powerpc__
1473	    n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1474#else
1475	    /* On the powerpc, a va_list is an array of 1 structure */
1476	    n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1477#endif
1478	    buf += n;
1479	    buflen -= n;
1480	    continue;
1481	case 't':
1482	    time(&t);
1483	    str = ctime(&t);
1484	    str += 4;		/* chop off the day name */
1485	    str[15] = 0;	/* chop off year and newline */
1486	    break;
1487	case 'v':		/* "visible" string */
1488	case 'q':		/* quoted string */
1489	    quoted = c == 'q';
1490	    p = va_arg(args, unsigned char *);
1491	    if (fillch == '0' && prec > 0) {
1492		n = prec;
1493	    } else {
1494		n = strlen((char *)p);
1495		if (prec > 0 && prec < n)
1496		    n = prec;
1497	    }
1498	    while (n > 0 && buflen > 0) {
1499		c = *p++;
1500		--n;
1501		if (!quoted && c >= 0x80) {
1502		    OUTCHAR('M');
1503		    OUTCHAR('-');
1504		    c -= 0x80;
1505		}
1506		if (quoted && (c == '"' || c == '\\'))
1507		    OUTCHAR('\\');
1508		if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1509		    if (quoted) {
1510			OUTCHAR('\\');
1511			switch (c) {
1512			case '\t':	OUTCHAR('t');	break;
1513			case '\n':	OUTCHAR('n');	break;
1514			case '\b':	OUTCHAR('b');	break;
1515			case '\f':	OUTCHAR('f');	break;
1516			default:
1517			    OUTCHAR('x');
1518			    OUTCHAR(hexchars[c >> 4]);
1519			    OUTCHAR(hexchars[c & 0xf]);
1520			}
1521		    } else {
1522			if (c == '\t')
1523			    OUTCHAR(c);
1524			else {
1525			    OUTCHAR('^');
1526			    OUTCHAR(c ^ 0x40);
1527			}
1528		    }
1529		} else
1530		    OUTCHAR(c);
1531	    }
1532	    continue;
1533	default:
1534	    *buf++ = '%';
1535	    if (c != '%')
1536		--fmt;		/* so %z outputs %z etc. */
1537	    --buflen;
1538	    continue;
1539	}
1540	if (base != 0) {
1541	    str = num + sizeof(num);
1542	    *--str = 0;
1543	    while (str > num + neg) {
1544		*--str = hexchars[val % base];
1545		val = val / base;
1546		if (--prec <= 0 && val == 0)
1547		    break;
1548	    }
1549	    switch (neg) {
1550	    case 1:
1551		*--str = '-';
1552		break;
1553	    case 2:
1554		*--str = 'x';
1555		*--str = '0';
1556		break;
1557	    }
1558	    len = num + sizeof(num) - 1 - str;
1559	} else {
1560	    len = strlen(str);
1561	    if (prec > 0 && len > prec)
1562		len = prec;
1563	}
1564	if (width > 0) {
1565	    if (width > buflen)
1566		width = buflen;
1567	    if ((n = width - len) > 0) {
1568		buflen -= n;
1569		for (; n > 0; --n)
1570		    *buf++ = fillch;
1571	    }
1572	}
1573	if (len > buflen)
1574	    len = buflen;
1575	memcpy(buf, str, len);
1576	buf += len;
1577	buflen -= len;
1578    }
1579    *buf = 0;
1580    return buf - buf0;
1581}
1582