2 * main.c - Point-to-Point Protocol main module
4 * Copyright (c) 1989 Carnegie Mellon University.
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 $"
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
53 #include "pathnames.h"
61 #endif /* IPX_CHANGE */
66 static const char rcsid
[] = RCSID
;
69 char ifname
[32]; /* Interface name */
70 int ifunit
; /* Interface unit number */
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 */
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 */
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.
143 void (*done
) __P((void *));
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)
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
183 #define O_NONBLOCK O_NDELAY
187 #define setlogmask(x)
191 * PPP Data Link Layer "protocol" table.
192 * One entry per supported protocol.
193 * The last entry must be NULL.
195 struct protent
*protocols
[] = {
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)
222 return (stat(name, &st) == 0);
234 struct protent
*protp
;
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)
253 /* Initialize syslog facilities */
256 if (gethostname(hostname
, MAXNAMELEN
) < 0 ) {
257 LOGX_ERROR("Couldn't get hostname");
258 option_error("Couldn't get hostname: %m");
261 hostname
[MAXNAMELEN
-1] = 0;
263 /* make sure we don't create world or group writable files. */
264 umask(umask(0777) | 022);
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.
280 * Initialize each protocol.
282 for (i
= 0; (protp
= protocols
[i
]) != NULL
; ++i
)
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
)();
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",
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.
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
);
345 * Initialize system-dependent stuff.
350 * Initialize random seed.
355 * Detach ourselves from the terminal, if required,
356 * and identify who is running us.
358 if (!nodetach
&& !updetach
)
363 if (pw
!= NULL
&& pw
->pw_name
!= NULL
)
369 LOGX_INFO("Starting");
370 LOGX_DEBUG("demand=%d", demand
);
372 script_setenv("PPPLOGNAME", p
, 0);
375 script_setenv("DEVICE", devnam
, 1);
376 slprintf(numbuf
, sizeof(numbuf
), "%d", getpid());
377 script_setenv("PPPD_PID", numbuf
, 1);
383 create_linkpidfile();
386 * If we're doing dial-on-demand, set up the interface now.
390 * Open the loopback channel and set it up to be the ppp interface.
392 fd_loop
= open_ppp_loopback();
396 * Configure the interface and mark it up, etc.
411 doing_callback
= do_callback
;
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
);
424 if (kill_link
&& !persist
)
426 if (get_loop_output()) {
431 if (kill_link
&& !persist
) {
432 LOGX_DEBUG("%s: (kill_link && !persist)", __FUNCTION__
);
437 * Now we want to bring up the link.
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
);
448 redial_immediately
= 0;
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
);
456 status
= EXIT_FATAL_ERROR
;
460 if (!demand
&& ifunit
>= 0)
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");
476 lcp_open(0); /* Start protocol */
477 status
= EXIT_NEGOTIATION_FAILED
;
478 new_phase(PHASE_ESTABLISH
);
479 while (phase
!= PHASE_DEAD
) {
483 lcp_close(0, "User request");
486 if (phase
== PHASE_NETWORK
|| phase
== PHASE_RUNNING
) {
487 ccp_fsm
[0].flags
= OPT_RESTART
; /* clears OPT_SILENT */
488 (*ccp_protent
.open
)(0);
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.
512 if (pidfilename
[0] != 0
513 && unlink(pidfilename
) < 0 && errno
!= ENOENT
)
514 warn("unable to delete pid file %s: %m", pidfilename
);
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.
525 the_channel
->disestablish_ppp(devfd
);
530 script_unsetenv("IFNAME");
533 LOGX_DEBUG("%s: disconnect", __FUNCTION__
);
539 new_phase(PHASE_DISCONNECT
);
540 the_channel
->disconnect();
542 if (the_channel
->cleanup
)
543 (*the_channel
->cleanup
)();
546 if (pidfilename
[0] != 0
547 && unlink(pidfilename
) < 0 && errno
!= ENOENT
)
548 warn("unable to delete pid file %s: %m", pidfilename
);
552 if (!persist
|| (maxfail
> 0 && unsuccess
>= maxfail
))
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
)
576 holdoff
= (int)(3 + (((retransmit_time
- 3.0) * rand())/ (RAND_MAX
+ 1.0)));
577 if((holdoff
> 93) && (holdoff
> retransmit_time
- 90))
581 //holdoff = 3 + gen_random_int(retransmit_time - 3);
592 t
= 10; //modified from 0 to 10 //by crazy 20070508
593 redial_immediately
= 0;
596 LOGX_DEBUG("%s: t=%d", __FUNCTION__
, t
);
599 new_phase(PHASE_HOLDOFF
);
600 TIMEOUT(holdoff_end
, NULL
, t
);
604 new_phase(PHASE_DORMANT
); /* allow signal to end holdoff */
605 } while (phase
== PHASE_HOLDOFF
);
611 LOGX_DEBUG("%s: !need_holdoff", __FUNCTION__
);
615 /* Wait for scripts to finish */
616 while (n_children
> 0) {
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)
632 * handle_events - wait for something to happen and respond to it.
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
);
647 sigprocmask(SIG_UNBLOCK
, &mask
, NULL
);
648 wait_input(timeleft(&timo
));
656 if (status
!= EXIT_HANGUP
)
657 status
= EXIT_USER_REQUEST
;
665 * remove by tanghui @ 2006-03-31
666 * don't terminate the process
669 /*****************************/
671 status
= EXIT_USER_REQUEST
;
675 reap_kids(0); /* Don't leave dead kids lying around */
685 * setup_signals - initialize signal handling.
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.
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); \
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
);
733 SIGNAL(SIGBUS
, bad_signal
);
736 SIGNAL(SIGEMT
, bad_signal
);
739 SIGNAL(SIGPOLL
, bad_signal
);
742 SIGNAL(SIGPROF
, bad_signal
);
745 SIGNAL(SIGSYS
, bad_signal
);
748 SIGNAL(SIGTRAP
, bad_signal
);
751 SIGNAL(SIGVTALRM
, bad_signal
);
754 SIGNAL(SIGXCPU
, bad_signal
);
757 SIGNAL(SIGXFSZ
, bad_signal
);
761 * Apparently we can get a SIGPIPE when we call syslog, if
762 * syslogd has died and been restarted. Ignoring it seems
765 signal(SIGPIPE
, SIG_IGN
);
769 * set_ifunit - do things we need to do once we know which ppp
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);
784 create_pidfile(); /* write pid to file */
785 create_linkpidfile();
790 * detach - detach us from the controlling terminal.
800 if ((pid
= fork()) < 0) {
801 error("Couldn't detach (fork failed: %m)");
802 die(1); /* or just return? */
806 exit(0); /* parent dies */
816 /* update pid files if they have been written already */
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.
832 openlog("pppd", LOG_PID
);
834 #ifdef MPPPOE_SUPPORT
835 if(!strncmp(ipparam
, "0", 1))
836 openlog("pppoe", LOG_PID
| LOG_NDELAY
, LOG_PPP
);
838 openlog("pppoe-1", LOG_PID
| LOG_NDELAY
, LOG_PPP
);
840 openlog("pppoe", LOG_PID
| LOG_NDELAY
, LOG_PPP
);
842 setlogmask(LOG_UPTO(logmask
));
847 * Create a file containing our process ID.
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
);
860 error("Failed to create pid file %s: %m", pidfilename
);
870 if (linkname
[0] == 0)
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());
878 fprintf(pidfile
, "%s\n", ifname
);
879 (void) fclose(pidfile
);
881 error("Failed to create pid file %s: %m", linkpidfile
);
887 * holdoff_end - called via a timeout when the holdoff period ends.
893 new_phase(PHASE_DORMANT
);
897 * get_input - called when incoming data is available.
905 struct protent
*protp
;
907 p
= inpacket_buf
; /* point to beginning of packet buffer */
909 len
= read_packet(inpacket_buf
);
914 notice("Modem hangup");
916 status
= EXIT_HANGUP
;
917 lcp_lowerdown(0); /* serial link is no longer available */
922 if (debug
/*&& (debugflags & DBG_INPACKET)*/)
923 dbglog("rcvd %P", p
, len
);
925 if (len
< PPP_HDRLEN
) {
926 MAINDEBUG(("io(): Received short packet."));
930 p
+= 2; /* Skip address and control */
931 GETSHORT(protocol
, p
);
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."));
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",
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
);
962 if (protocol
== (protp
->protocol
& ~0x8000) && protp
->enabled_flag
963 && protp
->datainput
!= NULL
) {
964 (*protp
->datainput
)(0, p
, len
);
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.
984 (*new_phase_hook
)(p
);
988 * die - clean up state and exit with the specified status.
996 LOGX_INFO("Exiting");
1001 * cleanup - restore anything which needs to be restored before we exit
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
);
1017 if (linkpidfile
[0] != 0 && unlink(linkpidfile
) < 0 && errno
!= ENOENT
)
1018 warn("unable to delete pid file %s: %m", linkpidfile
);
1021 unlink(pppoe_disc_file
);
1025 * update_link_stats - get stats at link termination.
1028 update_link_stats(u
)
1034 if (!get_ppp_stats(u
, &link_stats
)
1035 || my_gettimeofday(&now
, NULL
) < 0)
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);
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
1066 timeout(func
, arg
, secs
, usecs
)
1067 void (*func
) __P((void *));
1071 struct callout
*newp
, *p
, **pp
;
1074 //MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
1075 // time / 1000, time % 1000));
1080 if ((newp
= (struct callout
*) malloc(sizeof(struct callout
))) == NULL
)
1081 fatal("Out of memory in timeout()!");
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
))
1106 * untimeout - Unschedule a timeout.
1109 untimeout(func
, arg
)
1110 void (*func
) __P((void *));
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
);
1130 * calltimeout - Call any timeout routines which are now due.
1137 while (callout
!= NULL
) {
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
);
1156 * timeleft - return the length of time until the next timeout is due.
1158 static struct timeval
*
1160 struct timeval
*tvp
;
1162 if (callout
== 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;
1172 if (tvp
->tv_sec
< 0)
1173 tvp
->tv_sec
= tvp
->tv_usec
= 0;
1180 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1186 struct sigaction act
, oldact
;
1188 act
.sa_handler
= SIG_IGN
;
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.
1207 info("Hangup (SIGHUP)");
1210 /* Send the signal to the [dis]connector process(es) also */
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.
1227 info("Terminating on signal %d.", sig
);
1230 /* Send the signal to the [dis]connector process(es) also */
1233 siglongjmp(sigjmp
, 1);
1238 * chld - Catch SIGCHLD signal.
1239 * Sets a flag so we will call reap_kids in the mainline.
1247 siglongjmp(sigjmp
, 1);
1252 * toggle_debug - Catch SIGUSR1 signal.
1254 * Toggle debug flag.
1256 static void toggle_debug(int sig
)
1259 setlogmask(LOG_UPTO(debug
? LOG_DEBUG
: logmask
));
1264 * open_ccp - Catch SIGUSR2 signal.
1266 * Try to (re)negotiate compression.
1275 siglongjmp(sigjmp
, 1);
1280 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1286 static int crashed
= 0;
1292 LOGX_ERROR("Fatal signal %d.", sig
);
1295 kill_my_pg(SIGTERM
);
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.
1310 run_program(prog
, args
, must_exist
, done
, arg
)
1314 void (*done
) __P((void *));
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.
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
);
1336 error("Failed to create child process for %s: %m", prog
);
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 */
1349 /* Ensure that nothing of our device environment is inherited. */
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
);
1362 dup2 (new_fd
, 0); /* stdin <- /dev/null */
1365 dup2 (0, 1); /* stdout -> /dev/null */
1366 dup2 (0, 2); /* stderr -> /dev/null */
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");
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. */
1383 syslog(LOG_ERR
, "Can't execute %s: %m", prog
);
1390 dbglog("Script %s started (pid %d)", prog
, pid
);
1391 record_child(pid
, prog
, done
, arg
);
1397 * record_child - add a child process to the list for reap_kids
1401 record_child(pid
, prog
, done
, arg
)
1404 void (*done
) __P((void *));
1407 struct subprocess
*chp
;
1411 chp
= (struct subprocess
*) malloc(sizeof(struct subprocess
));
1413 warn("losing track of %s process", prog
);
1419 chp
->next
= children
;
1426 * reap_kids - get status from any dead child processes,
1427 * and log a message for abnormal terminations.
1434 struct subprocess
*chp
, **prevp
;
1436 if (n_children
== 0)
1438 while ((pid
= waitpid(-1, &status
, (waitfor
? 0: WNOHANG
))) != -1
1440 for (prevp
= &children
; (chp
= *prevp
) != NULL
; prevp
= &chp
->next
) {
1441 if (chp
->pid
== pid
) {
1447 if (WIFSIGNALED(status
)) {
1448 warn("Child process %s (pid %d) terminated with signal %d",
1449 (chp
? chp
->prog
: "??"), pid
, WTERMSIG(status
));
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
);
1459 if (errno
== ECHILD
)
1462 error("Error waiting for child process: %m");
1468 * script_setenv - set an environment variable value to be used
1469 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1472 script_setenv(var
, value
, iskey
)
1476 size_t varl
= strlen(var
);
1477 size_t vl
= varl
+ strlen(value
) + 2;
1479 char *p
, *newstring
;
1481 newstring
= (char *) malloc(vl
+1);
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
)
1494 script_env
[i
] = newstring
;
1495 if (iskey
&& pppdb
!= NULL
)
1496 add_db_key(newstring
);
1502 /* no space allocated for script env. ptrs. yet */
1504 script_env
= (char **) malloc(16 * sizeof(char *));
1505 if (script_env
== 0)
1510 /* reallocate script_env with more space if needed */
1511 if (i
+ 1 >= s_env_nalloc
) {
1513 char **newenv
= (char **) realloc((void *)script_env
,
1514 new_n
* sizeof(char *));
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
) {
1526 add_db_key(newstring
);
1532 * script_unsetenv - remove a variable from the environment
1536 script_unsetenv(var
)
1539 int vl
= strlen(var
);
1543 if (script_env
== 0)
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
)
1550 while ((script_env
[i
] = script_env
[i
+1]) != 0)