Tomato 1.28
[tomato.git] / release / src / router / ppp / pppoecd / main.c
blobdbf2145e21c2a408e7df742a1a98ea4824c5cd98
1 /*
2 * main.c - Point-to-Point Protocol main module
4 * Copyright (c) 1989 Carnegie Mellon University.
5 * All rights reserved.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by Carnegie Mellon University. The name of the
13 * University may not be used to endorse or promote products derived
14 * from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 #define RCSID "$Id: main.c,v 1.7 2004/08/12 02:56:55 tallest Exp $"
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <pwd.h>
34 #include <setjmp.h>
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
45 #include "pppd.h"
46 #include "magic.h"
47 #include "fsm.h"
48 #include "lcp.h"
49 #include "ipcp.h"
50 #include "upap.h"
51 #include "chap.h"
52 #include "ccp.h"
53 #include "pathnames.h"
55 #ifdef CBCP_SUPPORT
56 #include "cbcp.h"
57 #endif
59 #ifdef IPX_CHANGE
60 #include "ipxcp.h"
61 #endif /* IPX_CHANGE */
62 #ifdef AT_CHANGE
63 #include "atcp.h"
64 #endif
66 static const char rcsid[] = RCSID;
68 /* interface vars */
69 char ifname[32]; /* Interface name */
70 int ifunit; /* Interface unit number */
71 int dial_cnt;
73 struct channel *the_channel;
75 char *progname; /* Name of this program */
76 char hostname[MAXNAMELEN]; /* Our hostname */
77 static char pidfilename[MAXPATHLEN]; /* name of pid file */
78 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
79 char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
80 uid_t uid; /* Our real user-id */
82 int hungup; /* terminal has been hung up */
83 int privileged; /* we're running as real uid root */
84 int need_holdoff; /* need holdoff period before restarting */
85 int detached; /* have detached from terminal */
86 volatile int status; /* exit status for pppd */
87 int unsuccess; /* # unsuccessful connection attempts */
88 int do_callback; /* != 0 if we should do callback next */
89 int doing_callback; /* != 0 if we are doing callback */
90 #define pppdb NULL
92 // int (*holdoff_hook) __P((void)) = NULL;
93 int (*new_phase_hook) __P((int)) = NULL;
95 static int conn_running; /* we have a [dis]connector running */
96 static int devfd; /* fd of underlying device */
97 static int fd_ppp = -1; /* fd for talking PPP */
98 static int fd_loop; /* fd for getting demand-dial packets */
100 int phase; /* where the link is at */
101 int kill_link;
102 int open_ccp_flag;
103 int listen_time;
104 int got_sigusr2;
105 int got_sigterm;
106 int got_sighup;
108 static int waiting;
109 static sigjmp_buf sigjmp;
111 char **script_env; /* Env. variable values for scripts */
112 int s_env_nalloc; /* # words avail at script_env */
114 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
115 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
117 static int n_children; /* # child processes still running */
118 static int got_sigchld; /* set if we have received a SIGCHLD */
120 int privopen; /* don't lock, open device as root */
122 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
124 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
125 int ngroups; /* How many groups valid in groups */
127 static struct timeval start_time; /* Time when link was started. */
129 struct pppd_stats link_stats;
130 int link_connect_time;
131 int link_stats_valid;
133 const char pppoe_disc_file[] = "/var/lib/misc/pppoe-disc";
137 * We maintain a list of child process pids and
138 * functions to call when they exit.
140 struct subprocess {
141 pid_t pid;
142 char *prog;
143 void (*done) __P((void *));
144 void *arg;
145 struct subprocess *next;
148 static struct subprocess *children;
150 /* Prototypes for procedures local to this file. */
152 static void setup_signals __P((void));
153 static void create_pidfile __P((void));
154 static void create_linkpidfile __P((void));
155 static void cleanup __P((void));
156 static void get_input __P((void));
157 static void calltimeout __P((void));
158 static struct timeval *timeleft __P((struct timeval *));
159 static void kill_my_pg __P((int));
160 static void hup __P((int));
161 static void term __P((int));
162 static void chld __P((int));
163 static void toggle_debug __P((int));
164 static void open_ccp __P((int));
165 static void bad_signal __P((int));
166 static void holdoff_end __P((void *));
167 static int reap_kids __P((int waitfor));
168 #define update_db_entry()
169 #define add_db_key(a)
170 #define delete_db_key(a)
171 #define cleanup_db()
172 static void handle_events __P((void));
174 extern char *ttyname __P((int));
175 extern char *getlogin __P((void));
176 int main __P((int, char *[]));
178 extern void prng_init(); // random.c
181 #ifdef ultrix
182 #undef O_NONBLOCK
183 #define O_NONBLOCK O_NDELAY
184 #endif
186 #ifdef ULTRIX
187 #define setlogmask(x)
188 #endif
191 * PPP Data Link Layer "protocol" table.
192 * One entry per supported protocol.
193 * The last entry must be NULL.
195 struct protent *protocols[] = {
196 &lcp_protent,
197 &pap_protent,
198 #ifdef CHAP_SUPPORT
199 &chap_protent,
200 #endif
201 &ipcp_protent,
202 #ifdef CCP_SUPPORT
203 &ccp_protent,
204 #endif
205 NULL
209 * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
211 #if !defined(PPP_DRV_NAME)
212 #define PPP_DRV_NAME "ppp"
213 #endif /* !defined(PPP_DRV_NAME) */
215 extern int retransmit_time;
216 extern int redial_immediately;
219 int debug_exist(const char *name)
221 struct stat st;
222 return (stat(name, &st) == 0);
227 main(argc, argv)
228 int argc;
229 char *argv[];
231 int i, t;
232 char *p;
233 struct passwd *pw;
234 struct protent *protp;
235 char numbuf[16];
237 new_phase(PHASE_INITIALIZE);
240 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
241 * This way we can close 0, 1, 2 in detach() without clobbering
242 * a fd that we are using.
244 if ((i = open("/dev/null", O_RDWR)) >= 0) {
245 while (0 <= i && i <= 2)
246 i = dup(i);
247 if (i >= 0)
248 close(i);
251 script_env = NULL;
253 /* Initialize syslog facilities */
254 //reopen_log();
256 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
257 LOGX_ERROR("Couldn't get hostname");
258 option_error("Couldn't get hostname: %m");
259 exit(1);
261 hostname[MAXNAMELEN-1] = 0;
263 /* make sure we don't create world or group writable files. */
264 umask(umask(0777) | 022);
266 uid = getuid();
267 privileged = uid == 0;
268 slprintf(numbuf, sizeof(numbuf), "%d", uid);
269 script_setenv("ORIG_UID", numbuf, 0);
271 ngroups = getgroups(NGROUPS_MAX, groups);
274 * Initialize magic number generator now so that protocols may
275 * use magic numbers in initialization.
277 magic_init();
280 * Initialize each protocol.
282 for (i = 0; (protp = protocols[i]) != NULL; ++i)
283 (*protp->init)(0);
285 progname = *argv;
288 * Parse, in order, the system options file, the user's options file,
289 * and the command line arguments.
292 if (!parse_args(argc, argv))
293 exit(EXIT_OPTION_ERROR);
294 devnam_fixed = 1; /* can no longer change device name */
296 reopen_log(); // According to ipparam value, decide log name
299 * Work out the device name, if it hasn't already been specified,
300 * and parse the tty's options file.
302 if (the_channel->process_extra_options)
303 (*the_channel->process_extra_options)();
305 if (debug)
306 setlogmask(LOG_UPTO(LOG_DEBUG));
309 * Check that we are running as root.
311 if (geteuid() != 0) {
312 option_error("must be root to run %s, since it is not setuid-root",
313 argv[0]);
314 exit(EXIT_NOT_ROOT);
317 if (!ppp_available()) {
318 option_error("%s", no_ppp_msg);
319 exit(EXIT_NO_KERNEL_SUPPORT);
323 * Check that the options given are valid and consistent.
325 check_options();
326 if (!sys_check_options())
327 exit(EXIT_OPTION_ERROR);
328 auth_check_options();
329 for (i = 0; (protp = protocols[i]) != NULL; ++i)
330 if (protp->check_options != NULL)
331 (*protp->check_options)();
332 if (the_channel->check_options)
333 (*the_channel->check_options)();
336 if (dump_options || dryrun) {
337 init_pr_log(NULL, LOG_INFO);
338 print_options(pr_log, NULL);
339 end_pr_log();
340 if (dryrun)
341 die(0);
345 * Initialize system-dependent stuff.
347 sys_init();
350 * Initialize random seed.
352 prng_init();
355 * Detach ourselves from the terminal, if required,
356 * and identify who is running us.
358 if (!nodetach && !updetach)
359 detach();
360 p = getlogin();
361 if (p == NULL) {
362 pw = getpwuid(uid);
363 if (pw != NULL && pw->pw_name != NULL)
364 p = pw->pw_name;
365 else
366 p = "(unknown)";
369 LOGX_INFO("Starting");
370 LOGX_DEBUG("demand=%d", demand);
372 script_setenv("PPPLOGNAME", p, 0);
374 if (devnam[0])
375 script_setenv("DEVICE", devnam, 1);
376 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
377 script_setenv("PPPD_PID", numbuf, 1);
379 setup_signals();
381 waiting = 0;
383 create_linkpidfile();
386 * If we're doing dial-on-demand, set up the interface now.
388 if (demand) {
390 * Open the loopback channel and set it up to be the ppp interface.
392 fd_loop = open_ppp_loopback();
393 set_ifunit(1);
396 * Configure the interface and mark it up, etc.
398 demand_conf();
401 do_callback = 0;
403 dial_cnt = 0;
404 for (;;) { // ##1
406 listen_time = 0;
407 need_holdoff = 1;
408 devfd = -1;
409 status = EXIT_OK;
410 ++unsuccess;
411 doing_callback = do_callback;
412 do_callback = 0;
414 if (demand && !doing_callback) {
416 * Don't do anything until we see some activity.
418 LOGX_DEBUG("%s: PHASE_DORMANT", __FUNCTION__);
419 new_phase(PHASE_DORMANT);
420 demand_unblock();
421 add_fd(fd_loop);
422 for (;;) { // ##2
423 handle_events();
424 if (kill_link && !persist)
425 break;
426 if (get_loop_output()) {
427 break;
429 } // for (;;) ##2
430 remove_fd(fd_loop);
431 if (kill_link && !persist) {
432 LOGX_DEBUG("%s: (kill_link && !persist)", __FUNCTION__);
433 break;
437 * Now we want to bring up the link.
439 demand_block();
440 info("Starting link");
441 } // if (demand && !doing_callback)
443 new_phase(PHASE_SERIALCONN);
445 devfd = the_channel->connect();
446 LOGX_DEBUG("%s: the_channel->connect()=%d", __FUNCTION__, devfd);
447 if (devfd < 0) {
448 redial_immediately = 0;
449 continue;
452 /* set up the serial device as a ppp interface */
453 fd_ppp = the_channel->establish_ppp(devfd);
454 LOGX_DEBUG("%s: the_channel->establish_ppp()=%d", __FUNCTION__, fd_ppp);
455 if (fd_ppp < 0) {
456 status = EXIT_FATAL_ERROR;
457 goto disconnect;
460 if (!demand && ifunit >= 0)
461 set_ifunit(1);
464 * Start opening the connection and wait for
465 * incoming events (reply, timeout, etc.).
467 notice("Connect: %s <--> %s", ifname, ppp_devnam);
468 my_gettimeofday(&start_time, NULL);
469 link_stats_valid = 0;
470 script_unsetenv("CONNECT_TIME");
471 script_unsetenv("BYTES_SENT");
472 script_unsetenv("BYTES_RCVD");
473 lcp_lowerup(0);
475 add_fd(fd_ppp);
476 lcp_open(0); /* Start protocol */
477 status = EXIT_NEGOTIATION_FAILED;
478 new_phase(PHASE_ESTABLISH);
479 while (phase != PHASE_DEAD) {
480 handle_events();
481 get_input();
482 if (kill_link)
483 lcp_close(0, "User request");
484 #ifdef CCP_SUPPORT
485 if (open_ccp_flag) {
486 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
487 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
488 (*ccp_protent.open)(0);
491 #endif
492 } // while (phase != PHASE_DEAD)
494 LOGX_DEBUG("%s: phase == PHASE_DEAD", __FUNCTION__);
497 * Print connect time and statistics.
499 LOGX_NOTICE("Disconnected.");
500 if (link_stats_valid) {
501 int tt = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
502 LOGX_NOTICE("Connect time %d.%d minutes.", tt / 10, tt % 10);
503 LOGX_NOTICE("Sent %u bytes, received %u bytes.", link_stats.bytes_out, link_stats.bytes_in);
507 * Delete pid file before disestablishing ppp. Otherwise it
508 * can happen that another pppd gets the same unit and then
509 * we delete its pid file.
511 if (!demand) {
512 if (pidfilename[0] != 0
513 && unlink(pidfilename) < 0 && errno != ENOENT)
514 warn("unable to delete pid file %s: %m", pidfilename);
515 pidfilename[0] = 0;
519 * If we may want to bring the link up again, transfer
520 * the ppp unit back to the loopback. Set the
521 * real serial device back to its normal mode of operation.
523 remove_fd(fd_ppp);
524 clean_check();
525 the_channel->disestablish_ppp(devfd);
526 fd_ppp = -1;
527 if (!hungup)
528 lcp_lowerdown(0);
529 if (!demand)
530 script_unsetenv("IFNAME");
532 disconnect:
533 LOGX_DEBUG("%s: disconnect", __FUNCTION__);
535 if (!demand) {
536 sys_cleanup();
539 new_phase(PHASE_DISCONNECT);
540 the_channel->disconnect();
542 if (the_channel->cleanup)
543 (*the_channel->cleanup)();
545 if (!demand) {
546 if (pidfilename[0] != 0
547 && unlink(pidfilename) < 0 && errno != ENOENT)
548 warn("unable to delete pid file %s: %m", pidfilename);
549 pidfilename[0] = 0;
552 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
553 break;
554 if (demand)
555 demand_discard();
557 if (need_holdoff) {
558 LOGX_DEBUG("%s: redial_immediately=%d", __FUNCTION__, redial_immediately);
560 /***************************************
561 * modify by tanghui 2006-03-28
562 * first 3 time set to 15 sec
563 * after that, should try to redial randomly
564 * FIXME: has send a PADI before HOLDOFF so, (3 - 1)
565 ***************************************/
566 if (!redial_immediately)
568 if(!idle_time_limit)
570 if(dial_cnt < 3)
572 holdoff = 10;
574 else
576 holdoff = (int)(3 + (((retransmit_time - 3.0) * rand())/ (RAND_MAX + 1.0)));
577 if((holdoff > 93) && (holdoff > retransmit_time - 90))
579 holdoff -= 90;
581 //holdoff = 3 + gen_random_int(retransmit_time - 3);
584 else
586 holdoff = 10;
588 t = holdoff;
590 else
592 t = 10; //modified from 0 to 10 //by crazy 20070508
593 redial_immediately = 0;
596 LOGX_DEBUG("%s: t=%d", __FUNCTION__, t);
598 if (t > 0) {
599 new_phase(PHASE_HOLDOFF);
600 TIMEOUT(holdoff_end, NULL, t);
601 do {
602 handle_events();
603 if (kill_link)
604 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
605 } while (phase == PHASE_HOLDOFF);
606 if (!persist)
607 break;
609 } // need_holdoff
610 else {
611 LOGX_DEBUG("%s: !need_holdoff", __FUNCTION__);
613 } // for(;;) ##1
615 /* Wait for scripts to finish */
616 while (n_children > 0) {
617 if (debug) {
618 struct subprocess *chp;
619 dbglog("Waiting for %d child processes...", n_children);
620 for (chp = children; chp != NULL; chp = chp->next)
621 dbglog(" script %s, pid %d", chp->prog, chp->pid);
623 if (reap_kids(1) < 0)
624 break;
627 die(status);
628 return 0;
632 * handle_events - wait for something to happen and respond to it.
634 static void
635 handle_events()
637 struct timeval timo;
638 sigset_t mask;
640 kill_link = open_ccp_flag = 0;
641 if (sigsetjmp(sigjmp, 1) == 0) {
642 sigprocmask(SIG_BLOCK, &mask, NULL);
643 if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
644 sigprocmask(SIG_UNBLOCK, &mask, NULL);
645 } else {
646 waiting = 1;
647 sigprocmask(SIG_UNBLOCK, &mask, NULL);
648 wait_input(timeleft(&timo));
651 waiting = 0;
652 calltimeout();
653 if (got_sighup) {
654 kill_link = 1;
655 got_sighup = 0;
656 if (status != EXIT_HANGUP)
657 status = EXIT_USER_REQUEST;
659 if (got_sigterm) {
660 kill_link = 1;
661 #if 1 // zzz
662 persist = 0;
663 #else
665 * remove by tanghui @ 2006-03-31
666 * don't terminate the process
668 //persist = 0;
669 /*****************************/
670 #endif
671 status = EXIT_USER_REQUEST;
672 got_sigterm = 0;
674 if (got_sigchld) {
675 reap_kids(0); /* Don't leave dead kids lying around */
676 got_sigchld = 0;
678 if (got_sigusr2) {
679 open_ccp_flag = 1;
680 got_sigusr2 = 0;
685 * setup_signals - initialize signal handling.
687 static void
688 setup_signals()
690 struct sigaction sa;
691 sigset_t mask;
694 * Compute mask of all interesting signals and install signal handlers
695 * for each. Only one signal handler may be active at a time. Therefore,
696 * all other signals should be masked when any handler is executing.
698 sigemptyset(&mask);
699 sigaddset(&mask, SIGHUP);
700 sigaddset(&mask, SIGINT);
701 sigaddset(&mask, SIGTERM);
702 sigaddset(&mask, SIGCHLD);
703 sigaddset(&mask, SIGUSR2);
705 #define SIGNAL(s, handler) do { \
706 sa.sa_handler = handler; \
707 if (sigaction(s, &sa, NULL) < 0) \
708 fatal("Couldn't establish signal handler (%d): %m", s); \
709 } while (0)
711 sa.sa_mask = mask;
712 sa.sa_flags = 0;
713 SIGNAL(SIGHUP, hup); /* Hangup */
714 SIGNAL(SIGINT, term); /* Interrupt */
715 SIGNAL(SIGTERM, term); /* Terminate */
716 SIGNAL(SIGCHLD, chld);
718 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
719 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
722 * Install a handler for other signals which would otherwise
723 * cause pppd to exit without cleaning up.
725 SIGNAL(SIGABRT, bad_signal);
726 SIGNAL(SIGALRM, bad_signal);
727 SIGNAL(SIGFPE, bad_signal);
728 SIGNAL(SIGILL, bad_signal);
729 SIGNAL(SIGPIPE, bad_signal);
730 SIGNAL(SIGQUIT, bad_signal);
731 SIGNAL(SIGSEGV, bad_signal);
732 #ifdef SIGBUS
733 SIGNAL(SIGBUS, bad_signal);
734 #endif
735 #ifdef SIGEMT
736 SIGNAL(SIGEMT, bad_signal);
737 #endif
738 #ifdef SIGPOLL
739 SIGNAL(SIGPOLL, bad_signal);
740 #endif
741 #ifdef SIGPROF
742 SIGNAL(SIGPROF, bad_signal);
743 #endif
744 #ifdef SIGSYS
745 SIGNAL(SIGSYS, bad_signal);
746 #endif
747 #ifdef SIGTRAP
748 SIGNAL(SIGTRAP, bad_signal);
749 #endif
750 #ifdef SIGVTALRM
751 SIGNAL(SIGVTALRM, bad_signal);
752 #endif
753 #ifdef SIGXCPU
754 SIGNAL(SIGXCPU, bad_signal);
755 #endif
756 #ifdef SIGXFSZ
757 SIGNAL(SIGXFSZ, bad_signal);
758 #endif
761 * Apparently we can get a SIGPIPE when we call syslog, if
762 * syslogd has died and been restarted. Ignoring it seems
763 * be sufficient.
765 signal(SIGPIPE, SIG_IGN);
769 * set_ifunit - do things we need to do once we know which ppp
770 * unit we are using.
772 void
773 set_ifunit(iskey)
774 int iskey;
776 info("Using interface %s%d", PPP_DRV_NAME, ifunit);
777 slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
778 script_setenv("IFNAME", ifname, iskey);
780 char *arg[3]={_PATH_SETPPPOEPID, ipparam, NULL}; // tallest 1219
781 run_program(_PATH_SETPPPOEPID,arg,0,0,0);
783 if (iskey) {
784 create_pidfile(); /* write pid to file */
785 create_linkpidfile();
790 * detach - detach us from the controlling terminal.
792 void
793 detach()
795 int pid;
796 char numbuf[16];
798 if (detached)
799 return;
800 if ((pid = fork()) < 0) {
801 error("Couldn't detach (fork failed: %m)");
802 die(1); /* or just return? */
804 if (pid != 0) {
805 /* parent */
806 exit(0); /* parent dies */
808 setsid();
809 chdir("/");
810 close(0);
811 close(1);
812 close(2);
813 detached = 1;
814 if (log_default)
815 log_to_fd = -1;
816 /* update pid files if they have been written already */
817 if (pidfilename[0])
818 create_pidfile();
819 if (linkpidfile[0])
820 create_linkpidfile();
821 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
822 script_setenv("PPPD_PID", numbuf, 1);
826 * reopen_log - (re)open our connection to syslog.
828 void
829 reopen_log()
831 #ifdef ULTRIX
832 openlog("pppd", LOG_PID);
833 #else
834 #ifdef MPPPOE_SUPPORT
835 if(!strncmp(ipparam, "0", 1))
836 openlog("pppoe", LOG_PID | LOG_NDELAY, LOG_PPP);
837 else
838 openlog("pppoe-1", LOG_PID | LOG_NDELAY, LOG_PPP);
839 #else
840 openlog("pppoe", LOG_PID | LOG_NDELAY, LOG_PPP);
841 #endif
842 setlogmask(LOG_UPTO(logmask));
843 #endif
847 * Create a file containing our process ID.
849 static void
850 create_pidfile()
852 FILE *pidfile;
854 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
855 _PATH_VARRUN, ifname);
856 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
857 fprintf(pidfile, "%d\n", getpid());
858 (void) fclose(pidfile);
859 } else {
860 error("Failed to create pid file %s: %m", pidfilename);
861 pidfilename[0] = 0;
865 static void
866 create_linkpidfile()
868 FILE *pidfile;
870 if (linkname[0] == 0)
871 return;
872 script_setenv("LINKNAME", linkname, 1);
873 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
874 _PATH_VARRUN, linkname);
875 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
876 fprintf(pidfile, "%d\n", getpid());
877 if (ifname[0])
878 fprintf(pidfile, "%s\n", ifname);
879 (void) fclose(pidfile);
880 } else {
881 error("Failed to create pid file %s: %m", linkpidfile);
882 linkpidfile[0] = 0;
887 * holdoff_end - called via a timeout when the holdoff period ends.
889 static void
890 holdoff_end(arg)
891 void *arg;
893 new_phase(PHASE_DORMANT);
897 * get_input - called when incoming data is available.
899 static void
900 get_input()
902 int len, i;
903 u_char *p;
904 u_short protocol;
905 struct protent *protp;
907 p = inpacket_buf; /* point to beginning of packet buffer */
909 len = read_packet(inpacket_buf);
910 if (len < 0)
911 return;
913 if (len == 0) {
914 notice("Modem hangup");
915 hungup = 1;
916 status = EXIT_HANGUP;
917 lcp_lowerdown(0); /* serial link is no longer available */
918 link_terminated(0);
919 return;
922 if (debug /*&& (debugflags & DBG_INPACKET)*/)
923 dbglog("rcvd %P", p, len);
925 if (len < PPP_HDRLEN) {
926 MAINDEBUG(("io(): Received short packet."));
927 return;
930 p += 2; /* Skip address and control */
931 GETSHORT(protocol, p);
932 len -= PPP_HDRLEN;
935 * Toss all non-LCP packets unless LCP is OPEN.
937 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
938 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
939 return;
943 * Until we get past the authentication phase, toss all packets
944 * except LCP, LQR and authentication packets.
946 if (phase <= PHASE_AUTHENTICATE
947 && !(protocol == PPP_LCP || protocol == PPP_LQR
948 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
949 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
950 protocol, phase));
951 return;
955 * Upcall the proper protocol input routine.
957 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
958 if (protp->protocol == protocol && protp->enabled_flag) {
959 (*protp->input)(0, p, len);
960 return;
962 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
963 && protp->datainput != NULL) {
964 (*protp->datainput)(0, p, len);
965 return;
969 if (debug) {
970 warn("Unsupported protocol 0x%x received", protocol);
972 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
976 * new_phase - signal the start of a new phase of pppd's operation.
978 void
979 new_phase(p)
980 int p;
982 phase = p;
983 if (new_phase_hook)
984 (*new_phase_hook)(p);
988 * die - clean up state and exit with the specified status.
990 void
991 die(status)
992 int status;
994 cleanup();
996 LOGX_INFO("Exiting");
997 exit(status);
1001 * cleanup - restore anything which needs to be restored before we exit
1003 /* ARGSUSED */
1004 static void
1005 cleanup()
1007 sys_cleanup();
1009 if (fd_ppp >= 0)
1010 the_channel->disestablish_ppp(devfd);
1011 if (the_channel->cleanup)
1012 (*the_channel->cleanup)();
1014 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1015 warn("unable to delete pid file %s: %m", pidfilename);
1016 pidfilename[0] = 0;
1017 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1018 warn("unable to delete pid file %s: %m", linkpidfile);
1019 linkpidfile[0] = 0;
1021 unlink(pppoe_disc_file);
1025 * update_link_stats - get stats at link termination.
1027 void
1028 update_link_stats(u)
1029 int u;
1031 struct timeval now;
1032 char numbuf[32];
1034 if (!get_ppp_stats(u, &link_stats)
1035 || my_gettimeofday(&now, NULL) < 0)
1036 return;
1037 link_connect_time = now.tv_sec - start_time.tv_sec;
1038 link_stats_valid = 1;
1040 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1041 script_setenv("CONNECT_TIME", numbuf, 0);
1042 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1043 script_setenv("BYTES_SENT", numbuf, 0);
1044 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1045 script_setenv("BYTES_RCVD", numbuf, 0);
1049 struct callout {
1050 struct timeval c_time; /* time at which to call routine */
1051 void *c_arg; /* argument to routine */
1052 void (*c_func) __P((void *)); /* routine */
1053 struct callout *c_next;
1056 static struct callout *callout = NULL; /* Callout list */
1057 static struct timeval timenow; /* Current time */
1060 * timeout - Schedule a timeout.
1062 * Note that this timeout takes the number of milliseconds, NOT hz (as in
1063 * the kernel).
1065 void
1066 timeout(func, arg, secs, usecs)
1067 void (*func) __P((void *));
1068 void *arg;
1069 int secs, usecs;
1071 struct callout *newp, *p, **pp;
1073 // Compiler error
1074 //MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
1075 // time / 1000, time % 1000));
1078 * Allocate timeout.
1080 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1081 fatal("Out of memory in timeout()!");
1082 newp->c_arg = arg;
1083 newp->c_func = func;
1084 my_gettimeofday(&timenow, NULL);
1085 newp->c_time.tv_sec = timenow.tv_sec + secs;
1086 newp->c_time.tv_usec = timenow.tv_usec + usecs;
1087 if (newp->c_time.tv_usec >= 1000000) {
1088 newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1089 newp->c_time.tv_usec %= 1000000;
1093 * Find correct place and link it in.
1095 for (pp = &callout; (p = *pp); pp = &p->c_next)
1096 if (newp->c_time.tv_sec < p->c_time.tv_sec
1097 || (newp->c_time.tv_sec == p->c_time.tv_sec
1098 && newp->c_time.tv_usec < p->c_time.tv_usec))
1099 break;
1100 newp->c_next = p;
1101 *pp = newp;
1106 * untimeout - Unschedule a timeout.
1108 void
1109 untimeout(func, arg)
1110 void (*func) __P((void *));
1111 void *arg;
1113 struct callout **copp, *freep;
1115 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1118 * Find first matching timeout and remove it from the list.
1120 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1121 if (freep->c_func == func && freep->c_arg == arg) {
1122 *copp = freep->c_next;
1123 free((char *) freep);
1124 break;
1130 * calltimeout - Call any timeout routines which are now due.
1132 static void
1133 calltimeout()
1135 struct callout *p;
1137 while (callout != NULL) {
1138 p = callout;
1140 if (my_gettimeofday(&timenow, NULL) < 0)
1141 fatal("Failed to get time of day: %m");
1142 if (!(p->c_time.tv_sec < timenow.tv_sec
1143 || (p->c_time.tv_sec == timenow.tv_sec
1144 && p->c_time.tv_usec <= timenow.tv_usec)))
1145 break; /* no, it's not time yet */
1147 callout = p->c_next;
1148 (*p->c_func)(p->c_arg);
1150 free((char *) p);
1156 * timeleft - return the length of time until the next timeout is due.
1158 static struct timeval *
1159 timeleft(tvp)
1160 struct timeval *tvp;
1162 if (callout == NULL)
1163 return NULL;
1165 my_gettimeofday(&timenow, NULL);
1166 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1167 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1168 if (tvp->tv_usec < 0) {
1169 tvp->tv_usec += 1000000;
1170 tvp->tv_sec -= 1;
1172 if (tvp->tv_sec < 0)
1173 tvp->tv_sec = tvp->tv_usec = 0;
1175 return tvp;
1180 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1182 static void
1183 kill_my_pg(sig)
1184 int sig;
1186 struct sigaction act, oldact;
1188 act.sa_handler = SIG_IGN;
1189 act.sa_flags = 0;
1190 kill(0, sig);
1191 sigaction(sig, &act, &oldact);
1192 sigaction(sig, &oldact, NULL);
1197 * hup - Catch SIGHUP signal.
1199 * Indicates that the physical layer has been disconnected.
1200 * We don't rely on this indication; if the user has sent this
1201 * signal, we just take the link down.
1203 static void
1204 hup(sig)
1205 int sig;
1207 info("Hangup (SIGHUP)");
1208 got_sighup = 1;
1209 if (conn_running)
1210 /* Send the signal to the [dis]connector process(es) also */
1211 kill_my_pg(sig);
1212 if (waiting)
1213 siglongjmp(sigjmp, 1);
1218 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1220 * Indicates that we should initiate a graceful disconnect and exit.
1222 /*ARGSUSED*/
1223 static void
1224 term(sig)
1225 int sig;
1227 info("Terminating on signal %d.", sig);
1228 got_sigterm = 1;
1229 if (conn_running)
1230 /* Send the signal to the [dis]connector process(es) also */
1231 kill_my_pg(sig);
1232 if (waiting)
1233 siglongjmp(sigjmp, 1);
1238 * chld - Catch SIGCHLD signal.
1239 * Sets a flag so we will call reap_kids in the mainline.
1241 static void
1242 chld(sig)
1243 int sig;
1245 got_sigchld = 1;
1246 if (waiting)
1247 siglongjmp(sigjmp, 1);
1252 * toggle_debug - Catch SIGUSR1 signal.
1254 * Toggle debug flag.
1256 static void toggle_debug(int sig)
1258 debug = !debug;
1259 setlogmask(LOG_UPTO(debug ? LOG_DEBUG : logmask));
1264 * open_ccp - Catch SIGUSR2 signal.
1266 * Try to (re)negotiate compression.
1268 /*ARGSUSED*/
1269 static void
1270 open_ccp(sig)
1271 int sig;
1273 got_sigusr2 = 1;
1274 if (waiting)
1275 siglongjmp(sigjmp, 1);
1280 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1282 static void
1283 bad_signal(sig)
1284 int sig;
1286 static int crashed = 0;
1288 if (crashed)
1289 _exit(127);
1290 crashed = 1;
1292 LOGX_ERROR("Fatal signal %d.", sig);
1294 if (conn_running)
1295 kill_my_pg(SIGTERM);
1296 die(127);
1300 * run-program - execute a program with given arguments,
1301 * but don't wait for it.
1302 * If the program can't be executed, logs an error unless
1303 * must_exist is 0 and the program file doesn't exist.
1304 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1305 * or isn't an executable plain file, or the process ID of the child.
1306 * If done != NULL, (*done)(arg) will be called later (within
1307 * reap_kids) iff the return value is > 0.
1309 pid_t
1310 run_program(prog, args, must_exist, done, arg)
1311 char *prog;
1312 char **args;
1313 int must_exist;
1314 void (*done) __P((void *));
1315 void *arg;
1317 int pid;
1318 struct stat sbuf;
1321 * First check if the file exists and is executable.
1322 * We don't use access() because that would use the
1323 * real user-id, which might not be root, and the script
1324 * might be accessible only to root.
1326 errno = EINVAL;
1327 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1328 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1329 if (must_exist || errno != ENOENT)
1330 warn("Can't execute %s: %m", prog);
1331 return 0;
1334 pid = fork();
1335 if (pid == -1) {
1336 error("Failed to create child process for %s: %m", prog);
1337 return -1;
1339 if (pid == 0) {
1340 int new_fd;
1342 /* Leave the current location */
1343 (void) setsid(); /* No controlling tty. */
1344 (void) umask (S_IRWXG|S_IRWXO);
1345 (void) chdir ("/"); /* no current directory. */
1346 setuid(0); /* set real UID = root */
1347 setgid(getegid());
1349 /* Ensure that nothing of our device environment is inherited. */
1350 sys_close();
1351 closelog();
1352 close (0);
1353 close (1);
1354 close (2);
1355 if (the_channel->close)
1356 (*the_channel->close)();
1358 /* Don't pass handles to the PPP device, even by accident. */
1359 new_fd = open (_PATH_DEVNULL, O_RDWR);
1360 if (new_fd >= 0) {
1361 if (new_fd != 0) {
1362 dup2 (new_fd, 0); /* stdin <- /dev/null */
1363 close (new_fd);
1365 dup2 (0, 1); /* stdout -> /dev/null */
1366 dup2 (0, 2); /* stderr -> /dev/null */
1369 #ifdef BSD
1370 /* Force the priority back to zero if pppd is running higher. */
1371 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1372 warn("can't reset priority to 0: %m");
1373 #endif
1375 /* SysV recommends a second fork at this point. */
1377 /* run the program */
1378 execve(prog, args, script_env);
1379 if (must_exist || errno != ENOENT) {
1380 /* have to reopen the log, there's nowhere else
1381 for the message to go. */
1382 reopen_log();
1383 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1384 closelog();
1386 _exit(-1);
1389 if (debug)
1390 dbglog("Script %s started (pid %d)", prog, pid);
1391 record_child(pid, prog, done, arg);
1392 return pid;
1397 * record_child - add a child process to the list for reap_kids
1398 * to use.
1400 void
1401 record_child(pid, prog, done, arg)
1402 int pid;
1403 char *prog;
1404 void (*done) __P((void *));
1405 void *arg;
1407 struct subprocess *chp;
1409 ++n_children;
1411 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1412 if (chp == NULL) {
1413 warn("losing track of %s process", prog);
1414 } else {
1415 chp->pid = pid;
1416 chp->prog = prog;
1417 chp->done = done;
1418 chp->arg = arg;
1419 chp->next = children;
1420 children = chp;
1426 * reap_kids - get status from any dead child processes,
1427 * and log a message for abnormal terminations.
1429 static int
1430 reap_kids(waitfor)
1431 int waitfor;
1433 int pid, status;
1434 struct subprocess *chp, **prevp;
1436 if (n_children == 0)
1437 return 0;
1438 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1439 && pid != 0) {
1440 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1441 if (chp->pid == pid) {
1442 --n_children;
1443 *prevp = chp->next;
1444 break;
1447 if (WIFSIGNALED(status)) {
1448 warn("Child process %s (pid %d) terminated with signal %d",
1449 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1450 } else if (debug)
1451 dbglog("Script %s finished (pid %d), status = 0x%x",
1452 (chp? chp->prog: "??"), pid, status);
1453 if (chp && chp->done)
1454 (*chp->done)(chp->arg);
1455 if (chp)
1456 free(chp);
1458 if (pid == -1) {
1459 if (errno == ECHILD)
1460 return -1;
1461 if (errno != EINTR)
1462 error("Error waiting for child process: %m");
1464 return 0;
1468 * script_setenv - set an environment variable value to be used
1469 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1471 void
1472 script_setenv(var, value, iskey)
1473 char *var, *value;
1474 int iskey;
1476 size_t varl = strlen(var);
1477 size_t vl = varl + strlen(value) + 2;
1478 int i;
1479 char *p, *newstring;
1481 newstring = (char *) malloc(vl+1);
1482 if (newstring == 0)
1483 return;
1484 *newstring++ = iskey;
1485 slprintf(newstring, vl, "%s=%s", var, value);
1487 /* check if this variable is already set */
1488 if (script_env != 0) {
1489 for (i = 0; (p = script_env[i]) != 0; ++i) {
1490 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1491 if (p[-1] && pppdb != NULL)
1492 delete_db_key(p);
1493 free(p-1);
1494 script_env[i] = newstring;
1495 if (iskey && pppdb != NULL)
1496 add_db_key(newstring);
1497 update_db_entry();
1498 return;
1501 } else {
1502 /* no space allocated for script env. ptrs. yet */
1503 i = 0;
1504 script_env = (char **) malloc(16 * sizeof(char *));
1505 if (script_env == 0)
1506 return;
1507 s_env_nalloc = 16;
1510 /* reallocate script_env with more space if needed */
1511 if (i + 1 >= s_env_nalloc) {
1512 int new_n = i + 17;
1513 char **newenv = (char **) realloc((void *)script_env,
1514 new_n * sizeof(char *));
1515 if (newenv == 0)
1516 return;
1517 script_env = newenv;
1518 s_env_nalloc = new_n;
1521 script_env[i] = newstring;
1522 script_env[i+1] = 0;
1524 if (pppdb != NULL) {
1525 if (iskey)
1526 add_db_key(newstring);
1527 update_db_entry();
1532 * script_unsetenv - remove a variable from the environment
1533 * for scripts.
1535 void
1536 script_unsetenv(var)
1537 char *var;
1539 int vl = strlen(var);
1540 int i;
1541 char *p;
1543 if (script_env == 0)
1544 return;
1545 for (i = 0; (p = script_env[i]) != 0; ++i) {
1546 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1547 if (p[-1] && pppdb != NULL)
1548 delete_db_key(p);
1549 free(p-1);
1550 while ((script_env[i] = script_env[i+1]) != 0)
1551 ++i;
1552 break;
1555 if (pppdb != NULL)
1556 update_db_entry();