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