• 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.148 2004/11/13 12:05:48 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 #include <cutils/properties.h>
94 
95 #include "pppd.h"
96 #include "magic.h"
97 #include "fsm.h"
98 #include "lcp.h"
99 #include "ipcp.h"
100 #ifdef INET6
101 #include "ipv6cp.h"
102 #endif
103 #include "upap.h"
104 #include "chap-new.h"
105 #include "eap.h"
106 #include "ccp.h"
107 #include "ecp.h"
108 #include "pathnames.h"
109 
110 #ifdef USE_TDB
111 #include "tdb.h"
112 #endif
113 
114 #ifdef CBCP_SUPPORT
115 #include "cbcp.h"
116 #endif
117 
118 #ifdef IPX_CHANGE
119 #include "ipxcp.h"
120 #endif /* IPX_CHANGE */
121 #ifdef AT_CHANGE
122 #include "atcp.h"
123 #endif
124 
125 static const char rcsid[] = RCSID;
126 
127 /* interface vars */
128 char ifname[32];		/* Interface name */
129 int ifunit;			/* Interface unit number */
130 
131 struct channel *the_channel;
132 
133 char *progname;			/* Name of this program */
134 char hostname[MAXNAMELEN];	/* Our hostname */
135 static char pidfilename[MAXPATHLEN];	/* name of pid file */
136 static char linkpidfile[MAXPATHLEN];	/* name of linkname pid file */
137 char ppp_devnam[MAXPATHLEN];	/* name of PPP tty (maybe ttypx) */
138 uid_t uid;			/* Our real user-id */
139 struct notifier *pidchange = NULL;
140 struct notifier *phasechange = NULL;
141 struct notifier *exitnotify = NULL;
142 struct notifier *sigreceived = NULL;
143 struct notifier *fork_notifier = NULL;
144 
145 int hungup;			/* terminal has been hung up */
146 int privileged;			/* we're running as real uid root */
147 int need_holdoff;		/* need holdoff period before restarting */
148 int detached;			/* have detached from terminal */
149 volatile int status;		/* exit status for pppd */
150 int unsuccess;			/* # unsuccessful connection attempts */
151 int do_callback;		/* != 0 if we should do callback next */
152 int doing_callback;		/* != 0 if we are doing callback */
153 int ppp_session_number;		/* Session number, for channels with such a
154 				   concept (eg PPPoE) */
155 int childwait_done;		/* have timed out waiting for children */
156 
157 #ifdef USE_TDB
158 TDB_CONTEXT *pppdb;		/* database for storing status etc. */
159 #endif
160 
161 char db_key[32];
162 
163 int (*holdoff_hook) __P((void)) = NULL;
164 int (*new_phase_hook) __P((int)) = NULL;
165 void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
166 void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
167 
168 static int conn_running;	/* we have a [dis]connector running */
169 static int fd_loop;		/* fd for getting demand-dial packets */
170 
171 int fd_devnull;			/* fd for /dev/null */
172 int devfd = -1;			/* fd of underlying device */
173 int fd_ppp = -1;		/* fd for talking PPP */
174 int phase;			/* where the link is at */
175 int kill_link;
176 int asked_to_quit;
177 int open_ccp_flag;
178 int listen_time;
179 int got_sigusr2;
180 int got_sigterm;
181 int got_sighup;
182 
183 static sigset_t signals_handled;
184 static int waiting;
185 static sigjmp_buf sigjmp;
186 
187 char **script_env;		/* Env. variable values for scripts */
188 int s_env_nalloc;		/* # words avail at script_env */
189 
190 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
191 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
192 
193 static int n_children;		/* # child processes still running */
194 static int got_sigchld;		/* set if we have received a SIGCHLD */
195 
196 int privopen;			/* don't lock, open device as root */
197 
198 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
199 
200 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
201 int ngroups;			/* How many groups valid in groups */
202 
203 static struct timeval start_time;	/* Time when link was started. */
204 
205 static struct pppd_stats old_link_stats;
206 struct pppd_stats link_stats;
207 unsigned link_connect_time;
208 int link_stats_valid;
209 
210 int error_count;
211 
212 bool bundle_eof;
213 bool bundle_terminating;
214 
215 int sent_since_received = 0;
216 int sent_total = 0;
217 int received_total = 0;
218 
219 /*
220  * We maintain a list of child process pids and
221  * functions to call when they exit.
222  */
223 struct subprocess {
224     pid_t	pid;
225     char	*prog;
226     void	(*done) __P((void *));
227     void	*arg;
228     struct subprocess *next;
229 };
230 
231 static struct subprocess *children;
232 
233 /* Prototypes for procedures local to this file. */
234 
235 static void setup_signals __P((void));
236 static void create_pidfile __P((int pid));
237 static void create_linkpidfile __P((int pid));
238 static void cleanup __P((void));
239 static void get_input __P((void));
240 static void calltimeout __P((void));
241 static struct timeval *timeleft __P((struct timeval *));
242 static void kill_my_pg __P((int));
243 static void hup __P((int));
244 static void term __P((int));
245 static void chld __P((int));
246 static void toggle_debug __P((int));
247 static void open_ccp __P((int));
248 static void bad_signal __P((int));
249 static void holdoff_end __P((void *));
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
main(argc,argv)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 #ifdef ANDROID_CHANGES
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 #ifdef ANDROID_CHANGES
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 #ifndef ANDROID_CHANGES
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 	while (phase != PHASE_DEAD) {
584 	    handle_events();
585 	    get_input();
586 	    if (kill_link)
587 		lcp_close(0, "User request");
588 	    if (asked_to_quit) {
589 		bundle_terminating = 1;
590 		if (phase == PHASE_MASTER)
591 		    mp_bundle_terminated();
592 	    }
593 	    if (open_ccp_flag) {
594 		if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
595 		    ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
596 		    (*ccp_protent.open)(0);
597 		}
598 	    }
599 	}
600 
601 	if (!persist || asked_to_quit || (maxfail > 0 && unsuccess >= maxfail))
602 	    break;
603 
604 	if (demand)
605 	    demand_discard();
606 	t = need_holdoff? holdoff: 0;
607 	if (holdoff_hook)
608 	    t = (*holdoff_hook)();
609 	if (t > 0) {
610 	    new_phase(PHASE_HOLDOFF);
611 	    TIMEOUT(holdoff_end, NULL, t);
612 	    do {
613 		handle_events();
614 		if (kill_link)
615 		    new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
616 	    } while (phase == PHASE_HOLDOFF);
617 	    if (!persist)
618 		break;
619 	}
620     }
621 
622     /* Wait for scripts to finish */
623     reap_kids();
624     if (n_children > 0) {
625 	if (child_wait > 0)
626 	    TIMEOUT(childwait_end, NULL, child_wait);
627 	if (debug) {
628 	    struct subprocess *chp;
629 	    dbglog("Waiting for %d child processes...", n_children);
630 	    for (chp = children; chp != NULL; chp = chp->next)
631 		dbglog("  script %s, pid %d", chp->prog, chp->pid);
632 	}
633 	while (n_children > 0 && !childwait_done) {
634 	    handle_events();
635 	    if (kill_link && !childwait_done)
636 		childwait_end(NULL);
637 	}
638     }
639 
640     die(status);
641     return 0;
642 }
643 
644 /*
645  * handle_events - wait for something to happen and respond to it.
646  */
647 static void
handle_events()648 handle_events()
649 {
650     struct timeval timo;
651 
652     kill_link = open_ccp_flag = 0;
653     if (sigsetjmp(sigjmp, 1) == 0) {
654 	sigprocmask(SIG_BLOCK, &signals_handled, NULL);
655 	if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
656 	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
657 	} else {
658 	    waiting = 1;
659 	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
660 	    wait_input(timeleft(&timo));
661 	}
662     }
663     waiting = 0;
664     calltimeout();
665     if (got_sighup) {
666 	info("Hangup (SIGHUP)");
667 	kill_link = 1;
668 	got_sighup = 0;
669 	if (status != EXIT_HANGUP)
670 	    status = EXIT_USER_REQUEST;
671     }
672     if (got_sigterm) {
673 	info("Terminating on signal %d", got_sigterm);
674 	kill_link = 1;
675 	asked_to_quit = 1;
676 	persist = 0;
677 	status = EXIT_USER_REQUEST;
678 	got_sigterm = 0;
679     }
680     if (got_sigchld) {
681 	got_sigchld = 0;
682 	reap_kids();	/* Don't leave dead kids lying around */
683     }
684     if (got_sigusr2) {
685 	open_ccp_flag = 1;
686 	got_sigusr2 = 0;
687     }
688 }
689 
690 /*
691  * setup_signals - initialize signal handling.
692  */
693 static void
setup_signals()694 setup_signals()
695 {
696     struct sigaction sa;
697 
698     /*
699      * Compute mask of all interesting signals and install signal handlers
700      * for each.  Only one signal handler may be active at a time.  Therefore,
701      * all other signals should be masked when any handler is executing.
702      */
703     sigemptyset(&signals_handled);
704     sigaddset(&signals_handled, SIGHUP);
705     sigaddset(&signals_handled, SIGINT);
706     sigaddset(&signals_handled, SIGTERM);
707     sigaddset(&signals_handled, SIGCHLD);
708     sigaddset(&signals_handled, SIGUSR2);
709 
710 #define SIGNAL(s, handler)	do { \
711 	sa.sa_handler = handler; \
712 	if (sigaction(s, &sa, NULL) < 0) \
713 	    fatal("Couldn't establish signal handler (%d): %m", s); \
714     } while (0)
715 
716     sa.sa_mask = signals_handled;
717     sa.sa_flags = 0;
718     SIGNAL(SIGHUP, hup);		/* Hangup */
719     SIGNAL(SIGINT, term);		/* Interrupt */
720     SIGNAL(SIGTERM, term);		/* Terminate */
721     SIGNAL(SIGCHLD, chld);
722 
723     SIGNAL(SIGUSR1, toggle_debug);	/* Toggle debug flag */
724     SIGNAL(SIGUSR2, open_ccp);		/* Reopen CCP */
725 
726     /*
727      * Install a handler for other signals which would otherwise
728      * cause pppd to exit without cleaning up.
729      */
730     SIGNAL(SIGABRT, bad_signal);
731     SIGNAL(SIGALRM, bad_signal);
732     SIGNAL(SIGFPE, bad_signal);
733     SIGNAL(SIGILL, bad_signal);
734     SIGNAL(SIGPIPE, bad_signal);
735     SIGNAL(SIGQUIT, bad_signal);
736     SIGNAL(SIGSEGV, bad_signal);
737 #ifdef SIGBUS
738     SIGNAL(SIGBUS, bad_signal);
739 #endif
740 #ifdef SIGEMT
741     SIGNAL(SIGEMT, bad_signal);
742 #endif
743 #ifdef SIGPOLL
744     SIGNAL(SIGPOLL, bad_signal);
745 #endif
746 #ifdef SIGPROF
747     SIGNAL(SIGPROF, bad_signal);
748 #endif
749 #ifdef SIGSYS
750     SIGNAL(SIGSYS, bad_signal);
751 #endif
752 #ifdef SIGTRAP
753     SIGNAL(SIGTRAP, bad_signal);
754 #endif
755 #ifdef SIGVTALRM
756     SIGNAL(SIGVTALRM, bad_signal);
757 #endif
758 #ifdef SIGXCPU
759     SIGNAL(SIGXCPU, bad_signal);
760 #endif
761 #ifdef SIGXFSZ
762     SIGNAL(SIGXFSZ, bad_signal);
763 #endif
764 
765     /*
766      * Apparently we can get a SIGPIPE when we call syslog, if
767      * syslogd has died and been restarted.  Ignoring it seems
768      * be sufficient.
769      */
770     signal(SIGPIPE, SIG_IGN);
771 }
772 
773 /*
774  * set_ifunit - do things we need to do once we know which ppp
775  * unit we are using.
776  */
777 void
set_ifunit(iskey)778 set_ifunit(iskey)
779     int iskey;
780 {
781     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
782     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
783     script_setenv("IFNAME", ifname, iskey);
784     if (iskey) {
785 	create_pidfile(getpid());	/* write pid to file */
786 	create_linkpidfile(getpid());
787     }
788 }
789 
790 /*
791  * detach - detach us from the controlling terminal.
792  */
793 void
detach()794 detach()
795 {
796     int pid;
797     char numbuf[16];
798     int pipefd[2];
799 
800     if (detached)
801 	return;
802     if (pipe(pipefd) == -1)
803 	pipefd[0] = pipefd[1] = -1;
804     if ((pid = fork()) < 0) {
805 	error("Couldn't detach (fork failed: %m)");
806 	die(1);			/* or just return? */
807     }
808     if (pid != 0) {
809 	/* parent */
810 	notify(pidchange, pid);
811 	/* update pid files if they have been written already */
812 	if (pidfilename[0])
813 	    create_pidfile(pid);
814 	if (linkpidfile[0])
815 	    create_linkpidfile(pid);
816 	exit(0);		/* parent dies */
817     }
818     setsid();
819     chdir("/");
820     dup2(fd_devnull, 0);
821     dup2(fd_devnull, 1);
822     dup2(fd_devnull, 2);
823     detached = 1;
824     if (log_default)
825 	log_to_fd = -1;
826     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
827     script_setenv("PPPD_PID", numbuf, 1);
828 
829     /* wait for parent to finish updating pid & lock files and die */
830     close(pipefd[1]);
831     complete_read(pipefd[0], numbuf, 1);
832     close(pipefd[0]);
833 }
834 
835 /*
836  * reopen_log - (re)open our connection to syslog.
837  */
838 void
reopen_log()839 reopen_log()
840 {
841 #ifndef ANDROID_CHANGES
842     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
843     setlogmask(LOG_UPTO(LOG_INFO));
844 #endif
845 }
846 
847 /*
848  * Create a file containing our process ID.
849  */
850 static void
create_pidfile(pid)851 create_pidfile(pid)
852     int pid;
853 {
854 #ifndef ANDROID_CHANGES
855     FILE *pidfile;
856 
857     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
858 	     _PATH_VARRUN, ifname);
859     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
860 	fprintf(pidfile, "%d\n", pid);
861 	(void) fclose(pidfile);
862     } else {
863 	error("Failed to create pid file %s: %m", pidfilename);
864 	pidfilename[0] = 0;
865     }
866 #endif
867 }
868 
869 void
create_linkpidfile(pid)870 create_linkpidfile(pid)
871     int pid;
872 {
873 #ifndef ANDROID_CHANGES
874     FILE *pidfile;
875 
876     if (linkname[0] == 0)
877 	return;
878     script_setenv("LINKNAME", linkname, 1);
879     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
880 	     _PATH_VARRUN, linkname);
881     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
882 	fprintf(pidfile, "%d\n", pid);
883 	if (ifname[0])
884 	    fprintf(pidfile, "%s\n", ifname);
885 	(void) fclose(pidfile);
886     } else {
887 	error("Failed to create pid file %s: %m", linkpidfile);
888 	linkpidfile[0] = 0;
889     }
890 #endif
891 }
892 
893 /*
894  * remove_pidfile - remove our pid files
895  */
remove_pidfiles()896 void remove_pidfiles()
897 {
898 #ifndef ANDROID_CHANGES
899     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
900 	warn("unable to delete pid file %s: %m", pidfilename);
901     pidfilename[0] = 0;
902     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
903 	warn("unable to delete pid file %s: %m", linkpidfile);
904     linkpidfile[0] = 0;
905 #endif
906 }
907 
908 /*
909  * holdoff_end - called via a timeout when the holdoff period ends.
910  */
911 static void
holdoff_end(arg)912 holdoff_end(arg)
913     void *arg;
914 {
915     new_phase(PHASE_DORMANT);
916 }
917 
918 /* List of protocol names, to make our messages a little more informative. */
919 struct protocol_list {
920     u_short	proto;
921     const char	*name;
922 } protocol_list[] = {
923     { 0x21,	"IP" },
924     { 0x23,	"OSI Network Layer" },
925     { 0x25,	"Xerox NS IDP" },
926     { 0x27,	"DECnet Phase IV" },
927     { 0x29,	"Appletalk" },
928     { 0x2b,	"Novell IPX" },
929     { 0x2d,	"VJ compressed TCP/IP" },
930     { 0x2f,	"VJ uncompressed TCP/IP" },
931     { 0x31,	"Bridging PDU" },
932     { 0x33,	"Stream Protocol ST-II" },
933     { 0x35,	"Banyan Vines" },
934     { 0x39,	"AppleTalk EDDP" },
935     { 0x3b,	"AppleTalk SmartBuffered" },
936     { 0x3d,	"Multi-Link" },
937     { 0x3f,	"NETBIOS Framing" },
938     { 0x41,	"Cisco Systems" },
939     { 0x43,	"Ascom Timeplex" },
940     { 0x45,	"Fujitsu Link Backup and Load Balancing (LBLB)" },
941     { 0x47,	"DCA Remote Lan" },
942     { 0x49,	"Serial Data Transport Protocol (PPP-SDTP)" },
943     { 0x4b,	"SNA over 802.2" },
944     { 0x4d,	"SNA" },
945     { 0x4f,	"IP6 Header Compression" },
946     { 0x6f,	"Stampede Bridging" },
947     { 0xfb,	"single-link compression" },
948     { 0xfd,	"1st choice compression" },
949     { 0x0201,	"802.1d Hello Packets" },
950     { 0x0203,	"IBM Source Routing BPDU" },
951     { 0x0205,	"DEC LANBridge100 Spanning Tree" },
952     { 0x0231,	"Luxcom" },
953     { 0x0233,	"Sigma Network Systems" },
954     { 0x8021,	"Internet Protocol Control Protocol" },
955     { 0x8023,	"OSI Network Layer Control Protocol" },
956     { 0x8025,	"Xerox NS IDP Control Protocol" },
957     { 0x8027,	"DECnet Phase IV Control Protocol" },
958     { 0x8029,	"Appletalk Control Protocol" },
959     { 0x802b,	"Novell IPX Control Protocol" },
960     { 0x8031,	"Bridging NCP" },
961     { 0x8033,	"Stream Protocol Control Protocol" },
962     { 0x8035,	"Banyan Vines Control Protocol" },
963     { 0x803d,	"Multi-Link Control Protocol" },
964     { 0x803f,	"NETBIOS Framing Control Protocol" },
965     { 0x8041,	"Cisco Systems Control Protocol" },
966     { 0x8043,	"Ascom Timeplex" },
967     { 0x8045,	"Fujitsu LBLB Control Protocol" },
968     { 0x8047,	"DCA Remote Lan Network Control Protocol (RLNCP)" },
969     { 0x8049,	"Serial Data Control Protocol (PPP-SDCP)" },
970     { 0x804b,	"SNA over 802.2 Control Protocol" },
971     { 0x804d,	"SNA Control Protocol" },
972     { 0x804f,	"IP6 Header Compression Control Protocol" },
973     { 0x006f,	"Stampede Bridging Control Protocol" },
974     { 0x80fb,	"Single Link Compression Control Protocol" },
975     { 0x80fd,	"Compression Control Protocol" },
976     { 0xc021,	"Link Control Protocol" },
977     { 0xc023,	"Password Authentication Protocol" },
978     { 0xc025,	"Link Quality Report" },
979     { 0xc027,	"Shiva Password Authentication Protocol" },
980     { 0xc029,	"CallBack Control Protocol (CBCP)" },
981     { 0xc081,	"Container Control Protocol" },
982     { 0xc223,	"Challenge Handshake Authentication Protocol" },
983     { 0xc281,	"Proprietary Authentication Protocol" },
984     { 0,	NULL },
985 };
986 
987 /*
988  * protocol_name - find a name for a PPP protocol.
989  */
990 const char *
protocol_name(proto)991 protocol_name(proto)
992     int proto;
993 {
994     struct protocol_list *lp;
995 
996     for (lp = protocol_list; lp->proto != 0; ++lp)
997 	if (proto == lp->proto)
998 	    return lp->name;
999     return NULL;
1000 }
1001 
1002 /*
1003  * get_input - called when incoming data is available.
1004  */
1005 static void
get_input()1006 get_input()
1007 {
1008     int len, i;
1009     u_char *p;
1010     u_short protocol;
1011     struct protent *protp;
1012 
1013     p = inpacket_buf;	/* point to beginning of packet buffer */
1014 
1015     len = read_packet(inpacket_buf);
1016     if (len < 0)
1017 	return;
1018 
1019     if (len == 0) {
1020 	if (bundle_eof && multilink_master) {
1021 	    notice("Last channel has disconnected");
1022 	    mp_bundle_terminated();
1023 	    return;
1024 	}
1025 	notice("Modem hangup");
1026 	hungup = 1;
1027 	status = EXIT_HANGUP;
1028 	lcp_lowerdown(0);	/* serial link is no longer available */
1029 	link_terminated(0);
1030 	return;
1031     }
1032 
1033     if (len < PPP_HDRLEN) {
1034 	dbglog("received short packet:%.*B", len, p);
1035 	return;
1036     }
1037 
1038     dump_packet("rcvd", p, len);
1039     if (snoop_recv_hook) snoop_recv_hook(p, len);
1040 
1041     p += 2;				/* Skip address and control */
1042     GETSHORT(protocol, p);
1043     len -= PPP_HDRLEN;
1044 
1045     /*
1046      * Toss all non-LCP packets unless LCP is OPEN.
1047      */
1048     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1049 	dbglog("Discarded non-LCP packet when LCP not open");
1050 	return;
1051     }
1052 
1053     /*
1054      * Until we get past the authentication phase, toss all packets
1055      * except LCP, LQR and authentication packets.
1056      */
1057     if (phase <= PHASE_AUTHENTICATE
1058 	&& !(protocol == PPP_LCP || protocol == PPP_LQR
1059 	     || protocol == PPP_PAP || protocol == PPP_CHAP ||
1060 		protocol == PPP_EAP)) {
1061 	dbglog("discarding proto 0x%x in phase %d",
1062 		   protocol, phase);
1063 	return;
1064     }
1065 
1066     /*
1067      * Upcall the proper protocol input routine.
1068      */
1069     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1070 	if (protp->protocol == protocol && protp->enabled_flag) {
1071 	    (*protp->input)(0, p, len);
1072 	    return;
1073 	}
1074         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1075 	    && protp->datainput != NULL) {
1076 	    (*protp->datainput)(0, p, len);
1077 	    return;
1078 	}
1079     }
1080 
1081     if (debug) {
1082 	const char *pname = protocol_name(protocol);
1083 	if (pname != NULL)
1084 	    warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1085 	else
1086 	    warn("Unsupported protocol 0x%x received", protocol);
1087     }
1088     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1089 }
1090 
1091 /*
1092  * ppp_send_config - configure the transmit-side characteristics of
1093  * the ppp interface.  Returns -1, indicating an error, if the channel
1094  * send_config procedure called error() (or incremented error_count
1095  * itself), otherwise 0.
1096  */
1097 int
ppp_send_config(unit,mtu,accm,pcomp,accomp)1098 ppp_send_config(unit, mtu, accm, pcomp, accomp)
1099     int unit, mtu;
1100     u_int32_t accm;
1101     int pcomp, accomp;
1102 {
1103 	int errs;
1104 
1105 	if (the_channel->send_config == NULL)
1106 		return 0;
1107 	errs = error_count;
1108 	(*the_channel->send_config)(mtu, accm, pcomp, accomp);
1109 	return (error_count != errs)? -1: 0;
1110 }
1111 
1112 /*
1113  * ppp_recv_config - configure the receive-side characteristics of
1114  * the ppp interface.  Returns -1, indicating an error, if the channel
1115  * recv_config procedure called error() (or incremented error_count
1116  * itself), otherwise 0.
1117  */
1118 int
ppp_recv_config(unit,mru,accm,pcomp,accomp)1119 ppp_recv_config(unit, mru, accm, pcomp, accomp)
1120     int unit, mru;
1121     u_int32_t accm;
1122     int pcomp, accomp;
1123 {
1124 	int errs;
1125 
1126 	if (the_channel->recv_config == NULL)
1127 		return 0;
1128 	errs = error_count;
1129 	(*the_channel->recv_config)(mru, accm, pcomp, accomp);
1130 	return (error_count != errs)? -1: 0;
1131 }
1132 
1133 /*
1134  * new_phase - signal the start of a new phase of pppd's operation.
1135  */
1136 void
new_phase(p)1137 new_phase(p)
1138     int p;
1139 {
1140     phase = p;
1141     if (new_phase_hook)
1142 	(*new_phase_hook)(p);
1143     notify(phasechange, p);
1144 }
1145 
1146 /*
1147  * die - clean up state and exit with the specified status.
1148  */
1149 void
die(status)1150 die(status)
1151     int status;
1152 {
1153     if (!doing_multilink || multilink_master)
1154 	print_link_stats();
1155     cleanup();
1156     notify(exitnotify, status);
1157     syslog(LOG_INFO, "Exit.");
1158     exit(status);
1159 }
1160 
1161 /*
1162  * cleanup - restore anything which needs to be restored before we exit
1163  */
1164 /* ARGSUSED */
1165 static void
cleanup()1166 cleanup()
1167 {
1168     sys_cleanup();
1169 
1170     if (fd_ppp >= 0)
1171 	the_channel->disestablish_ppp(devfd);
1172     if (the_channel->cleanup)
1173 	(*the_channel->cleanup)();
1174     remove_pidfiles();
1175 
1176 #ifdef USE_TDB
1177     if (pppdb != NULL)
1178 	cleanup_db();
1179 #endif
1180 
1181 }
1182 
1183 void
print_link_stats()1184 print_link_stats()
1185 {
1186     /*
1187      * Print connect time and statistics.
1188      */
1189     if (link_stats_valid) {
1190        int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
1191        info("Connect time %d.%d minutes.", t/10, t%10);
1192        info("Sent %u bytes, received %u bytes.",
1193 	    link_stats.bytes_out, link_stats.bytes_in);
1194        link_stats_valid = 0;
1195     }
1196 }
1197 
1198 /*
1199  * reset_link_stats - "reset" stats when link goes up.
1200  */
1201 void
reset_link_stats(u)1202 reset_link_stats(u)
1203     int u;
1204 {
1205     if (!get_ppp_stats(u, &old_link_stats))
1206 	return;
1207     gettimeofday(&start_time, NULL);
1208 }
1209 
1210 /*
1211  * update_link_stats - get stats at link termination.
1212  */
1213 void
update_link_stats(u)1214 update_link_stats(u)
1215     int u;
1216 {
1217     struct timeval now;
1218     char numbuf[32];
1219 
1220     if (!get_ppp_stats(u, &link_stats)
1221 	|| gettimeofday(&now, NULL) < 0)
1222 	return;
1223     link_connect_time = now.tv_sec - start_time.tv_sec;
1224     link_stats_valid = 1;
1225 
1226     link_stats.bytes_in  -= old_link_stats.bytes_in;
1227     link_stats.bytes_out -= old_link_stats.bytes_out;
1228     link_stats.pkts_in   -= old_link_stats.pkts_in;
1229     link_stats.pkts_out  -= old_link_stats.pkts_out;
1230 
1231     slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
1232     script_setenv("CONNECT_TIME", numbuf, 0);
1233     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
1234     script_setenv("BYTES_SENT", numbuf, 0);
1235     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
1236     script_setenv("BYTES_RCVD", numbuf, 0);
1237 }
1238 
1239 
1240 struct	callout {
1241     struct timeval	c_time;		/* time at which to call routine */
1242     void		*c_arg;		/* argument to routine */
1243     void		(*c_func) __P((void *)); /* routine */
1244     struct		callout *c_next;
1245 };
1246 
1247 static struct callout *callout = NULL;	/* Callout list */
1248 static struct timeval timenow;		/* Current time */
1249 
1250 /*
1251  * timeout - Schedule a timeout.
1252  */
1253 void
1254 timeout(func, arg, secs, usecs)
1255     void (*func) __P((void *));
1256     void *arg;
1257     int secs, usecs;
1258 {
1259     struct callout *newp, *p, **pp;
1260 
1261     /*
1262      * Allocate timeout.
1263      */
1264     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1265 	fatal("Out of memory in timeout()!");
1266     newp->c_arg = arg;
1267     newp->c_func = func;
1268     gettimeofday(&timenow, NULL);
1269     newp->c_time.tv_sec = timenow.tv_sec + secs;
1270     newp->c_time.tv_usec = timenow.tv_usec + usecs;
1271     if (newp->c_time.tv_usec >= 1000000) {
1272 	newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1273 	newp->c_time.tv_usec %= 1000000;
1274     }
1275 
1276     /*
1277      * Find correct place and link it in.
1278      */
1279     for (pp = &callout; (p = *pp); pp = &p->c_next)
1280 	if (newp->c_time.tv_sec < p->c_time.tv_sec
1281 	    || (newp->c_time.tv_sec == p->c_time.tv_sec
1282 		&& newp->c_time.tv_usec < p->c_time.tv_usec))
1283 	    break;
1284     newp->c_next = p;
1285     *pp = newp;
1286 }
1287 
1288 
1289 /*
1290  * untimeout - Unschedule a timeout.
1291  */
1292 void
1293 untimeout(func, arg)
1294     void (*func) __P((void *));
1295     void *arg;
1296 {
1297     struct callout **copp, *freep;
1298 
1299     /*
1300      * Find first matching timeout and remove it from the list.
1301      */
1302     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1303 	if (freep->c_func == func && freep->c_arg == arg) {
1304 	    *copp = freep->c_next;
1305 	    free((char *) freep);
1306 	    break;
1307 	}
1308 }
1309 
1310 
1311 /*
1312  * calltimeout - Call any timeout routines which are now due.
1313  */
1314 static void
calltimeout()1315 calltimeout()
1316 {
1317     struct callout *p;
1318 
1319     while (callout != NULL) {
1320 	p = callout;
1321 
1322 	if (gettimeofday(&timenow, NULL) < 0)
1323 	    fatal("Failed to get time of day: %m");
1324 	if (!(p->c_time.tv_sec < timenow.tv_sec
1325 	      || (p->c_time.tv_sec == timenow.tv_sec
1326 		  && p->c_time.tv_usec <= timenow.tv_usec)))
1327 	    break;		/* no, it's not time yet */
1328 
1329 	callout = p->c_next;
1330 	(*p->c_func)(p->c_arg);
1331 
1332 	free((char *) p);
1333     }
1334 }
1335 
1336 
1337 /*
1338  * timeleft - return the length of time until the next timeout is due.
1339  */
1340 static struct timeval *
timeleft(tvp)1341 timeleft(tvp)
1342     struct timeval *tvp;
1343 {
1344     if (callout == NULL)
1345 	return NULL;
1346 
1347     gettimeofday(&timenow, NULL);
1348     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1349     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1350     if (tvp->tv_usec < 0) {
1351 	tvp->tv_usec += 1000000;
1352 	tvp->tv_sec -= 1;
1353     }
1354     if (tvp->tv_sec < 0)
1355 	tvp->tv_sec = tvp->tv_usec = 0;
1356 
1357     return tvp;
1358 }
1359 
1360 
1361 /*
1362  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1363  * We assume that sig is currently blocked.
1364  */
1365 static void
kill_my_pg(sig)1366 kill_my_pg(sig)
1367     int sig;
1368 {
1369     struct sigaction act, oldact;
1370 
1371     sigemptyset(&act.sa_mask);		/* unnecessary in fact */
1372     act.sa_handler = SIG_IGN;
1373     act.sa_flags = 0;
1374     kill(0, sig);
1375     /*
1376      * The kill() above made the signal pending for us, as well as
1377      * the rest of our process group, but we don't want it delivered
1378      * to us.  It is blocked at the moment.  Setting it to be ignored
1379      * will cause the pending signal to be discarded.  If we did the
1380      * kill() after setting the signal to be ignored, it is unspecified
1381      * (by POSIX) whether the signal is immediately discarded or left
1382      * pending, and in fact Linux would leave it pending, and so it
1383      * would be delivered after the current signal handler exits,
1384      * leading to an infinite loop.
1385      */
1386     sigaction(sig, &act, &oldact);
1387     sigaction(sig, &oldact, NULL);
1388 }
1389 
1390 
1391 /*
1392  * hup - Catch SIGHUP signal.
1393  *
1394  * Indicates that the physical layer has been disconnected.
1395  * We don't rely on this indication; if the user has sent this
1396  * signal, we just take the link down.
1397  */
1398 static void
hup(sig)1399 hup(sig)
1400     int sig;
1401 {
1402     /* can't log a message here, it can deadlock */
1403     got_sighup = 1;
1404     if (conn_running)
1405 	/* Send the signal to the [dis]connector process(es) also */
1406 	kill_my_pg(sig);
1407     notify(sigreceived, sig);
1408     if (waiting)
1409 	siglongjmp(sigjmp, 1);
1410 }
1411 
1412 
1413 /*
1414  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1415  *
1416  * Indicates that we should initiate a graceful disconnect and exit.
1417  */
1418 /*ARGSUSED*/
1419 static void
term(sig)1420 term(sig)
1421     int sig;
1422 {
1423     /* can't log a message here, it can deadlock */
1424     got_sigterm = sig;
1425     if (conn_running)
1426 	/* Send the signal to the [dis]connector process(es) also */
1427 	kill_my_pg(sig);
1428     notify(sigreceived, sig);
1429     if (waiting)
1430 	siglongjmp(sigjmp, 1);
1431 }
1432 
1433 
1434 /*
1435  * chld - Catch SIGCHLD signal.
1436  * Sets a flag so we will call reap_kids in the mainline.
1437  */
1438 static void
chld(sig)1439 chld(sig)
1440     int sig;
1441 {
1442     got_sigchld = 1;
1443     if (waiting)
1444 	siglongjmp(sigjmp, 1);
1445 }
1446 
1447 
1448 /*
1449  * toggle_debug - Catch SIGUSR1 signal.
1450  *
1451  * Toggle debug flag.
1452  */
1453 /*ARGSUSED*/
1454 static void
toggle_debug(sig)1455 toggle_debug(sig)
1456     int sig;
1457 {
1458     debug = !debug;
1459     if (debug) {
1460 	setlogmask(LOG_UPTO(LOG_DEBUG));
1461     } else {
1462 	setlogmask(LOG_UPTO(LOG_WARNING));
1463     }
1464 }
1465 
1466 
1467 /*
1468  * open_ccp - Catch SIGUSR2 signal.
1469  *
1470  * Try to (re)negotiate compression.
1471  */
1472 /*ARGSUSED*/
1473 static void
open_ccp(sig)1474 open_ccp(sig)
1475     int sig;
1476 {
1477     got_sigusr2 = 1;
1478     if (waiting)
1479 	siglongjmp(sigjmp, 1);
1480 }
1481 
1482 
1483 /*
1484  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1485  */
1486 static void
bad_signal(sig)1487 bad_signal(sig)
1488     int sig;
1489 {
1490     static int crashed = 0;
1491 
1492     if (crashed)
1493 	_exit(127);
1494     crashed = 1;
1495     error("Fatal signal %d", sig);
1496     if (conn_running)
1497 	kill_my_pg(SIGTERM);
1498     notify(sigreceived, sig);
1499     die(127);
1500 }
1501 
1502 /*
1503  * safe_fork - Create a child process.  The child closes all the
1504  * file descriptors that we don't want to leak to a script.
1505  * The parent waits for the child to do this before returning.
1506  * This also arranges for the specified fds to be dup'd to
1507  * fds 0, 1, 2 in the child.
1508  */
1509 pid_t
safe_fork(int infd,int outfd,int errfd)1510 safe_fork(int infd, int outfd, int errfd)
1511 {
1512 	pid_t pid;
1513 	int fd, pipefd[2];
1514 	char buf[1];
1515 
1516 	/* make sure fds 0, 1, 2 are occupied (probably not necessary) */
1517 	while ((fd = dup(fd_devnull)) >= 0) {
1518 		if (fd > 2) {
1519 			close(fd);
1520 			break;
1521 		}
1522 	}
1523 
1524 	if (pipe(pipefd) == -1)
1525 		pipefd[0] = pipefd[1] = -1;
1526 	pid = fork();
1527 	if (pid < 0) {
1528 		error("fork failed: %m");
1529 		return -1;
1530 	}
1531 	if (pid > 0) {
1532 		/* parent */
1533 		close(pipefd[1]);
1534 		/* this read() blocks until the close(pipefd[1]) below */
1535 		complete_read(pipefd[0], buf, 1);
1536 		close(pipefd[0]);
1537 		return pid;
1538 	}
1539 
1540 	/* Executing in the child */
1541 	sys_close();
1542 #ifdef USE_TDB
1543 	tdb_close(pppdb);
1544 #endif
1545 
1546 	/* make sure infd, outfd and errfd won't get tromped on below */
1547 	if (infd == 1 || infd == 2)
1548 		infd = dup(infd);
1549 	if (outfd == 0 || outfd == 2)
1550 		outfd = dup(outfd);
1551 	if (errfd == 0 || errfd == 1)
1552 		errfd = dup(errfd);
1553 
1554 	/* dup the in, out, err fds to 0, 1, 2 */
1555 	if (infd != 0)
1556 		dup2(infd, 0);
1557 	if (outfd != 1)
1558 		dup2(outfd, 1);
1559 	if (errfd != 2)
1560 		dup2(errfd, 2);
1561 
1562 #ifndef ANDROID_CHANGES
1563 	closelog();
1564 #endif
1565 	if (log_to_fd > 2)
1566 		close(log_to_fd);
1567 	if (the_channel->close)
1568 		(*the_channel->close)();
1569 	else
1570 		close(devfd);	/* some plugins don't have a close function */
1571 	close(fd_ppp);
1572 	close(fd_devnull);
1573 	if (infd != 0)
1574 		close(infd);
1575 	if (outfd != 1)
1576 		close(outfd);
1577 	if (errfd != 2)
1578 		close(errfd);
1579 
1580 	notify(fork_notifier, 0);
1581 	close(pipefd[0]);
1582 	/* this close unblocks the read() call above in the parent */
1583 	close(pipefd[1]);
1584 
1585 	return 0;
1586 }
1587 
1588 /*
1589  * device_script - run a program to talk to the specified fds
1590  * (e.g. to run the connector or disconnector script).
1591  * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1592  */
1593 int
device_script(program,in,out,dont_wait)1594 device_script(program, in, out, dont_wait)
1595     char *program;
1596     int in, out;
1597     int dont_wait;
1598 {
1599     int pid;
1600     int status = -1;
1601     int errfd;
1602 
1603     if (log_to_fd >= 0)
1604 	errfd = log_to_fd;
1605     else
1606 	errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1607 
1608     ++conn_running;
1609     pid = safe_fork(in, out, errfd);
1610 
1611     if (pid != 0 && log_to_fd < 0)
1612 	close(errfd);
1613 
1614     if (pid < 0) {
1615 	--conn_running;
1616 	error("Failed to create child process: %m");
1617 	return -1;
1618     }
1619 
1620     if (pid != 0) {
1621 	if (dont_wait) {
1622 	    record_child(pid, program, NULL, NULL);
1623 	    status = 0;
1624 	} else {
1625 	    while (waitpid(pid, &status, 0) < 0) {
1626 		if (errno == EINTR)
1627 		    continue;
1628 		fatal("error waiting for (dis)connection process: %m");
1629 	    }
1630 	    --conn_running;
1631 	}
1632 	return (status == 0 ? 0 : -1);
1633     }
1634 
1635     /* here we are executing in the child */
1636 
1637     setgid(getgid());
1638     setuid(uid);
1639     if (getuid() != uid) {
1640 	fprintf(stderr, "pppd: setuid failed\n");
1641 	exit(1);
1642     }
1643     execl("/system/bin/sh", "sh", "-c", program, NULL);
1644     perror("pppd: could not exec /bin/sh");
1645     exit(99);
1646     /* NOTREACHED */
1647 }
1648 
1649 
1650 /*
1651  * run-program - execute a program with given arguments,
1652  * but don't wait for it.
1653  * If the program can't be executed, logs an error unless
1654  * must_exist is 0 and the program file doesn't exist.
1655  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1656  * or isn't an executable plain file, or the process ID of the child.
1657  * If done != NULL, (*done)(arg) will be called later (within
1658  * reap_kids) iff the return value is > 0.
1659  */
1660 pid_t
run_program(prog,args,must_exist,done,arg)1661 run_program(prog, args, must_exist, done, arg)
1662     char *prog;
1663     char **args;
1664     int must_exist;
1665     void (*done) __P((void *));
1666     void *arg;
1667 {
1668     int pid;
1669     struct stat sbuf;
1670 
1671 #ifdef ANDROID_CHANGES
1672     /* Originally linkname is used to create named pid files, which is
1673     * meaningless to android. Here we use it as a suffix of program names,
1674     * so different users can run their own program by specifying it. For
1675     * example, "/etc/ppp/ip-up-vpn" will be executed when IPCP is up and
1676     * linkname is "vpn". Note that "/" is not allowed for security reasons. */
1677     char file[MAXPATHLEN];
1678 
1679     if (linkname[0] && !strchr(linkname, '/')) {
1680         snprintf(file, MAXPATHLEN, "%s-%s", prog, linkname);
1681         file[MAXPATHLEN - 1] = '\0';
1682         prog = file;
1683     }
1684 #endif
1685 
1686     /*
1687      * First check if the file exists and is executable.
1688      * We don't use access() because that would use the
1689      * real user-id, which might not be root, and the script
1690      * might be accessible only to root.
1691      */
1692     errno = EINVAL;
1693     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1694 	|| (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1695 	if (must_exist || errno != ENOENT)
1696 	    warn("Can't execute %s: %m", prog);
1697 	return 0;
1698     }
1699 
1700     pid = safe_fork(fd_devnull, fd_devnull, fd_devnull);
1701     if (pid == -1) {
1702 	error("Failed to create child process for %s: %m", prog);
1703 	return -1;
1704     }
1705     if (pid != 0) {
1706 	if (debug)
1707 	    dbglog("Script %s started (pid %d)", prog, pid);
1708 	record_child(pid, prog, done, arg);
1709 	return pid;
1710     }
1711 
1712     /* Leave the current location */
1713     (void) setsid();	/* No controlling tty. */
1714     (void) umask (S_IRWXG|S_IRWXO);
1715     (void) chdir ("/");	/* no current directory. */
1716     setuid(0);		/* set real UID = root */
1717     setgid(getegid());
1718 
1719 #ifdef BSD
1720     /* Force the priority back to zero if pppd is running higher. */
1721     if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1722 	warn("can't reset priority to 0: %m");
1723 #endif
1724 
1725     /* run the program */
1726     execve(prog, args, script_env);
1727     if (must_exist || errno != ENOENT) {
1728 #ifndef ANDROID_CHANGES
1729 	/* have to reopen the log, there's nowhere else
1730 	   for the message to go. */
1731 	reopen_log();
1732 	syslog(LOG_ERR, "Can't execute %s: %m", prog);
1733 	closelog();
1734 #else
1735 	error("Can't execute %s: %m", prog);
1736 #endif
1737     }
1738     _exit(-1);
1739 }
1740 
1741 
1742 /*
1743  * record_child - add a child process to the list for reap_kids
1744  * to use.
1745  */
1746 void
record_child(pid,prog,done,arg)1747 record_child(pid, prog, done, arg)
1748     int pid;
1749     char *prog;
1750     void (*done) __P((void *));
1751     void *arg;
1752 {
1753     struct subprocess *chp;
1754 
1755     ++n_children;
1756 
1757     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1758     if (chp == NULL) {
1759 	warn("losing track of %s process", prog);
1760     } else {
1761 	chp->pid = pid;
1762 	chp->prog = prog;
1763 	chp->done = done;
1764 	chp->arg = arg;
1765 	chp->next = children;
1766 	children = chp;
1767     }
1768 }
1769 
1770 /*
1771  * childwait_end - we got fed up waiting for the child processes to
1772  * exit, send them all a SIGTERM.
1773  */
1774 static void
childwait_end(arg)1775 childwait_end(arg)
1776     void *arg;
1777 {
1778     struct subprocess *chp;
1779 
1780     for (chp = children; chp != NULL; chp = chp->next) {
1781 	if (debug)
1782 	    dbglog("sending SIGTERM to process %d", chp->pid);
1783 	kill(chp->pid, SIGTERM);
1784     }
1785     childwait_done = 1;
1786 }
1787 
1788 /*
1789  * reap_kids - get status from any dead child processes,
1790  * and log a message for abnormal terminations.
1791  */
1792 static int
reap_kids()1793 reap_kids()
1794 {
1795     int pid, status;
1796     struct subprocess *chp, **prevp;
1797 
1798     if (n_children == 0)
1799 	return 0;
1800     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1801 	for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1802 	    if (chp->pid == pid) {
1803 		--n_children;
1804 		*prevp = chp->next;
1805 		break;
1806 	    }
1807 	}
1808 	if (WIFSIGNALED(status)) {
1809 	    warn("Child process %s (pid %d) terminated with signal %d",
1810 		 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1811 	} else if (debug)
1812 	    dbglog("Script %s finished (pid %d), status = 0x%x",
1813 		   (chp? chp->prog: "??"), pid,
1814 		   WIFEXITED(status) ? WEXITSTATUS(status) : status);
1815 	if (chp && chp->done)
1816 	    (*chp->done)(chp->arg);
1817 	if (chp)
1818 	    free(chp);
1819     }
1820     if (pid == -1) {
1821 	if (errno == ECHILD)
1822 	    return -1;
1823 	if (errno != EINTR)
1824 	    error("Error waiting for child process: %m");
1825     }
1826     return 0;
1827 }
1828 
1829 /*
1830  * add_notifier - add a new function to be called when something happens.
1831  */
1832 void
add_notifier(notif,func,arg)1833 add_notifier(notif, func, arg)
1834     struct notifier **notif;
1835     notify_func func;
1836     void *arg;
1837 {
1838     struct notifier *np;
1839 
1840     np = malloc(sizeof(struct notifier));
1841     if (np == 0)
1842 	novm("notifier struct");
1843     np->next = *notif;
1844     np->func = func;
1845     np->arg = arg;
1846     *notif = np;
1847 }
1848 
1849 /*
1850  * remove_notifier - remove a function from the list of things to
1851  * be called when something happens.
1852  */
1853 void
remove_notifier(notif,func,arg)1854 remove_notifier(notif, func, arg)
1855     struct notifier **notif;
1856     notify_func func;
1857     void *arg;
1858 {
1859     struct notifier *np;
1860 
1861     for (; (np = *notif) != 0; notif = &np->next) {
1862 	if (np->func == func && np->arg == arg) {
1863 	    *notif = np->next;
1864 	    free(np);
1865 	    break;
1866 	}
1867     }
1868 }
1869 
1870 /*
1871  * notify - call a set of functions registered with add_notifier.
1872  */
1873 void
notify(notif,val)1874 notify(notif, val)
1875     struct notifier *notif;
1876     int val;
1877 {
1878     struct notifier *np;
1879 
1880     while ((np = notif) != 0) {
1881 	notif = np->next;
1882 	(*np->func)(np->arg, val);
1883     }
1884 }
1885 
1886 /*
1887  * novm - log an error message saying we ran out of memory, and die.
1888  */
1889 void
novm(msg)1890 novm(msg)
1891     char *msg;
1892 {
1893     fatal("Virtual memory exhausted allocating %s\n", msg);
1894 }
1895 
1896 /*
1897  * script_setenv - set an environment variable value to be used
1898  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1899  */
1900 void
script_setenv(var,value,iskey)1901 script_setenv(var, value, iskey)
1902     char *var, *value;
1903     int iskey;
1904 {
1905     size_t varl = strlen(var);
1906     size_t vl = varl + strlen(value) + 2;
1907     int i;
1908     char *p, *newstring;
1909 
1910     newstring = (char *) malloc(vl+1);
1911     if (newstring == 0)
1912 	return;
1913     *newstring++ = iskey;
1914     slprintf(newstring, vl, "%s=%s", var, value);
1915 
1916     /* check if this variable is already set */
1917     if (script_env != 0) {
1918 	for (i = 0; (p = script_env[i]) != 0; ++i) {
1919 	    if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1920 #ifdef USE_TDB
1921 		if (p[-1] && pppdb != NULL)
1922 		    delete_db_key(p);
1923 #endif
1924 		free(p-1);
1925 		script_env[i] = newstring;
1926 #ifdef USE_TDB
1927 		if (iskey && pppdb != NULL)
1928 		    add_db_key(newstring);
1929 		update_db_entry();
1930 #endif
1931 		return;
1932 	    }
1933 	}
1934     } else {
1935 	/* no space allocated for script env. ptrs. yet */
1936 	i = 0;
1937 	script_env = (char **) malloc(16 * sizeof(char *));
1938 	if (script_env == 0)
1939 	    return;
1940 	s_env_nalloc = 16;
1941     }
1942 
1943     /* reallocate script_env with more space if needed */
1944     if (i + 1 >= s_env_nalloc) {
1945 	int new_n = i + 17;
1946 	char **newenv = (char **) realloc((void *)script_env,
1947 					  new_n * sizeof(char *));
1948 	if (newenv == 0)
1949 	    return;
1950 	script_env = newenv;
1951 	s_env_nalloc = new_n;
1952     }
1953 
1954     script_env[i] = newstring;
1955     script_env[i+1] = 0;
1956 
1957 #ifdef USE_TDB
1958     if (pppdb != NULL) {
1959 	if (iskey)
1960 	    add_db_key(newstring);
1961 	update_db_entry();
1962     }
1963 #endif
1964 }
1965 
1966 /*
1967  * script_unsetenv - remove a variable from the environment
1968  * for scripts.
1969  */
1970 void
script_unsetenv(var)1971 script_unsetenv(var)
1972     char *var;
1973 {
1974     int vl = strlen(var);
1975     int i;
1976     char *p;
1977 
1978     if (script_env == 0)
1979 	return;
1980     for (i = 0; (p = script_env[i]) != 0; ++i) {
1981 	if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1982 #ifdef USE_TDB
1983 	    if (p[-1] && pppdb != NULL)
1984 		delete_db_key(p);
1985 #endif
1986 	    free(p-1);
1987 	    while ((script_env[i] = script_env[i+1]) != 0)
1988 		++i;
1989 	    break;
1990 	}
1991     }
1992 #ifdef USE_TDB
1993     if (pppdb != NULL)
1994 	update_db_entry();
1995 #endif
1996 }
1997 
1998 /*
1999  * Any arbitrary string used as a key for locking the database.
2000  * It doesn't matter what it is as long as all pppds use the same string.
2001  */
2002 #define PPPD_LOCK_KEY	"pppd lock"
2003 
2004 /*
2005  * lock_db - get an exclusive lock on the TDB database.
2006  * Used to ensure atomicity of various lookup/modify operations.
2007  */
lock_db()2008 void lock_db()
2009 {
2010 #ifdef USE_TDB
2011 	TDB_DATA key;
2012 
2013 	key.dptr = PPPD_LOCK_KEY;
2014 	key.dsize = strlen(key.dptr);
2015 	tdb_chainlock(pppdb, key);
2016 #endif
2017 }
2018 
2019 /*
2020  * unlock_db - remove the exclusive lock obtained by lock_db.
2021  */
unlock_db()2022 void unlock_db()
2023 {
2024 #ifdef USE_TDB
2025 	TDB_DATA key;
2026 
2027 	key.dptr = PPPD_LOCK_KEY;
2028 	key.dsize = strlen(key.dptr);
2029 	tdb_chainunlock(pppdb, key);
2030 #endif
2031 }
2032 
2033 #ifdef USE_TDB
2034 /*
2035  * update_db_entry - update our entry in the database.
2036  */
2037 static void
update_db_entry()2038 update_db_entry()
2039 {
2040     TDB_DATA key, dbuf;
2041     int vlen, i;
2042     char *p, *q, *vbuf;
2043 
2044     if (script_env == NULL)
2045 	return;
2046     vlen = 0;
2047     for (i = 0; (p = script_env[i]) != 0; ++i)
2048 	vlen += strlen(p) + 1;
2049     vbuf = malloc(vlen + 1);
2050     if (vbuf == 0)
2051 	novm("database entry");
2052     q = vbuf;
2053     for (i = 0; (p = script_env[i]) != 0; ++i)
2054 	q += slprintf(q, vbuf + vlen - q, "%s;", p);
2055 
2056     key.dptr = db_key;
2057     key.dsize = strlen(db_key);
2058     dbuf.dptr = vbuf;
2059     dbuf.dsize = vlen;
2060     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2061 	error("tdb_store failed: %s", tdb_error(pppdb));
2062 
2063     if (vbuf)
2064         free(vbuf);
2065 
2066 }
2067 
2068 /*
2069  * add_db_key - add a key that we can use to look up our database entry.
2070  */
2071 static void
add_db_key(str)2072 add_db_key(str)
2073     const char *str;
2074 {
2075     TDB_DATA key, dbuf;
2076 
2077     key.dptr = (char *) str;
2078     key.dsize = strlen(str);
2079     dbuf.dptr = db_key;
2080     dbuf.dsize = strlen(db_key);
2081     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2082 	error("tdb_store key failed: %s", tdb_error(pppdb));
2083 }
2084 
2085 /*
2086  * delete_db_key - delete a key for looking up our database entry.
2087  */
2088 static void
delete_db_key(str)2089 delete_db_key(str)
2090     const char *str;
2091 {
2092     TDB_DATA key;
2093 
2094     key.dptr = (char *) str;
2095     key.dsize = strlen(str);
2096     tdb_delete(pppdb, key);
2097 }
2098 
2099 /*
2100  * cleanup_db - delete all the entries we put in the database.
2101  */
2102 static void
cleanup_db()2103 cleanup_db()
2104 {
2105     TDB_DATA key;
2106     int i;
2107     char *p;
2108 
2109     key.dptr = db_key;
2110     key.dsize = strlen(db_key);
2111     tdb_delete(pppdb, key);
2112     for (i = 0; (p = script_env[i]) != 0; ++i)
2113 	if (p[-1])
2114 	    delete_db_key(p);
2115 }
2116 #endif /* USE_TDB */
2117