Home | History | Annotate | Download | only in pppd
      1 /*
      2  * main.c - Point-to-Point Protocol main module
      3  *
      4  * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  *
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  *
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in
     15  *    the documentation and/or other materials provided with the
     16  *    distribution.
     17  *
     18  * 3. The name "Carnegie Mellon University" must not be used to
     19  *    endorse or promote products derived from this software without
     20  *    prior written permission. For permission or any legal
     21  *    details, please contact
     22  *      Office of Technology Transfer
     23  *      Carnegie Mellon University
     24  *      5000 Forbes Avenue
     25  *      Pittsburgh, PA  15213-3890
     26  *      (412) 268-4387, fax: (412) 268-7395
     27  *      tech-transfer (at) andrew.cmu.edu
     28  *
     29  * 4. Redistributions of any form whatsoever must retain the following
     30  *    acknowledgment:
     31  *    "This product includes software developed by Computing Services
     32  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
     33  *
     34  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
     35  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
     36  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
     37  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     38  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
     39  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
     40  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     41  *
     42  * Copyright (c) 1999-2004 Paul Mackerras. All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  *
     48  * 1. Redistributions of source code must retain the above copyright
     49  *    notice, this list of conditions and the following disclaimer.
     50  *
     51  * 2. The name(s) of the authors of this software must not be used to
     52  *    endorse or promote products derived from this software without
     53  *    prior written permission.
     54  *
     55  * 3. Redistributions of any form whatsoever must retain the following
     56  *    acknowledgment:
     57  *    "This product includes software developed by Paul Mackerras
     58  *     <paulus (at) samba.org>".
     59  *
     60  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
     61  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
     62  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
     63  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     64  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
     65  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
     66  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     67  */
     68 
     69 #define RCSID	"$Id: main.c,v 1.156 2008/06/23 11:47:18 paulus Exp $"
     70 
     71 #include <stdio.h>
     72 #include <ctype.h>
     73 #include <stdlib.h>
     74 #include <string.h>
     75 #include <unistd.h>
     76 #include <signal.h>
     77 #include <errno.h>
     78 #include <fcntl.h>
     79 #include <syslog.h>
     80 #include <netdb.h>
     81 #include <utmp.h>
     82 #include <pwd.h>
     83 #include <setjmp.h>
     84 #include <sys/param.h>
     85 #include <sys/types.h>
     86 #include <sys/wait.h>
     87 #include <sys/time.h>
     88 #include <sys/resource.h>
     89 #include <sys/stat.h>
     90 #include <sys/socket.h>
     91 #include <netinet/in.h>
     92 #include <arpa/inet.h>
     93 #if defined(__ANDROID__)
     94 #include <cutils/properties.h>
     95 #endif
     96 
     97 #include "pppd.h"
     98 #include "magic.h"
     99 #include "fsm.h"
    100 #include "lcp.h"
    101 #include "ipcp.h"
    102 #ifdef INET6
    103 #include "ipv6cp.h"
    104 #endif
    105 #include "upap.h"
    106 #include "chap-new.h"
    107 #include "eap.h"
    108 #include "ccp.h"
    109 #include "ecp.h"
    110 #include "pathnames.h"
    111 
    112 #ifdef USE_TDB
    113 #include "tdb.h"
    114 #endif
    115 
    116 #ifdef CBCP_SUPPORT
    117 #include "cbcp.h"
    118 #endif
    119 
    120 #ifdef IPX_CHANGE
    121 #include "ipxcp.h"
    122 #endif /* IPX_CHANGE */
    123 #ifdef AT_CHANGE
    124 #include "atcp.h"
    125 #endif
    126 
    127 static const char rcsid[] = RCSID;
    128 
    129 /* interface vars */
    130 char ifname[32];		/* Interface name */
    131 int ifunit;			/* Interface unit number */
    132 
    133 struct channel *the_channel;
    134 
    135 char *progname;			/* Name of this program */
    136 char hostname[MAXNAMELEN];	/* Our hostname */
    137 static char pidfilename[MAXPATHLEN];	/* name of pid file */
    138 static char linkpidfile[MAXPATHLEN];	/* name of linkname pid file */
    139 char ppp_devnam[MAXPATHLEN];	/* name of PPP tty (maybe ttypx) */
    140 uid_t uid;			/* Our real user-id */
    141 struct notifier *pidchange = NULL;
    142 struct notifier *phasechange = NULL;
    143 struct notifier *exitnotify = NULL;
    144 struct notifier *sigreceived = NULL;
    145 struct notifier *fork_notifier = NULL;
    146 
    147 int hungup;			/* terminal has been hung up */
    148 int privileged;			/* we're running as real uid root */
    149 int need_holdoff;		/* need holdoff period before restarting */
    150 int detached;			/* have detached from terminal */
    151 volatile int status;		/* exit status for pppd */
    152 int unsuccess;			/* # unsuccessful connection attempts */
    153 int do_callback;		/* != 0 if we should do callback next */
    154 int doing_callback;		/* != 0 if we are doing callback */
    155 int ppp_session_number;		/* Session number, for channels with such a
    156 				   concept (eg PPPoE) */
    157 int childwait_done;		/* have timed out waiting for children */
    158 
    159 #ifdef USE_TDB
    160 TDB_CONTEXT *pppdb;		/* database for storing status etc. */
    161 #endif
    162 
    163 char db_key[32];
    164 
    165 int (*holdoff_hook) __P((void)) = NULL;
    166 int (*new_phase_hook) __P((int)) = NULL;
    167 void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
    168 void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
    169 
    170 static int conn_running;	/* we have a [dis]connector running */
    171 static int fd_loop;		/* fd for getting demand-dial packets */
    172 
    173 int fd_devnull;			/* fd for /dev/null */
    174 int devfd = -1;			/* fd of underlying device */
    175 int fd_ppp = -1;		/* fd for talking PPP */
    176 int phase;			/* where the link is at */
    177 int kill_link;
    178 int asked_to_quit;
    179 int open_ccp_flag;
    180 int listen_time;
    181 int got_sigusr2;
    182 int got_sigterm;
    183 int got_sighup;
    184 
    185 static sigset_t signals_handled;
    186 static int waiting;
    187 static sigjmp_buf sigjmp;
    188 
    189 char **script_env;		/* Env. variable values for scripts */
    190 int s_env_nalloc;		/* # words avail at script_env */
    191 
    192 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
    193 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
    194 
    195 static int n_children;		/* # child processes still running */
    196 static int got_sigchld;		/* set if we have received a SIGCHLD */
    197 
    198 int privopen;			/* don't lock, open device as root */
    199 
    200 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
    201 
    202 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
    203 int ngroups;			/* How many groups valid in groups */
    204 
    205 static struct timeval start_time;	/* Time when link was started. */
    206 
    207 static struct pppd_stats old_link_stats;
    208 struct pppd_stats link_stats;
    209 unsigned link_connect_time;
    210 int link_stats_valid;
    211 
    212 int error_count;
    213 
    214 bool bundle_eof;
    215 bool bundle_terminating;
    216 
    217 /*
    218  * We maintain a list of child process pids and
    219  * functions to call when they exit.
    220  */
    221 struct subprocess {
    222     pid_t	pid;
    223     char	*prog;
    224     void	(*done) __P((void *));
    225     void	*arg;
    226     int		killable;
    227     struct subprocess *next;
    228 };
    229 
    230 static struct subprocess *children;
    231 
    232 /* Prototypes for procedures local to this file. */
    233 
    234 static void setup_signals __P((void));
    235 static void create_pidfile __P((int pid));
    236 static void create_linkpidfile __P((int pid));
    237 static void cleanup __P((void));
    238 static void get_input __P((void));
    239 static void calltimeout __P((void));
    240 static struct timeval *timeleft __P((struct timeval *));
    241 static void kill_my_pg __P((int));
    242 static void hup __P((int));
    243 static void term __P((int));
    244 static void chld __P((int));
    245 static void toggle_debug __P((int));
    246 static void open_ccp __P((int));
    247 static void bad_signal __P((int));
    248 static void holdoff_end __P((void *));
    249 static void forget_child __P((int pid, int status));
    250 static int reap_kids __P((void));
    251 static void childwait_end __P((void *));
    252 
    253 #ifdef USE_TDB
    254 static void update_db_entry __P((void));
    255 static void add_db_key __P((const char *));
    256 static void delete_db_key __P((const char *));
    257 static void cleanup_db __P((void));
    258 #endif
    259 
    260 static void handle_events __P((void));
    261 void print_link_stats __P((void));
    262 
    263 extern	char	*ttyname __P((int));
    264 extern	char	*getlogin __P((void));
    265 int main __P((int, char *[]));
    266 
    267 #ifdef ultrix
    268 #undef	O_NONBLOCK
    269 #define	O_NONBLOCK	O_NDELAY
    270 #endif
    271 
    272 #ifdef ULTRIX
    273 #define setlogmask(x)
    274 #endif
    275 
    276 /*
    277  * PPP Data Link Layer "protocol" table.
    278  * One entry per supported protocol.
    279  * The last entry must be NULL.
    280  */
    281 struct protent *protocols[] = {
    282     &lcp_protent,
    283     &pap_protent,
    284     &chap_protent,
    285 #ifdef CBCP_SUPPORT
    286     &cbcp_protent,
    287 #endif
    288     &ipcp_protent,
    289 #ifdef INET6
    290     &ipv6cp_protent,
    291 #endif
    292     &ccp_protent,
    293     &ecp_protent,
    294 #ifdef IPX_CHANGE
    295     &ipxcp_protent,
    296 #endif
    297 #ifdef AT_CHANGE
    298     &atcp_protent,
    299 #endif
    300     &eap_protent,
    301     NULL
    302 };
    303 
    304 /*
    305  * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
    306  */
    307 #if !defined(PPP_DRV_NAME)
    308 #define PPP_DRV_NAME	"ppp"
    309 #endif /* !defined(PPP_DRV_NAME) */
    310 
    311 int
    312 main(argc, argv)
    313     int argc;
    314     char *argv[];
    315 {
    316     int i, t;
    317     char *p;
    318     struct passwd *pw;
    319     struct protent *protp;
    320     char numbuf[16];
    321 
    322     link_stats_valid = 0;
    323     new_phase(PHASE_INITIALIZE);
    324 
    325     script_env = NULL;
    326 
    327     /* Initialize syslog facilities */
    328     reopen_log();
    329 
    330     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
    331 	option_error("Couldn't get hostname: %m");
    332 	exit(1);
    333     }
    334     hostname[MAXNAMELEN-1] = 0;
    335 
    336     /* make sure we don't create world or group writable files. */
    337     umask(umask(0777) | 022);
    338 
    339     uid = getuid();
    340     privileged = uid == 0;
    341     slprintf(numbuf, sizeof(numbuf), "%d", uid);
    342     script_setenv("ORIG_UID", numbuf, 0);
    343 
    344     ngroups = getgroups(NGROUPS_MAX, groups);
    345 
    346     /*
    347      * Initialize magic number generator now so that protocols may
    348      * use magic numbers in initialization.
    349      */
    350     magic_init();
    351 
    352     /*
    353      * Initialize each protocol.
    354      */
    355     for (i = 0; (protp = protocols[i]) != NULL; ++i)
    356         (*protp->init)(0);
    357 
    358     /*
    359      * Initialize the default channel.
    360      */
    361     tty_init();
    362 
    363     progname = *argv;
    364 
    365 #if defined(__ANDROID__)
    366     {
    367         extern void pppox_init();
    368         pppox_init();
    369         privileged = 1;
    370     }
    371     {
    372         char *envargs = getenv("envargs");
    373         if (envargs) {
    374             int i;
    375             /* Decode the arguments in-place and count the number of them.
    376              * They were hex encoded using [A-P] instead of [0-9A-F]. */
    377             for (argc = 0, i = 0; envargs[i] && envargs[i + 1]; i += 2) {
    378                 char c = ((envargs[i] - 'A') << 4) + (envargs[i + 1] - 'A');
    379                 if (c == 0) {
    380                     ++argc;
    381                 }
    382                 envargs[i / 2 + 1] = c;
    383             }
    384             if (argc == 0 || (argv = malloc(sizeof(char *) * argc)) == NULL) {
    385                 fatal("Failed to parse envargs!");
    386             }
    387             for (envargs[0] = 0, i = 0; i < argc; ++envargs) {
    388                 if (envargs[0] == 0) {
    389                     argv[i++] = &envargs[1];
    390                 }
    391             }
    392         }
    393     }
    394 #endif
    395 
    396     /*
    397      * Parse, in order, the system options file, the user's options file,
    398      * and the command line arguments.
    399      */
    400 #if defined(__ANDROID__)
    401     /* Android: only take options from commandline */
    402     if (!parse_args(argc-1, argv+1))
    403 	exit(EXIT_OPTION_ERROR);
    404 
    405 #else
    406     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
    407 	|| !options_from_user()
    408 	|| !parse_args(argc-1, argv+1))
    409 	exit(EXIT_OPTION_ERROR);
    410 
    411 #endif
    412 
    413     devnam_fixed = 1;		/* can no longer change device name */
    414 
    415     /*
    416      * Work out the device name, if it hasn't already been specified,
    417      * and parse the tty's options file.
    418      */
    419     if (the_channel->process_extra_options)
    420 	(*the_channel->process_extra_options)();
    421 
    422     if (debug)
    423 	setlogmask(LOG_UPTO(LOG_DEBUG));
    424 
    425 #if !defined(__ANDROID__)
    426     /*
    427      * Check that we are running as root.
    428      */
    429     if (geteuid() != 0) {
    430 	option_error("must be root to run %s, since it is not setuid-root",
    431 		     argv[0]);
    432 	exit(EXIT_NOT_ROOT);
    433     }
    434 #endif
    435 
    436     if (!ppp_available()) {
    437 	option_error("%s", no_ppp_msg);
    438 	exit(EXIT_NO_KERNEL_SUPPORT);
    439     }
    440 
    441     /*
    442      * Check that the options given are valid and consistent.
    443      */
    444     check_options();
    445     if (!sys_check_options())
    446 	exit(EXIT_OPTION_ERROR);
    447     auth_check_options();
    448 #ifdef HAVE_MULTILINK
    449     mp_check_options();
    450 #endif
    451     for (i = 0; (protp = protocols[i]) != NULL; ++i)
    452 	if (protp->check_options != NULL)
    453 	    (*protp->check_options)();
    454     if (the_channel->check_options)
    455 	(*the_channel->check_options)();
    456 
    457 
    458     if (dump_options || dryrun) {
    459 	init_pr_log(NULL, LOG_INFO);
    460 	print_options(pr_log, NULL);
    461 	end_pr_log();
    462     }
    463 
    464     if (dryrun)
    465 	die(0);
    466 
    467     /* Make sure fds 0, 1, 2 are open to somewhere. */
    468     fd_devnull = open(_PATH_DEVNULL, O_RDWR);
    469     if (fd_devnull < 0)
    470 	fatal("Couldn't open %s: %m", _PATH_DEVNULL);
    471     while (fd_devnull <= 2) {
    472 	i = dup(fd_devnull);
    473 	if (i < 0)
    474 	    fatal("Critical shortage of file descriptors: dup failed: %m");
    475 	fd_devnull = i;
    476     }
    477 
    478     /*
    479      * Initialize system-dependent stuff.
    480      */
    481     sys_init();
    482 #ifdef USE_TDB
    483     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
    484     if (pppdb != NULL) {
    485 	slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
    486 	update_db_entry();
    487     } else {
    488 	warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
    489 	if (multilink) {
    490 	    warn("Warning: disabling multilink");
    491 	    multilink = 0;
    492 	}
    493     }
    494 #endif
    495 
    496     /*
    497      * Detach ourselves from the terminal, if required,
    498      * and identify who is running us.
    499      */
    500     if (!nodetach && !updetach)
    501 	detach();
    502     p = getlogin();
    503     if (p == NULL) {
    504 	pw = getpwuid(uid);
    505 	if (pw != NULL && pw->pw_name != NULL)
    506 	    p = pw->pw_name;
    507 	else
    508 	    p = "(unknown)";
    509     }
    510     syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
    511     script_setenv("PPPLOGNAME", p, 0);
    512 
    513     if (devnam[0])
    514 	script_setenv("DEVICE", devnam, 1);
    515     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
    516     script_setenv("PPPD_PID", numbuf, 1);
    517 
    518     setup_signals();
    519 
    520     create_linkpidfile(getpid());
    521 
    522     waiting = 0;
    523 
    524     /*
    525      * If we're doing dial-on-demand, set up the interface now.
    526      */
    527     if (demand) {
    528 	/*
    529 	 * Open the loopback channel and set it up to be the ppp interface.
    530 	 */
    531 	fd_loop = open_ppp_loopback();
    532 	set_ifunit(1);
    533 	/*
    534 	 * Configure the interface and mark it up, etc.
    535 	 */
    536 	demand_conf();
    537     }
    538 
    539     do_callback = 0;
    540     for (;;) {
    541 
    542 	bundle_eof = 0;
    543 	bundle_terminating = 0;
    544 	listen_time = 0;
    545 	need_holdoff = 1;
    546 	devfd = -1;
    547 	status = EXIT_OK;
    548 	++unsuccess;
    549 	doing_callback = do_callback;
    550 	do_callback = 0;
    551 
    552 	if (demand && !doing_callback) {
    553 	    /*
    554 	     * Don't do anything until we see some activity.
    555 	     */
    556 	    new_phase(PHASE_DORMANT);
    557 	    demand_unblock();
    558 	    add_fd(fd_loop);
    559 	    for (;;) {
    560 		handle_events();
    561 		if (asked_to_quit)
    562 		    break;
    563 		if (get_loop_output())
    564 		    break;
    565 	    }
    566 	    remove_fd(fd_loop);
    567 	    if (asked_to_quit)
    568 		break;
    569 
    570 	    /*
    571 	     * Now we want to bring up the link.
    572 	     */
    573 	    demand_block();
    574 	    info("Starting link");
    575 	}
    576 
    577 	gettimeofday(&start_time, NULL);
    578 	script_unsetenv("CONNECT_TIME");
    579 	script_unsetenv("BYTES_SENT");
    580 	script_unsetenv("BYTES_RCVD");
    581 
    582 	lcp_open(0);		/* Start protocol */
    583 	start_link(0);
    584 	while (phase != PHASE_DEAD) {
    585 	    handle_events();
    586 	    get_input();
    587 	    if (kill_link)
    588 		lcp_close(0, "User request");
    589 	    if (asked_to_quit) {
    590 		bundle_terminating = 1;
    591 		if (phase == PHASE_MASTER)
    592 		    mp_bundle_terminated();
    593 	    }
    594 	    if (open_ccp_flag) {
    595 		if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
    596 		    ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
    597 		    (*ccp_protent.open)(0);
    598 		}
    599 	    }
    600 	}
    601 	/* restore FSMs to original state */
    602 	lcp_close(0, "");
    603 
    604 	if (!persist || asked_to_quit || (maxfail > 0 && unsuccess >= maxfail))
    605 	    break;
    606 
    607 	if (demand)
    608 	    demand_discard();
    609 	t = need_holdoff? holdoff: 0;
    610 	if (holdoff_hook)
    611 	    t = (*holdoff_hook)();
    612 	if (t > 0) {
    613 	    new_phase(PHASE_HOLDOFF);
    614 	    TIMEOUT(holdoff_end, NULL, t);
    615 	    do {
    616 		handle_events();
    617 		if (kill_link)
    618 		    new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
    619 	    } while (phase == PHASE_HOLDOFF);
    620 	    if (!persist)
    621 		break;
    622 	}
    623     }
    624 
    625     /* Wait for scripts to finish */
    626     reap_kids();
    627     if (n_children > 0) {
    628 	if (child_wait > 0)
    629 	    TIMEOUT(childwait_end, NULL, child_wait);
    630 	if (debug) {
    631 	    struct subprocess *chp;
    632 	    dbglog("Waiting for %d child processes...", n_children);
    633 	    for (chp = children; chp != NULL; chp = chp->next)
    634 		dbglog("  script %s, pid %d", chp->prog, chp->pid);
    635 	}
    636 	while (n_children > 0 && !childwait_done) {
    637 	    handle_events();
    638 	    if (kill_link && !childwait_done)
    639 		childwait_end(NULL);
    640 	}
    641     }
    642 
    643     die(status);
    644     return 0;
    645 }
    646 
    647 /*
    648  * handle_events - wait for something to happen and respond to it.
    649  */
    650 static void
    651 handle_events()
    652 {
    653     struct timeval timo;
    654 
    655     kill_link = open_ccp_flag = 0;
    656     if (sigsetjmp(sigjmp, 1) == 0) {
    657 	sigprocmask(SIG_BLOCK, &signals_handled, NULL);
    658 	if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
    659 	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
    660 	} else {
    661 	    waiting = 1;
    662 	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
    663 	    wait_input(timeleft(&timo));
    664 	}
    665     }
    666     waiting = 0;
    667     calltimeout();
    668     if (got_sighup) {
    669 	info("Hangup (SIGHUP)");
    670 	kill_link = 1;
    671 	got_sighup = 0;
    672 	if (status != EXIT_HANGUP)
    673 	    status = EXIT_USER_REQUEST;
    674     }
    675     if (got_sigterm) {
    676 	info("Terminating on signal %d", got_sigterm);
    677 	kill_link = 1;
    678 	asked_to_quit = 1;
    679 	persist = 0;
    680 	status = EXIT_USER_REQUEST;
    681 	got_sigterm = 0;
    682     }
    683     if (got_sigchld) {
    684 	got_sigchld = 0;
    685 	reap_kids();	/* Don't leave dead kids lying around */
    686     }
    687     if (got_sigusr2) {
    688 	open_ccp_flag = 1;
    689 	got_sigusr2 = 0;
    690     }
    691 }
    692 
    693 /*
    694  * setup_signals - initialize signal handling.
    695  */
    696 static void
    697 setup_signals()
    698 {
    699     struct sigaction sa;
    700 
    701     /*
    702      * Compute mask of all interesting signals and install signal handlers
    703      * for each.  Only one signal handler may be active at a time.  Therefore,
    704      * all other signals should be masked when any handler is executing.
    705      */
    706     sigemptyset(&signals_handled);
    707     sigaddset(&signals_handled, SIGHUP);
    708     sigaddset(&signals_handled, SIGINT);
    709     sigaddset(&signals_handled, SIGTERM);
    710     sigaddset(&signals_handled, SIGCHLD);
    711     sigaddset(&signals_handled, SIGUSR2);
    712 
    713 #define SIGNAL(s, handler)	do { \
    714 	sa.sa_handler = handler; \
    715 	if (sigaction(s, &sa, NULL) < 0) \
    716 	    fatal("Couldn't establish signal handler (%d): %m", s); \
    717     } while (0)
    718 
    719     sa.sa_mask = signals_handled;
    720     sa.sa_flags = 0;
    721     SIGNAL(SIGHUP, hup);		/* Hangup */
    722     SIGNAL(SIGINT, term);		/* Interrupt */
    723     SIGNAL(SIGTERM, term);		/* Terminate */
    724     SIGNAL(SIGCHLD, chld);
    725 
    726     SIGNAL(SIGUSR1, toggle_debug);	/* Toggle debug flag */
    727     SIGNAL(SIGUSR2, open_ccp);		/* Reopen CCP */
    728 
    729     /*
    730      * Install a handler for other signals which would otherwise
    731      * cause pppd to exit without cleaning up.
    732      */
    733     SIGNAL(SIGABRT, bad_signal);
    734     SIGNAL(SIGALRM, bad_signal);
    735     SIGNAL(SIGFPE, bad_signal);
    736     SIGNAL(SIGILL, bad_signal);
    737     SIGNAL(SIGPIPE, bad_signal);
    738     SIGNAL(SIGQUIT, bad_signal);
    739     SIGNAL(SIGSEGV, bad_signal);
    740 #ifdef SIGBUS
    741     SIGNAL(SIGBUS, bad_signal);
    742 #endif
    743 #ifdef SIGEMT
    744     SIGNAL(SIGEMT, bad_signal);
    745 #endif
    746 #ifdef SIGPOLL
    747     SIGNAL(SIGPOLL, bad_signal);
    748 #endif
    749 #ifdef SIGPROF
    750     SIGNAL(SIGPROF, bad_signal);
    751 #endif
    752 #ifdef SIGSYS
    753     SIGNAL(SIGSYS, bad_signal);
    754 #endif
    755 #ifdef SIGTRAP
    756     SIGNAL(SIGTRAP, bad_signal);
    757 #endif
    758 #ifdef SIGVTALRM
    759     SIGNAL(SIGVTALRM, bad_signal);
    760 #endif
    761 #ifdef SIGXCPU
    762     SIGNAL(SIGXCPU, bad_signal);
    763 #endif
    764 #ifdef SIGXFSZ
    765     SIGNAL(SIGXFSZ, bad_signal);
    766 #endif
    767 
    768     /*
    769      * Apparently we can get a SIGPIPE when we call syslog, if
    770      * syslogd has died and been restarted.  Ignoring it seems
    771      * be sufficient.
    772      */
    773     signal(SIGPIPE, SIG_IGN);
    774 }
    775 
    776 /*
    777  * set_ifunit - do things we need to do once we know which ppp
    778  * unit we are using.
    779  */
    780 void
    781 set_ifunit(iskey)
    782     int iskey;
    783 {
    784     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
    785     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
    786     script_setenv("IFNAME", ifname, iskey);
    787     if (iskey) {
    788 	create_pidfile(getpid());	/* write pid to file */
    789 	create_linkpidfile(getpid());
    790     }
    791 }
    792 
    793 /*
    794  * detach - detach us from the controlling terminal.
    795  */
    796 void
    797 detach()
    798 {
    799     int pid;
    800     char numbuf[16];
    801     int pipefd[2];
    802 
    803     if (detached)
    804 	return;
    805     if (pipe(pipefd) == -1)
    806 	pipefd[0] = pipefd[1] = -1;
    807     if ((pid = fork()) < 0) {
    808 	error("Couldn't detach (fork failed: %m)");
    809 	die(1);			/* or just return? */
    810     }
    811     if (pid != 0) {
    812 	/* parent */
    813 	notify(pidchange, pid);
    814 	/* update pid files if they have been written already */
    815 	if (pidfilename[0])
    816 	    create_pidfile(pid);
    817 	if (linkpidfile[0])
    818 	    create_linkpidfile(pid);
    819 	exit(0);		/* parent dies */
    820     }
    821     setsid();
    822     chdir("/");
    823     dup2(fd_devnull, 0);
    824     dup2(fd_devnull, 1);
    825     dup2(fd_devnull, 2);
    826     detached = 1;
    827     if (log_default)
    828 	log_to_fd = -1;
    829     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
    830     script_setenv("PPPD_PID", numbuf, 1);
    831 
    832     /* wait for parent to finish updating pid & lock files and die */
    833     close(pipefd[1]);
    834     complete_read(pipefd[0], numbuf, 1);
    835     close(pipefd[0]);
    836 }
    837 
    838 /*
    839  * reopen_log - (re)open our connection to syslog.
    840  */
    841 void
    842 reopen_log()
    843 {
    844     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
    845     setlogmask(LOG_UPTO(LOG_INFO));
    846 }
    847 
    848 /*
    849  * Create a file containing our process ID.
    850  */
    851 static void
    852 create_pidfile(pid)
    853     int pid;
    854 {
    855 #if !defined(__ANDROID__)
    856     FILE *pidfile;
    857 
    858     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
    859 	     _PATH_VARRUN, ifname);
    860     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
    861 	fprintf(pidfile, "%d\n", pid);
    862 	(void) fclose(pidfile);
    863     } else {
    864 	error("Failed to create pid file %s: %m", pidfilename);
    865 	pidfilename[0] = 0;
    866     }
    867 #endif
    868 }
    869 
    870 void
    871 create_linkpidfile(pid)
    872     int pid;
    873 {
    874 #if !defined(__ANDROID__)
    875     FILE *pidfile;
    876 
    877     if (linkname[0] == 0)
    878 	return;
    879     script_setenv("LINKNAME", linkname, 1);
    880     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
    881 	     _PATH_VARRUN, linkname);
    882     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
    883 	fprintf(pidfile, "%d\n", pid);
    884 	if (ifname[0])
    885 	    fprintf(pidfile, "%s\n", ifname);
    886 	(void) fclose(pidfile);
    887     } else {
    888 	error("Failed to create pid file %s: %m", linkpidfile);
    889 	linkpidfile[0] = 0;
    890     }
    891 #endif
    892 }
    893 
    894 /*
    895  * remove_pidfile - remove our pid files
    896  */
    897 void remove_pidfiles()
    898 {
    899 #if !defined(__ANDROID__)
    900     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
    901 	warn("unable to delete pid file %s: %m", pidfilename);
    902     pidfilename[0] = 0;
    903     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
    904 	warn("unable to delete pid file %s: %m", linkpidfile);
    905     linkpidfile[0] = 0;
    906 #endif
    907 }
    908 
    909 /*
    910  * holdoff_end - called via a timeout when the holdoff period ends.
    911  */
    912 static void
    913 holdoff_end(arg)
    914     void *arg;
    915 {
    916     new_phase(PHASE_DORMANT);
    917 }
    918 
    919 /* List of protocol names, to make our messages a little more informative. */
    920 struct protocol_list {
    921     u_short	proto;
    922     const char	*name;
    923 } protocol_list[] = {
    924     { 0x21,	"IP" },
    925     { 0x23,	"OSI Network Layer" },
    926     { 0x25,	"Xerox NS IDP" },
    927     { 0x27,	"DECnet Phase IV" },
    928     { 0x29,	"Appletalk" },
    929     { 0x2b,	"Novell IPX" },
    930     { 0x2d,	"VJ compressed TCP/IP" },
    931     { 0x2f,	"VJ uncompressed TCP/IP" },
    932     { 0x31,	"Bridging PDU" },
    933     { 0x33,	"Stream Protocol ST-II" },
    934     { 0x35,	"Banyan Vines" },
    935     { 0x39,	"AppleTalk EDDP" },
    936     { 0x3b,	"AppleTalk SmartBuffered" },
    937     { 0x3d,	"Multi-Link" },
    938     { 0x3f,	"NETBIOS Framing" },
    939     { 0x41,	"Cisco Systems" },
    940     { 0x43,	"Ascom Timeplex" },
    941     { 0x45,	"Fujitsu Link Backup and Load Balancing (LBLB)" },
    942     { 0x47,	"DCA Remote Lan" },
    943     { 0x49,	"Serial Data Transport Protocol (PPP-SDTP)" },
    944     { 0x4b,	"SNA over 802.2" },
    945     { 0x4d,	"SNA" },
    946     { 0x4f,	"IP6 Header Compression" },
    947     { 0x51,	"KNX Bridging Data" },
    948     { 0x53,	"Encryption" },
    949     { 0x55,	"Individual Link Encryption" },
    950     { 0x57,	"IPv6" },
    951     { 0x59,	"PPP Muxing" },
    952     { 0x5b,	"Vendor-Specific Network Protocol" },
    953     { 0x61,	"RTP IPHC Full Header" },
    954     { 0x63,	"RTP IPHC Compressed TCP" },
    955     { 0x65,	"RTP IPHC Compressed non-TCP" },
    956     { 0x67,	"RTP IPHC Compressed UDP 8" },
    957     { 0x69,	"RTP IPHC Compressed RTP 8" },
    958     { 0x6f,	"Stampede Bridging" },
    959     { 0x73,	"MP+" },
    960     { 0xc1,	"NTCITS IPI" },
    961     { 0xfb,	"single-link compression" },
    962     { 0xfd,	"Compressed Datagram" },
    963     { 0x0201,	"802.1d Hello Packets" },
    964     { 0x0203,	"IBM Source Routing BPDU" },
    965     { 0x0205,	"DEC LANBridge100 Spanning Tree" },
    966     { 0x0207,	"Cisco Discovery Protocol" },
    967     { 0x0209,	"Netcs Twin Routing" },
    968     { 0x020b,	"STP - Scheduled Transfer Protocol" },
    969     { 0x020d,	"EDP - Extreme Discovery Protocol" },
    970     { 0x0211,	"Optical Supervisory Channel Protocol" },
    971     { 0x0213,	"Optical Supervisory Channel Protocol" },
    972     { 0x0231,	"Luxcom" },
    973     { 0x0233,	"Sigma Network Systems" },
    974     { 0x0235,	"Apple Client Server Protocol" },
    975     { 0x0281,	"MPLS Unicast" },
    976     { 0x0283,	"MPLS Multicast" },
    977     { 0x0285,	"IEEE p1284.4 standard - data packets" },
    978     { 0x0287,	"ETSI TETRA Network Protocol Type 1" },
    979     { 0x0289,	"Multichannel Flow Treatment Protocol" },
    980     { 0x2063,	"RTP IPHC Compressed TCP No Delta" },
    981     { 0x2065,	"RTP IPHC Context State" },
    982     { 0x2067,	"RTP IPHC Compressed UDP 16" },
    983     { 0x2069,	"RTP IPHC Compressed RTP 16" },
    984     { 0x4001,	"Cray Communications Control Protocol" },
    985     { 0x4003,	"CDPD Mobile Network Registration Protocol" },
    986     { 0x4005,	"Expand accelerator protocol" },
    987     { 0x4007,	"ODSICP NCP" },
    988     { 0x4009,	"DOCSIS DLL" },
    989     { 0x400B,	"Cetacean Network Detection Protocol" },
    990     { 0x4021,	"Stacker LZS" },
    991     { 0x4023,	"RefTek Protocol" },
    992     { 0x4025,	"Fibre Channel" },
    993     { 0x4027,	"EMIT Protocols" },
    994     { 0x405b,	"Vendor-Specific Protocol (VSP)" },
    995     { 0x8021,	"Internet Protocol Control Protocol" },
    996     { 0x8023,	"OSI Network Layer Control Protocol" },
    997     { 0x8025,	"Xerox NS IDP Control Protocol" },
    998     { 0x8027,	"DECnet Phase IV Control Protocol" },
    999     { 0x8029,	"Appletalk Control Protocol" },
   1000     { 0x802b,	"Novell IPX Control Protocol" },
   1001     { 0x8031,	"Bridging NCP" },
   1002     { 0x8033,	"Stream Protocol Control Protocol" },
   1003     { 0x8035,	"Banyan Vines Control Protocol" },
   1004     { 0x803d,	"Multi-Link Control Protocol" },
   1005     { 0x803f,	"NETBIOS Framing Control Protocol" },
   1006     { 0x8041,	"Cisco Systems Control Protocol" },
   1007     { 0x8043,	"Ascom Timeplex" },
   1008     { 0x8045,	"Fujitsu LBLB Control Protocol" },
   1009     { 0x8047,	"DCA Remote Lan Network Control Protocol (RLNCP)" },
   1010     { 0x8049,	"Serial Data Control Protocol (PPP-SDCP)" },
   1011     { 0x804b,	"SNA over 802.2 Control Protocol" },
   1012     { 0x804d,	"SNA Control Protocol" },
   1013     { 0x804f,	"IP6 Header Compression Control Protocol" },
   1014     { 0x8051,	"KNX Bridging Control Protocol" },
   1015     { 0x8053,	"Encryption Control Protocol" },
   1016     { 0x8055,	"Individual Link Encryption Control Protocol" },
   1017     { 0x8057,	"IPv6 Control Protocol" },
   1018     { 0x8059,	"PPP Muxing Control Protocol" },
   1019     { 0x805b,	"Vendor-Specific Network Control Protocol (VSNCP)" },
   1020     { 0x806f,	"Stampede Bridging Control Protocol" },
   1021     { 0x8073,	"MP+ Control Protocol" },
   1022     { 0x80c1,	"NTCITS IPI Control Protocol" },
   1023     { 0x80fb,	"Single Link Compression Control Protocol" },
   1024     { 0x80fd,	"Compression Control Protocol" },
   1025     { 0x8207,	"Cisco Discovery Protocol Control" },
   1026     { 0x8209,	"Netcs Twin Routing" },
   1027     { 0x820b,	"STP - Control Protocol" },
   1028     { 0x820d,	"EDPCP - Extreme Discovery Protocol Ctrl Prtcl" },
   1029     { 0x8235,	"Apple Client Server Protocol Control" },
   1030     { 0x8281,	"MPLSCP" },
   1031     { 0x8285,	"IEEE p1284.4 standard - Protocol Control" },
   1032     { 0x8287,	"ETSI TETRA TNP1 Control Protocol" },
   1033     { 0x8289,	"Multichannel Flow Treatment Protocol" },
   1034     { 0xc021,	"Link Control Protocol" },
   1035     { 0xc023,	"Password Authentication Protocol" },
   1036     { 0xc025,	"Link Quality Report" },
   1037     { 0xc027,	"Shiva Password Authentication Protocol" },
   1038     { 0xc029,	"CallBack Control Protocol (CBCP)" },
   1039     { 0xc02b,	"BACP Bandwidth Allocation Control Protocol" },
   1040     { 0xc02d,	"BAP" },
   1041     { 0xc05b,	"Vendor-Specific Authentication Protocol (VSAP)" },
   1042     { 0xc081,	"Container Control Protocol" },
   1043     { 0xc223,	"Challenge Handshake Authentication Protocol" },
   1044     { 0xc225,	"RSA Authentication Protocol" },
   1045     { 0xc227,	"Extensible Authentication Protocol" },
   1046     { 0xc229,	"Mitsubishi Security Info Exch Ptcl (SIEP)" },
   1047     { 0xc26f,	"Stampede Bridging Authorization Protocol" },
   1048     { 0xc281,	"Proprietary Authentication Protocol" },
   1049     { 0xc283,	"Proprietary Authentication Protocol" },
   1050     { 0xc481,	"Proprietary Node ID Authentication Protocol" },
   1051     { 0,	NULL },
   1052 };
   1053 
   1054 /*
   1055  * protocol_name - find a name for a PPP protocol.
   1056  */
   1057 const char *
   1058 protocol_name(proto)
   1059     int proto;
   1060 {
   1061     struct protocol_list *lp;
   1062 
   1063     for (lp = protocol_list; lp->proto != 0; ++lp)
   1064 	if (proto == lp->proto)
   1065 	    return lp->name;
   1066     return NULL;
   1067 }
   1068 
   1069 /*
   1070  * get_input - called when incoming data is available.
   1071  */
   1072 static void
   1073 get_input()
   1074 {
   1075     int len, i;
   1076     u_char *p;
   1077     u_short protocol;
   1078     struct protent *protp;
   1079 
   1080     p = inpacket_buf;	/* point to beginning of packet buffer */
   1081 
   1082     len = read_packet(inpacket_buf);
   1083     if (len < 0)
   1084 	return;
   1085 
   1086     if (len == 0) {
   1087 	if (bundle_eof && multilink_master) {
   1088 	    notice("Last channel has disconnected");
   1089 	    mp_bundle_terminated();
   1090 	    return;
   1091 	}
   1092 	notice("Modem hangup");
   1093 	hungup = 1;
   1094 	status = EXIT_HANGUP;
   1095 	lcp_lowerdown(0);	/* serial link is no longer available */
   1096 	link_terminated(0);
   1097 	return;
   1098     }
   1099 
   1100     if (len < PPP_HDRLEN) {
   1101 	dbglog("received short packet:%.*B", len, p);
   1102 	return;
   1103     }
   1104 
   1105     dump_packet("rcvd", p, len);
   1106     if (snoop_recv_hook) snoop_recv_hook(p, len);
   1107 
   1108     p += 2;				/* Skip address and control */
   1109     GETSHORT(protocol, p);
   1110     len -= PPP_HDRLEN;
   1111 
   1112     /*
   1113      * Toss all non-LCP packets unless LCP is OPEN.
   1114      */
   1115     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
   1116 	dbglog("Discarded non-LCP packet when LCP not open");
   1117 	return;
   1118     }
   1119 
   1120     /*
   1121      * Until we get past the authentication phase, toss all packets
   1122      * except LCP, LQR and authentication packets.
   1123      */
   1124     if (phase <= PHASE_AUTHENTICATE
   1125 	&& !(protocol == PPP_LCP || protocol == PPP_LQR
   1126 	     || protocol == PPP_PAP || protocol == PPP_CHAP ||
   1127 		protocol == PPP_EAP)) {
   1128 	dbglog("discarding proto 0x%x in phase %d",
   1129 		   protocol, phase);
   1130 	return;
   1131     }
   1132 
   1133     /*
   1134      * Upcall the proper protocol input routine.
   1135      */
   1136     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
   1137 	if (protp->protocol == protocol && protp->enabled_flag) {
   1138 	    (*protp->input)(0, p, len);
   1139 	    return;
   1140 	}
   1141         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
   1142 	    && protp->datainput != NULL) {
   1143 	    (*protp->datainput)(0, p, len);
   1144 	    return;
   1145 	}
   1146     }
   1147 
   1148     if (debug) {
   1149 	const char *pname = protocol_name(protocol);
   1150 	if (pname != NULL)
   1151 	    warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
   1152 	else
   1153 	    warn("Unsupported protocol 0x%x received", protocol);
   1154     }
   1155     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
   1156 }
   1157 
   1158 /*
   1159  * ppp_send_config - configure the transmit-side characteristics of
   1160  * the ppp interface.  Returns -1, indicating an error, if the channel
   1161  * send_config procedure called error() (or incremented error_count
   1162  * itself), otherwise 0.
   1163  */
   1164 int
   1165 ppp_send_config(unit, mtu, accm, pcomp, accomp)
   1166     int unit, mtu;
   1167     u_int32_t accm;
   1168     int pcomp, accomp;
   1169 {
   1170 	int errs;
   1171 
   1172 	if (the_channel->send_config == NULL)
   1173 		return 0;
   1174 	errs = error_count;
   1175 	(*the_channel->send_config)(mtu, accm, pcomp, accomp);
   1176 	return (error_count != errs)? -1: 0;
   1177 }
   1178 
   1179 /*
   1180  * ppp_recv_config - configure the receive-side characteristics of
   1181  * the ppp interface.  Returns -1, indicating an error, if the channel
   1182  * recv_config procedure called error() (or incremented error_count
   1183  * itself), otherwise 0.
   1184  */
   1185 int
   1186 ppp_recv_config(unit, mru, accm, pcomp, accomp)
   1187     int unit, mru;
   1188     u_int32_t accm;
   1189     int pcomp, accomp;
   1190 {
   1191 	int errs;
   1192 
   1193 	if (the_channel->recv_config == NULL)
   1194 		return 0;
   1195 	errs = error_count;
   1196 	(*the_channel->recv_config)(mru, accm, pcomp, accomp);
   1197 	return (error_count != errs)? -1: 0;
   1198 }
   1199 
   1200 /*
   1201  * new_phase - signal the start of a new phase of pppd's operation.
   1202  */
   1203 void
   1204 new_phase(p)
   1205     int p;
   1206 {
   1207     phase = p;
   1208     if (new_phase_hook)
   1209 	(*new_phase_hook)(p);
   1210     notify(phasechange, p);
   1211 }
   1212 
   1213 /*
   1214  * die - clean up state and exit with the specified status.
   1215  */
   1216 void
   1217 die(status)
   1218     int status;
   1219 {
   1220     if (!doing_multilink || multilink_master)
   1221 	print_link_stats();
   1222     cleanup();
   1223     notify(exitnotify, status);
   1224     syslog(LOG_INFO, "Exit.");
   1225     exit(status);
   1226 }
   1227 
   1228 /*
   1229  * cleanup - restore anything which needs to be restored before we exit
   1230  */
   1231 /* ARGSUSED */
   1232 static void
   1233 cleanup()
   1234 {
   1235     sys_cleanup();
   1236 
   1237     if (fd_ppp >= 0)
   1238 	the_channel->disestablish_ppp(devfd);
   1239     if (the_channel->cleanup)
   1240 	(*the_channel->cleanup)();
   1241     remove_pidfiles();
   1242 
   1243 #ifdef USE_TDB
   1244     if (pppdb != NULL)
   1245 	cleanup_db();
   1246 #endif
   1247 
   1248 }
   1249 
   1250 void
   1251 print_link_stats()
   1252 {
   1253     /*
   1254      * Print connect time and statistics.
   1255      */
   1256     if (link_stats_valid) {
   1257        int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
   1258        info("Connect time %d.%d minutes.", t/10, t%10);
   1259        info("Sent %u bytes, received %u bytes.",
   1260 	    link_stats.bytes_out, link_stats.bytes_in);
   1261        link_stats_valid = 0;
   1262     }
   1263 }
   1264 
   1265 /*
   1266  * reset_link_stats - "reset" stats when link goes up.
   1267  */
   1268 void
   1269 reset_link_stats(u)
   1270     int u;
   1271 {
   1272     if (!get_ppp_stats(u, &old_link_stats))
   1273 	return;
   1274     gettimeofday(&start_time, NULL);
   1275 }
   1276 
   1277 /*
   1278  * update_link_stats - get stats at link termination.
   1279  */
   1280 void
   1281 update_link_stats(u)
   1282     int u;
   1283 {
   1284     struct timeval now;
   1285     char numbuf[32];
   1286 
   1287     if (!get_ppp_stats(u, &link_stats)
   1288 	|| gettimeofday(&now, NULL) < 0)
   1289 	return;
   1290     link_connect_time = now.tv_sec - start_time.tv_sec;
   1291     link_stats_valid = 1;
   1292 
   1293     link_stats.bytes_in  -= old_link_stats.bytes_in;
   1294     link_stats.bytes_out -= old_link_stats.bytes_out;
   1295     link_stats.pkts_in   -= old_link_stats.pkts_in;
   1296     link_stats.pkts_out  -= old_link_stats.pkts_out;
   1297 
   1298     slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
   1299     script_setenv("CONNECT_TIME", numbuf, 0);
   1300     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
   1301     script_setenv("BYTES_SENT", numbuf, 0);
   1302     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
   1303     script_setenv("BYTES_RCVD", numbuf, 0);
   1304 }
   1305 
   1306 
   1307 struct	callout {
   1308     struct timeval	c_time;		/* time at which to call routine */
   1309     void		*c_arg;		/* argument to routine */
   1310     void		(*c_func) __P((void *)); /* routine */
   1311     struct		callout *c_next;
   1312 };
   1313 
   1314 static struct callout *callout = NULL;	/* Callout list */
   1315 static struct timeval timenow;		/* Current time */
   1316 
   1317 /*
   1318  * timeout - Schedule a timeout.
   1319  */
   1320 void
   1321 timeout(func, arg, secs, usecs)
   1322     void (*func) __P((void *));
   1323     void *arg;
   1324     int secs, usecs;
   1325 {
   1326     struct callout *newp, *p, **pp;
   1327 
   1328     /*
   1329      * Allocate timeout.
   1330      */
   1331     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
   1332 	fatal("Out of memory in timeout()!");
   1333     newp->c_arg = arg;
   1334     newp->c_func = func;
   1335     gettimeofday(&timenow, NULL);
   1336     newp->c_time.tv_sec = timenow.tv_sec + secs;
   1337     newp->c_time.tv_usec = timenow.tv_usec + usecs;
   1338     if (newp->c_time.tv_usec >= 1000000) {
   1339 	newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
   1340 	newp->c_time.tv_usec %= 1000000;
   1341     }
   1342 
   1343     /*
   1344      * Find correct place and link it in.
   1345      */
   1346     for (pp = &callout; (p = *pp); pp = &p->c_next)
   1347 	if (newp->c_time.tv_sec < p->c_time.tv_sec
   1348 	    || (newp->c_time.tv_sec == p->c_time.tv_sec
   1349 		&& newp->c_time.tv_usec < p->c_time.tv_usec))
   1350 	    break;
   1351     newp->c_next = p;
   1352     *pp = newp;
   1353 }
   1354 
   1355 
   1356 /*
   1357  * untimeout - Unschedule a timeout.
   1358  */
   1359 void
   1360 untimeout(func, arg)
   1361     void (*func) __P((void *));
   1362     void *arg;
   1363 {
   1364     struct callout **copp, *freep;
   1365 
   1366     /*
   1367      * Find first matching timeout and remove it from the list.
   1368      */
   1369     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
   1370 	if (freep->c_func == func && freep->c_arg == arg) {
   1371 	    *copp = freep->c_next;
   1372 	    free((char *) freep);
   1373 	    break;
   1374 	}
   1375 }
   1376 
   1377 
   1378 /*
   1379  * calltimeout - Call any timeout routines which are now due.
   1380  */
   1381 static void
   1382 calltimeout()
   1383 {
   1384     struct callout *p;
   1385 
   1386     while (callout != NULL) {
   1387 	p = callout;
   1388 
   1389 	if (gettimeofday(&timenow, NULL) < 0)
   1390 	    fatal("Failed to get time of day: %m");
   1391 	if (!(p->c_time.tv_sec < timenow.tv_sec
   1392 	      || (p->c_time.tv_sec == timenow.tv_sec
   1393 		  && p->c_time.tv_usec <= timenow.tv_usec)))
   1394 	    break;		/* no, it's not time yet */
   1395 
   1396 	callout = p->c_next;
   1397 	(*p->c_func)(p->c_arg);
   1398 
   1399 	free((char *) p);
   1400     }
   1401 }
   1402 
   1403 
   1404 /*
   1405  * timeleft - return the length of time until the next timeout is due.
   1406  */
   1407 static struct timeval *
   1408 timeleft(tvp)
   1409     struct timeval *tvp;
   1410 {
   1411     if (callout == NULL)
   1412 	return NULL;
   1413 
   1414     gettimeofday(&timenow, NULL);
   1415     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
   1416     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
   1417     if (tvp->tv_usec < 0) {
   1418 	tvp->tv_usec += 1000000;
   1419 	tvp->tv_sec -= 1;
   1420     }
   1421     if (tvp->tv_sec < 0)
   1422 	tvp->tv_sec = tvp->tv_usec = 0;
   1423 
   1424     return tvp;
   1425 }
   1426 
   1427 
   1428 /*
   1429  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
   1430  * We assume that sig is currently blocked.
   1431  */
   1432 static void
   1433 kill_my_pg(sig)
   1434     int sig;
   1435 {
   1436     struct sigaction act, oldact;
   1437     struct subprocess *chp;
   1438 
   1439     if (!detached) {
   1440 	/*
   1441 	 * There might be other things in our process group that we
   1442 	 * didn't start that would get hit if we did a kill(0), so
   1443 	 * just send the signal individually to our children.
   1444 	 */
   1445 	for (chp = children; chp != NULL; chp = chp->next)
   1446 	    if (chp->killable)
   1447 		kill(chp->pid, sig);
   1448 	return;
   1449     }
   1450 
   1451     /* We've done a setsid(), so we can just use a kill(0) */
   1452     sigemptyset(&act.sa_mask);		/* unnecessary in fact */
   1453     act.sa_handler = SIG_IGN;
   1454     act.sa_flags = 0;
   1455     kill(0, sig);
   1456     /*
   1457      * The kill() above made the signal pending for us, as well as
   1458      * the rest of our process group, but we don't want it delivered
   1459      * to us.  It is blocked at the moment.  Setting it to be ignored
   1460      * will cause the pending signal to be discarded.  If we did the
   1461      * kill() after setting the signal to be ignored, it is unspecified
   1462      * (by POSIX) whether the signal is immediately discarded or left
   1463      * pending, and in fact Linux would leave it pending, and so it
   1464      * would be delivered after the current signal handler exits,
   1465      * leading to an infinite loop.
   1466      */
   1467     sigaction(sig, &act, &oldact);
   1468     sigaction(sig, &oldact, NULL);
   1469 }
   1470 
   1471 
   1472 /*
   1473  * hup - Catch SIGHUP signal.
   1474  *
   1475  * Indicates that the physical layer has been disconnected.
   1476  * We don't rely on this indication; if the user has sent this
   1477  * signal, we just take the link down.
   1478  */
   1479 static void
   1480 hup(sig)
   1481     int sig;
   1482 {
   1483     /* can't log a message here, it can deadlock */
   1484     got_sighup = 1;
   1485     if (conn_running)
   1486 	/* Send the signal to the [dis]connector process(es) also */
   1487 	kill_my_pg(sig);
   1488     notify(sigreceived, sig);
   1489     if (waiting)
   1490 	siglongjmp(sigjmp, 1);
   1491 }
   1492 
   1493 
   1494 /*
   1495  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
   1496  *
   1497  * Indicates that we should initiate a graceful disconnect and exit.
   1498  */
   1499 /*ARGSUSED*/
   1500 static void
   1501 term(sig)
   1502     int sig;
   1503 {
   1504     /* can't log a message here, it can deadlock */
   1505     got_sigterm = sig;
   1506     if (conn_running)
   1507 	/* Send the signal to the [dis]connector process(es) also */
   1508 	kill_my_pg(sig);
   1509     notify(sigreceived, sig);
   1510     if (waiting)
   1511 	siglongjmp(sigjmp, 1);
   1512 }
   1513 
   1514 
   1515 /*
   1516  * chld - Catch SIGCHLD signal.
   1517  * Sets a flag so we will call reap_kids in the mainline.
   1518  */
   1519 static void
   1520 chld(sig)
   1521     int sig;
   1522 {
   1523     got_sigchld = 1;
   1524     if (waiting)
   1525 	siglongjmp(sigjmp, 1);
   1526 }
   1527 
   1528 
   1529 /*
   1530  * toggle_debug - Catch SIGUSR1 signal.
   1531  *
   1532  * Toggle debug flag.
   1533  */
   1534 /*ARGSUSED*/
   1535 static void
   1536 toggle_debug(sig)
   1537     int sig;
   1538 {
   1539     debug = !debug;
   1540     if (debug) {
   1541 	setlogmask(LOG_UPTO(LOG_DEBUG));
   1542     } else {
   1543 	setlogmask(LOG_UPTO(LOG_WARNING));
   1544     }
   1545 }
   1546 
   1547 
   1548 /*
   1549  * open_ccp - Catch SIGUSR2 signal.
   1550  *
   1551  * Try to (re)negotiate compression.
   1552  */
   1553 /*ARGSUSED*/
   1554 static void
   1555 open_ccp(sig)
   1556     int sig;
   1557 {
   1558     got_sigusr2 = 1;
   1559     if (waiting)
   1560 	siglongjmp(sigjmp, 1);
   1561 }
   1562 
   1563 
   1564 /*
   1565  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
   1566  */
   1567 static void
   1568 bad_signal(sig)
   1569     int sig;
   1570 {
   1571     static int crashed = 0;
   1572 
   1573     if (crashed)
   1574 	_exit(127);
   1575     crashed = 1;
   1576     error("Fatal signal %d", sig);
   1577     if (conn_running)
   1578 	kill_my_pg(SIGTERM);
   1579     notify(sigreceived, sig);
   1580     die(127);
   1581 }
   1582 
   1583 /*
   1584  * safe_fork - Create a child process.  The child closes all the
   1585  * file descriptors that we don't want to leak to a script.
   1586  * The parent waits for the child to do this before returning.
   1587  * This also arranges for the specified fds to be dup'd to
   1588  * fds 0, 1, 2 in the child.
   1589  */
   1590 pid_t
   1591 safe_fork(int infd, int outfd, int errfd)
   1592 {
   1593 	pid_t pid;
   1594 	int fd, pipefd[2];
   1595 	char buf[1];
   1596 
   1597 	/* make sure fds 0, 1, 2 are occupied (probably not necessary) */
   1598 	while ((fd = dup(fd_devnull)) >= 0) {
   1599 		if (fd > 2) {
   1600 			close(fd);
   1601 			break;
   1602 		}
   1603 	}
   1604 
   1605 	if (pipe(pipefd) == -1)
   1606 		pipefd[0] = pipefd[1] = -1;
   1607 	pid = fork();
   1608 	if (pid < 0) {
   1609 		error("fork failed: %m");
   1610 		return -1;
   1611 	}
   1612 	if (pid > 0) {
   1613 		/* parent */
   1614 		close(pipefd[1]);
   1615 		/* this read() blocks until the close(pipefd[1]) below */
   1616 		complete_read(pipefd[0], buf, 1);
   1617 		close(pipefd[0]);
   1618 		return pid;
   1619 	}
   1620 
   1621 	/* Executing in the child */
   1622 	sys_close();
   1623 #ifdef USE_TDB
   1624 	tdb_close(pppdb);
   1625 #endif
   1626 
   1627 	/* make sure infd, outfd and errfd won't get tromped on below */
   1628 	if (infd == 1 || infd == 2)
   1629 		infd = dup(infd);
   1630 	if (outfd == 0 || outfd == 2)
   1631 		outfd = dup(outfd);
   1632 	if (errfd == 0 || errfd == 1)
   1633 		errfd = dup(errfd);
   1634 
   1635 	closelog();
   1636 
   1637 	/* dup the in, out, err fds to 0, 1, 2 */
   1638 	if (infd != 0)
   1639 		dup2(infd, 0);
   1640 	if (outfd != 1)
   1641 		dup2(outfd, 1);
   1642 	if (errfd != 2)
   1643 		dup2(errfd, 2);
   1644 
   1645 	if (log_to_fd > 2)
   1646 		close(log_to_fd);
   1647 	if (the_channel->close)
   1648 		(*the_channel->close)();
   1649 	else
   1650 		close(devfd);	/* some plugins don't have a close function */
   1651 	close(fd_ppp);
   1652 	close(fd_devnull);
   1653 	if (infd != 0)
   1654 		close(infd);
   1655 	if (outfd != 1)
   1656 		close(outfd);
   1657 	if (errfd != 2)
   1658 		close(errfd);
   1659 
   1660 	notify(fork_notifier, 0);
   1661 	close(pipefd[0]);
   1662 	/* this close unblocks the read() call above in the parent */
   1663 	close(pipefd[1]);
   1664 
   1665 	return 0;
   1666 }
   1667 
   1668 static bool
   1669 add_script_env(pos, newstring)
   1670     int pos;
   1671     char *newstring;
   1672 {
   1673     if (pos + 1 >= s_env_nalloc) {
   1674 	int new_n = pos + 17;
   1675 	char **newenv = realloc(script_env, new_n * sizeof(char *));
   1676 	if (newenv == NULL) {
   1677 	    free(newstring - 1);
   1678 	    return 0;
   1679 	}
   1680 	script_env = newenv;
   1681 	s_env_nalloc = new_n;
   1682     }
   1683     script_env[pos] = newstring;
   1684     script_env[pos + 1] = NULL;
   1685     return 1;
   1686 }
   1687 
   1688 static void
   1689 remove_script_env(pos)
   1690     int pos;
   1691 {
   1692     free(script_env[pos] - 1);
   1693     while ((script_env[pos] = script_env[pos + 1]) != NULL)
   1694 	pos++;
   1695 }
   1696 
   1697 /*
   1698  * update_system_environment - process the list of set/unset options
   1699  * and update the system environment.
   1700  */
   1701 static void
   1702 update_system_environment()
   1703 {
   1704     struct userenv *uep;
   1705 
   1706     for (uep = userenv_list; uep != NULL; uep = uep->ue_next) {
   1707 	if (uep->ue_isset)
   1708 	    setenv(uep->ue_name, uep->ue_value, 1);
   1709 	else
   1710 	    unsetenv(uep->ue_name);
   1711     }
   1712 }
   1713 
   1714 /*
   1715  * device_script - run a program to talk to the specified fds
   1716  * (e.g. to run the connector or disconnector script).
   1717  * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
   1718  */
   1719 int
   1720 device_script(program, in, out, dont_wait)
   1721     char *program;
   1722     int in, out;
   1723     int dont_wait;
   1724 {
   1725     int pid;
   1726     int status = -1;
   1727     int errfd;
   1728 
   1729     if (log_to_fd >= 0)
   1730 	errfd = log_to_fd;
   1731     else
   1732 	errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
   1733 
   1734     ++conn_running;
   1735     pid = safe_fork(in, out, errfd);
   1736 
   1737     if (pid != 0 && log_to_fd < 0)
   1738 	close(errfd);
   1739 
   1740     if (pid < 0) {
   1741 	--conn_running;
   1742 	error("Failed to create child process: %m");
   1743 	return -1;
   1744     }
   1745 
   1746     if (pid != 0) {
   1747 	record_child(pid, program, NULL, NULL, 1);
   1748 	status = 0;
   1749 	if (!dont_wait) {
   1750 	    while (waitpid(pid, &status, 0) < 0) {
   1751 		if (errno == EINTR)
   1752 		    continue;
   1753 		fatal("error waiting for (dis)connection process: %m");
   1754 	    }
   1755 	    forget_child(pid, status);
   1756 	    --conn_running;
   1757 	}
   1758 	return (status == 0 ? 0 : -1);
   1759     }
   1760 
   1761     /* here we are executing in the child */
   1762 
   1763     setgid(getgid());
   1764     setuid(uid);
   1765     if (getuid() != uid) {
   1766 	fprintf(stderr, "pppd: setuid failed\n");
   1767 	exit(1);
   1768     }
   1769     update_system_environment();
   1770 #if defined(__ANDROID__)
   1771     execl("/system/bin/sh", "sh", "-c", program, NULL);
   1772 #else
   1773     execl("/bin/sh", "sh", "-c", program, (char *)0);
   1774 #endif
   1775     perror("pppd: could not exec /bin/sh");
   1776     _exit(99);
   1777     /* NOTREACHED */
   1778 }
   1779 
   1780 
   1781 /*
   1782  * update_script_environment - process the list of set/unset options
   1783  * and update the script environment.  Note that we intentionally do
   1784  * not update the TDB.  These changes are layered on top right before
   1785  * exec.  It is not possible to use script_setenv() or
   1786  * script_unsetenv() safely after this routine is run.
   1787  */
   1788 static void
   1789 update_script_environment()
   1790 {
   1791     struct userenv *uep;
   1792 
   1793     for (uep = userenv_list; uep != NULL; uep = uep->ue_next) {
   1794 	int i;
   1795 	char *p, *newstring;
   1796 	int nlen = strlen(uep->ue_name);
   1797 
   1798 	for (i = 0; (p = script_env[i]) != NULL; i++) {
   1799 	    if (strncmp(p, uep->ue_name, nlen) == 0 && p[nlen] == '=')
   1800 		break;
   1801 	}
   1802 	if (uep->ue_isset) {
   1803 	    nlen += strlen(uep->ue_value) + 2;
   1804 	    newstring = malloc(nlen + 1);
   1805 	    if (newstring == NULL)
   1806 		continue;
   1807 	    *newstring++ = 0;
   1808 	    slprintf(newstring, nlen, "%s=%s", uep->ue_name, uep->ue_value);
   1809 	    if (p != NULL)
   1810 		script_env[i] = newstring;
   1811 	    else
   1812 		add_script_env(i, newstring);
   1813 	} else {
   1814 	    remove_script_env(i);
   1815 	}
   1816     }
   1817 }
   1818 
   1819 /*
   1820  * run_program - execute a program with given arguments,
   1821  * but don't wait for it unless wait is non-zero.
   1822  * If the program can't be executed, logs an error unless
   1823  * must_exist is 0 and the program file doesn't exist.
   1824  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
   1825  * or isn't an executable plain file, or the process ID of the child.
   1826  * If done != NULL, (*done)(arg) will be called later (within
   1827  * reap_kids) iff the return value is > 0.
   1828  */
   1829 pid_t
   1830 run_program(prog, args, must_exist, done, arg, wait)
   1831     char *prog;
   1832     char **args;
   1833     int must_exist;
   1834     void (*done) __P((void *));
   1835     void *arg;
   1836     int wait;
   1837 {
   1838     int pid, status;
   1839     struct stat sbuf;
   1840 
   1841 #if defined(__ANDROID__)
   1842     /* Originally linkname is used to create named pid files, which is
   1843     * meaningless to android. Here we use it as a suffix of program names,
   1844     * so different users can run their own program by specifying it. For
   1845     * example, "/etc/ppp/ip-up-vpn" will be executed when IPCP is up and
   1846     * linkname is "vpn". Note that "/" is not allowed for security reasons. */
   1847     char file[MAXPATHLEN];
   1848 
   1849     if (linkname[0] && !strchr(linkname, '/')) {
   1850         snprintf(file, MAXPATHLEN, "%s-%s", prog, linkname);
   1851         file[MAXPATHLEN - 1] = '\0';
   1852         prog = file;
   1853     }
   1854 #endif
   1855 
   1856     /*
   1857      * First check if the file exists and is executable.
   1858      * We don't use access() because that would use the
   1859      * real user-id, which might not be root, and the script
   1860      * might be accessible only to root.
   1861      */
   1862     errno = EINVAL;
   1863     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
   1864 	|| (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
   1865 	if (must_exist || errno != ENOENT)
   1866 	    warn("Can't execute %s: %m", prog);
   1867 	return 0;
   1868     }
   1869 
   1870     pid = safe_fork(fd_devnull, fd_devnull, fd_devnull);
   1871     if (pid == -1) {
   1872 	error("Failed to create child process for %s: %m", prog);
   1873 	return -1;
   1874     }
   1875     if (pid != 0) {
   1876 	if (debug)
   1877 	    dbglog("Script %s started (pid %d)", prog, pid);
   1878 	record_child(pid, prog, done, arg, 0);
   1879 	if (wait) {
   1880 	    while (waitpid(pid, &status, 0) < 0) {
   1881 		if (errno == EINTR)
   1882 		    continue;
   1883 		fatal("error waiting for script %s: %m", prog);
   1884 	    }
   1885 	    forget_child(pid, status);
   1886 	}
   1887 	return pid;
   1888     }
   1889 
   1890     /* Leave the current location */
   1891     (void) setsid();	/* No controlling tty. */
   1892     (void) umask (S_IRWXG|S_IRWXO);
   1893     (void) chdir ("/");	/* no current directory. */
   1894     setuid(0);		/* set real UID = root */
   1895     setgid(getegid());
   1896 
   1897 #ifdef BSD
   1898     /* Force the priority back to zero if pppd is running higher. */
   1899     if (setpriority (PRIO_PROCESS, 0, 0) < 0)
   1900 	warn("can't reset priority to 0: %m");
   1901 #endif
   1902 
   1903     /* run the program */
   1904     update_script_environment();
   1905     execve(prog, args, script_env);
   1906     if (must_exist || errno != ENOENT) {
   1907 	/* have to reopen the log, there's nowhere else
   1908 	   for the message to go. */
   1909 	reopen_log();
   1910 	syslog(LOG_ERR, "Can't execute %s: %m", prog);
   1911 	closelog();
   1912     }
   1913     _exit(99);
   1914 }
   1915 
   1916 
   1917 /*
   1918  * record_child - add a child process to the list for reap_kids
   1919  * to use.
   1920  */
   1921 void
   1922 record_child(pid, prog, done, arg, killable)
   1923     int pid;
   1924     char *prog;
   1925     void (*done) __P((void *));
   1926     void *arg;
   1927     int killable;
   1928 {
   1929     struct subprocess *chp;
   1930 
   1931     ++n_children;
   1932 
   1933     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
   1934     if (chp == NULL) {
   1935 	warn("losing track of %s process", prog);
   1936     } else {
   1937 	chp->pid = pid;
   1938 	chp->prog = prog;
   1939 	chp->done = done;
   1940 	chp->arg = arg;
   1941 	chp->next = children;
   1942 	chp->killable = killable;
   1943 	children = chp;
   1944     }
   1945 }
   1946 
   1947 /*
   1948  * childwait_end - we got fed up waiting for the child processes to
   1949  * exit, send them all a SIGTERM.
   1950  */
   1951 static void
   1952 childwait_end(arg)
   1953     void *arg;
   1954 {
   1955     struct subprocess *chp;
   1956 
   1957     for (chp = children; chp != NULL; chp = chp->next) {
   1958 	if (debug)
   1959 	    dbglog("sending SIGTERM to process %d", chp->pid);
   1960 	kill(chp->pid, SIGTERM);
   1961     }
   1962     childwait_done = 1;
   1963 }
   1964 
   1965 /*
   1966  * forget_child - clean up after a dead child
   1967  */
   1968 static void
   1969 forget_child(pid, status)
   1970     int pid, status;
   1971 {
   1972     struct subprocess *chp, **prevp;
   1973 
   1974     for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
   1975         if (chp->pid == pid) {
   1976 	    --n_children;
   1977 	    *prevp = chp->next;
   1978 	    break;
   1979 	}
   1980     }
   1981     if (WIFSIGNALED(status)) {
   1982         warn("Child process %s (pid %d) terminated with signal %d",
   1983 	     (chp? chp->prog: "??"), pid, WTERMSIG(status));
   1984     } else if (debug)
   1985         dbglog("Script %s finished (pid %d), status = 0x%x",
   1986 	       (chp? chp->prog: "??"), pid,
   1987 	       WIFEXITED(status) ? WEXITSTATUS(status) : status);
   1988     if (chp && chp->done)
   1989         (*chp->done)(chp->arg);
   1990     if (chp)
   1991         free(chp);
   1992 }
   1993 
   1994 /*
   1995  * reap_kids - get status from any dead child processes,
   1996  * and log a message for abnormal terminations.
   1997  */
   1998 static int
   1999 reap_kids()
   2000 {
   2001     int pid, status;
   2002 
   2003     if (n_children == 0)
   2004 	return 0;
   2005     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
   2006         forget_child(pid, status);
   2007     }
   2008     if (pid == -1) {
   2009 	if (errno == ECHILD)
   2010 	    return -1;
   2011 	if (errno != EINTR)
   2012 	    error("Error waiting for child process: %m");
   2013     }
   2014     return 0;
   2015 }
   2016 
   2017 /*
   2018  * add_notifier - add a new function to be called when something happens.
   2019  */
   2020 void
   2021 add_notifier(notif, func, arg)
   2022     struct notifier **notif;
   2023     notify_func func;
   2024     void *arg;
   2025 {
   2026     struct notifier *np;
   2027 
   2028     np = malloc(sizeof(struct notifier));
   2029     if (np == 0)
   2030 	novm("notifier struct");
   2031     np->next = *notif;
   2032     np->func = func;
   2033     np->arg = arg;
   2034     *notif = np;
   2035 }
   2036 
   2037 /*
   2038  * remove_notifier - remove a function from the list of things to
   2039  * be called when something happens.
   2040  */
   2041 void
   2042 remove_notifier(notif, func, arg)
   2043     struct notifier **notif;
   2044     notify_func func;
   2045     void *arg;
   2046 {
   2047     struct notifier *np;
   2048 
   2049     for (; (np = *notif) != 0; notif = &np->next) {
   2050 	if (np->func == func && np->arg == arg) {
   2051 	    *notif = np->next;
   2052 	    free(np);
   2053 	    break;
   2054 	}
   2055     }
   2056 }
   2057 
   2058 /*
   2059  * notify - call a set of functions registered with add_notifier.
   2060  */
   2061 void
   2062 notify(notif, val)
   2063     struct notifier *notif;
   2064     int val;
   2065 {
   2066     struct notifier *np;
   2067 
   2068     while ((np = notif) != 0) {
   2069 	notif = np->next;
   2070 	(*np->func)(np->arg, val);
   2071     }
   2072 }
   2073 
   2074 /*
   2075  * novm - log an error message saying we ran out of memory, and die.
   2076  */
   2077 void
   2078 novm(msg)
   2079     char *msg;
   2080 {
   2081     fatal("Virtual memory exhausted allocating %s\n", msg);
   2082 }
   2083 
   2084 /*
   2085  * script_setenv - set an environment variable value to be used
   2086  * for scripts that we run (e.g. ip-up, auth-up, etc.)
   2087  */
   2088 void
   2089 script_setenv(var, value, iskey)
   2090     char *var, *value;
   2091     int iskey;
   2092 {
   2093     size_t varl = strlen(var);
   2094     size_t vl = varl + strlen(value) + 2;
   2095     int i;
   2096     char *p, *newstring;
   2097 
   2098     newstring = (char *) malloc(vl+1);
   2099     if (newstring == 0)
   2100 	return;
   2101     *newstring++ = iskey;
   2102     slprintf(newstring, vl, "%s=%s", var, value);
   2103 
   2104     /* check if this variable is already set */
   2105     if (script_env != 0) {
   2106 	for (i = 0; (p = script_env[i]) != 0; ++i) {
   2107 	    if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
   2108 #ifdef USE_TDB
   2109 		if (p[-1] && pppdb != NULL)
   2110 		    delete_db_key(p);
   2111 #endif
   2112 		free(p-1);
   2113 		script_env[i] = newstring;
   2114 #ifdef USE_TDB
   2115 		if (pppdb != NULL) {
   2116 		    if (iskey)
   2117 			add_db_key(newstring);
   2118 		    update_db_entry();
   2119 		}
   2120 #endif
   2121 		return;
   2122 	    }
   2123 	}
   2124     } else {
   2125 	/* no space allocated for script env. ptrs. yet */
   2126 	i = 0;
   2127 	script_env = malloc(16 * sizeof(char *));
   2128 	if (script_env == 0) {
   2129 	    free(newstring - 1);
   2130 	    return;
   2131 	}
   2132 	s_env_nalloc = 16;
   2133     }
   2134 
   2135     if (!add_script_env(i, newstring))
   2136 	return;
   2137 
   2138 #ifdef USE_TDB
   2139     if (pppdb != NULL) {
   2140 	if (iskey)
   2141 	    add_db_key(newstring);
   2142 	update_db_entry();
   2143     }
   2144 #endif
   2145 }
   2146 
   2147 /*
   2148  * script_unsetenv - remove a variable from the environment
   2149  * for scripts.
   2150  */
   2151 void
   2152 script_unsetenv(var)
   2153     char *var;
   2154 {
   2155     int vl = strlen(var);
   2156     int i;
   2157     char *p;
   2158 
   2159     if (script_env == 0)
   2160 	return;
   2161     for (i = 0; (p = script_env[i]) != 0; ++i) {
   2162 	if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
   2163 #ifdef USE_TDB
   2164 	    if (p[-1] && pppdb != NULL)
   2165 		delete_db_key(p);
   2166 #endif
   2167 	    remove_script_env(i);
   2168 	    break;
   2169 	}
   2170     }
   2171 #ifdef USE_TDB
   2172     if (pppdb != NULL)
   2173 	update_db_entry();
   2174 #endif
   2175 }
   2176 
   2177 /*
   2178  * Any arbitrary string used as a key for locking the database.
   2179  * It doesn't matter what it is as long as all pppds use the same string.
   2180  */
   2181 #define PPPD_LOCK_KEY	"pppd lock"
   2182 
   2183 /*
   2184  * lock_db - get an exclusive lock on the TDB database.
   2185  * Used to ensure atomicity of various lookup/modify operations.
   2186  */
   2187 void lock_db()
   2188 {
   2189 #ifdef USE_TDB
   2190 	TDB_DATA key;
   2191 
   2192 	key.dptr = PPPD_LOCK_KEY;
   2193 	key.dsize = strlen(key.dptr);
   2194 	tdb_chainlock(pppdb, key);
   2195 #endif
   2196 }
   2197 
   2198 /*
   2199  * unlock_db - remove the exclusive lock obtained by lock_db.
   2200  */
   2201 void unlock_db()
   2202 {
   2203 #ifdef USE_TDB
   2204 	TDB_DATA key;
   2205 
   2206 	key.dptr = PPPD_LOCK_KEY;
   2207 	key.dsize = strlen(key.dptr);
   2208 	tdb_chainunlock(pppdb, key);
   2209 #endif
   2210 }
   2211 
   2212 #ifdef USE_TDB
   2213 /*
   2214  * update_db_entry - update our entry in the database.
   2215  */
   2216 static void
   2217 update_db_entry()
   2218 {
   2219     TDB_DATA key, dbuf;
   2220     int vlen, i;
   2221     char *p, *q, *vbuf;
   2222 
   2223     if (script_env == NULL)
   2224 	return;
   2225     vlen = 0;
   2226     for (i = 0; (p = script_env[i]) != 0; ++i)
   2227 	vlen += strlen(p) + 1;
   2228     vbuf = malloc(vlen + 1);
   2229     if (vbuf == 0)
   2230 	novm("database entry");
   2231     q = vbuf;
   2232     for (i = 0; (p = script_env[i]) != 0; ++i)
   2233 	q += slprintf(q, vbuf + vlen - q, "%s;", p);
   2234 
   2235     key.dptr = db_key;
   2236     key.dsize = strlen(db_key);
   2237     dbuf.dptr = vbuf;
   2238     dbuf.dsize = vlen;
   2239     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
   2240 	error("tdb_store failed: %s", tdb_errorstr(pppdb));
   2241 
   2242     if (vbuf)
   2243         free(vbuf);
   2244 
   2245 }
   2246 
   2247 /*
   2248  * add_db_key - add a key that we can use to look up our database entry.
   2249  */
   2250 static void
   2251 add_db_key(str)
   2252     const char *str;
   2253 {
   2254     TDB_DATA key, dbuf;
   2255 
   2256     key.dptr = (char *) str;
   2257     key.dsize = strlen(str);
   2258     dbuf.dptr = db_key;
   2259     dbuf.dsize = strlen(db_key);
   2260     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
   2261 	error("tdb_store key failed: %s", tdb_errorstr(pppdb));
   2262 }
   2263 
   2264 /*
   2265  * delete_db_key - delete a key for looking up our database entry.
   2266  */
   2267 static void
   2268 delete_db_key(str)
   2269     const char *str;
   2270 {
   2271     TDB_DATA key;
   2272 
   2273     key.dptr = (char *) str;
   2274     key.dsize = strlen(str);
   2275     tdb_delete(pppdb, key);
   2276 }
   2277 
   2278 /*
   2279  * cleanup_db - delete all the entries we put in the database.
   2280  */
   2281 static void
   2282 cleanup_db()
   2283 {
   2284     TDB_DATA key;
   2285     int i;
   2286     char *p;
   2287 
   2288     key.dptr = db_key;
   2289     key.dsize = strlen(db_key);
   2290     tdb_delete(pppdb, key);
   2291     for (i = 0; (p = script_env[i]) != 0; ++i)
   2292 	if (p[-1])
   2293 	    delete_db_key(p);
   2294 }
   2295 #endif /* USE_TDB */
   2296