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.2 2001/08/08 22:47:15 mhuang 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 */
72 struct channel *the_channel;
74 char *progname; /* Name of this program */
75 char hostname[MAXNAMELEN]; /* Our hostname */
76 static char pidfilename[MAXPATHLEN]; /* name of pid file */
77 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
78 char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
79 uid_t uid; /* Our real user-id */
81 int hungup; /* terminal has been hung up */
82 int privileged; /* we're running as real uid root */
83 int need_holdoff; /* need holdoff period before restarting */
84 int detached; /* have detached from terminal */
85 volatile int status; /* exit status for pppd */
86 int unsuccess; /* # unsuccessful connection attempts */
87 int do_callback; /* != 0 if we should do callback next */
88 int doing_callback; /* != 0 if we are doing callback */
91 int (*holdoff_hook) __P((void)) = NULL;
92 int (*new_phase_hook) __P((int)) = NULL;
94 static int conn_running; /* we have a [dis]connector running */
95 static int devfd; /* fd of underlying device */
96 static int fd_ppp = -1; /* fd for talking PPP */
98 int phase; /* where the link is at */
107 static sigjmp_buf sigjmp;
109 char **script_env; /* Env. variable values for scripts */
110 int s_env_nalloc; /* # words avail at script_env */
112 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
113 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
115 static int n_children; /* # child processes still running */
116 static int got_sigchld; /* set if we have received a SIGCHLD */
118 int privopen; /* don't lock, open device as root */
120 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
122 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
123 int ngroups; /* How many groups valid in groups */
125 static struct timeval start_time; /* Time when link was started. */
127 struct pppd_stats link_stats;
128 int link_connect_time;
129 int link_stats_valid;
132 * We maintain a list of child process pids and
133 * functions to call when they exit.
138 void (*done) __P((void *));
140 struct subprocess *next;
143 static struct subprocess *children;
145 /* Prototypes for procedures local to this file. */
147 static void setup_signals __P((void));
148 static void create_pidfile __P((void));
149 static void create_linkpidfile __P((void));
150 static void cleanup __P((void));
151 static void get_input __P((void));
152 static void calltimeout __P((void));
153 static struct timeval *timeleft __P((struct timeval *));
154 static void kill_my_pg __P((int));
155 static void hup __P((int));
156 static void term __P((int));
157 static void chld __P((int));
158 static void toggle_debug __P((int));
159 static void open_ccp __P((int));
160 static void bad_signal __P((int));
161 static void holdoff_end __P((void *));
162 static int reap_kids __P((int waitfor));
163 #define update_db_entry()
164 #define add_db_key(a)
165 #define delete_db_key(a)
167 static void handle_events __P((void));
169 extern char *ttyname __P((int));
170 extern char *getlogin __P((void));
171 int main __P((int, char *[]));
175 #define O_NONBLOCK O_NDELAY
179 #define setlogmask(x)
183 * PPP Data Link Layer "protocol" table.
184 * One entry per supported protocol.
185 * The last entry must be NULL.
187 struct protent *protocols[] = {
201 * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
203 #if !defined(PPP_DRV_NAME)
204 #define PPP_DRV_NAME "ppp"
205 #endif /* !defined(PPP_DRV_NAME) */
209 pppd_main(argc, argv)
217 struct protent *protp;
220 new_phase(PHASE_INITIALIZE);
223 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
224 * This way we can close 0, 1, 2 in detach() without clobbering
225 * a fd that we are using.
227 if ((i = open("/dev/null", O_RDWR)) >= 0) {
228 while (0 <= i && i <= 2)
236 /* Initialize syslog facilities */
239 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
240 option_error("Couldn't get hostname: %m");
243 hostname[MAXNAMELEN-1] = 0;
245 /* make sure we don't create world or group writable files. */
246 umask(umask(0777) | 022);
249 privileged = uid == 0;
250 slprintf(numbuf, sizeof(numbuf), "%d", uid);
251 script_setenv("ORIG_UID", numbuf, 0);
253 ngroups = getgroups(NGROUPS_MAX, groups);
256 * Initialize magic number generator now so that protocols may
257 * use magic numbers in initialization.
262 * Initialize each protocol.
264 for (i = 0; (protp = protocols[i]) != NULL; ++i)
270 * Parse, in order, the system options file, the user's options file,
271 * and the command line arguments.
274 if (!parse_args(argc, argv))
275 exit(EXIT_OPTION_ERROR);
276 devnam_fixed = 1; /* can no longer change device name */
279 * Work out the device name, if it hasn't already been specified,
280 * and parse the tty's options file.
282 if (the_channel->process_extra_options)
283 (*the_channel->process_extra_options)();
286 setlogmask(LOG_UPTO(LOG_DEBUG));
289 * Check that we are running as root.
291 if (geteuid() != 0) {
292 option_error("must be root to run %s, since it is not setuid-root",
297 if (!ppp_available()) {
298 option_error("%s", no_ppp_msg);
299 exit(EXIT_NO_KERNEL_SUPPORT);
303 * Check that the options given are valid and consistent.
306 if (!sys_check_options())
307 exit(EXIT_OPTION_ERROR);
308 auth_check_options();
309 for (i = 0; (protp = protocols[i]) != NULL; ++i)
310 if (protp->check_options != NULL)
311 (*protp->check_options)();
312 if (the_channel->check_options)
313 (*the_channel->check_options)();
316 if (dump_options || dryrun) {
317 init_pr_log(NULL, LOG_INFO);
318 print_options(pr_log, NULL);
325 * Initialize system-dependent stuff.
330 * Detach ourselves from the terminal, if required,
331 * and identify who is running us.
333 if (!nodetach && !updetach)
338 if (pw != NULL && pw->pw_name != NULL)
343 syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
344 script_setenv("PPPLOGNAME", p, 0);
347 script_setenv("DEVICE", devnam, 1);
348 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
349 script_setenv("PPPD_PID", numbuf, 1);
355 create_linkpidfile();
365 doing_callback = do_callback;
368 new_phase(PHASE_SERIALCONN);
370 devfd = the_channel->connect();
374 /* set up the serial device as a ppp interface */
375 fd_ppp = the_channel->establish_ppp(devfd);
377 status = EXIT_FATAL_ERROR;
381 if (!demand && ifunit >= 0)
385 * Start opening the connection and wait for
386 * incoming events (reply, timeout, etc.).
388 notice("Connect: %s <--> %s", ifname, ppp_devnam);
389 gettimeofday(&start_time, NULL);
390 link_stats_valid = 0;
391 script_unsetenv("CONNECT_TIME");
392 script_unsetenv("BYTES_SENT");
393 script_unsetenv("BYTES_RCVD");
397 lcp_open(0); /* Start protocol */
398 status = EXIT_NEGOTIATION_FAILED;
399 new_phase(PHASE_ESTABLISH);
400 while (phase != PHASE_DEAD) {
404 lcp_close(0, "User request");
407 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
408 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
409 (*ccp_protent.open)(0);
416 * Print connect time and statistics.
418 if (link_stats_valid) {
419 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
420 info("Connect time %d.%d minutes.", t/10, t%10);
421 info("Sent %u bytes, received %u bytes.",
422 link_stats.bytes_out, link_stats.bytes_in);
426 * Delete pid file before disestablishing ppp. Otherwise it
427 * can happen that another pppd gets the same unit and then
428 * we delete its pid file.
431 if (pidfilename[0] != 0
432 && unlink(pidfilename) < 0 && errno != ENOENT)
433 warn("unable to delete pid file %s: %m", pidfilename);
438 * If we may want to bring the link up again, transfer
439 * the ppp unit back to the loopback. Set the
440 * real serial device back to its normal mode of operation.
444 the_channel->disestablish_ppp(devfd);
449 script_unsetenv("IFNAME");
452 * Run disconnector script, if requested.
453 * XXX we may not be able to do this if the line has hung up!
456 new_phase(PHASE_DISCONNECT);
457 the_channel->disconnect();
460 if (the_channel->cleanup)
461 (*the_channel->cleanup)();
464 if (pidfilename[0] != 0
465 && unlink(pidfilename) < 0 && errno != ENOENT)
466 warn("unable to delete pid file %s: %m", pidfilename);
470 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
473 t = need_holdoff? holdoff: 0;
475 t = (*holdoff_hook)();
477 new_phase(PHASE_HOLDOFF);
478 TIMEOUT(holdoff_end, NULL, t);
482 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
483 } while (phase == PHASE_HOLDOFF);
489 /* Wait for scripts to finish */
490 /* XXX should have a timeout here */
491 while (n_children > 0) {
493 struct subprocess *chp;
494 dbglog("Waiting for %d child processes...", n_children);
495 for (chp = children; chp != NULL; chp = chp->next)
496 dbglog(" script %s, pid %d", chp->prog, chp->pid);
498 if (reap_kids(1) < 0)
507 * handle_events - wait for something to happen and respond to it.
515 kill_link = open_ccp_flag = 0;
516 if (sigsetjmp(sigjmp, 1) == 0) {
517 sigprocmask(SIG_BLOCK, &mask, NULL);
518 if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
519 sigprocmask(SIG_UNBLOCK, &mask, NULL);
522 sigprocmask(SIG_UNBLOCK, &mask, NULL);
523 wait_input(timeleft(&timo));
531 if (status != EXIT_HANGUP)
532 status = EXIT_USER_REQUEST;
537 status = EXIT_USER_REQUEST;
541 reap_kids(0); /* Don't leave dead kids lying around */
551 * setup_signals - initialize signal handling.
560 * Compute mask of all interesting signals and install signal handlers
561 * for each. Only one signal handler may be active at a time. Therefore,
562 * all other signals should be masked when any handler is executing.
565 sigaddset(&mask, SIGHUP);
566 sigaddset(&mask, SIGINT);
567 sigaddset(&mask, SIGTERM);
568 sigaddset(&mask, SIGCHLD);
569 sigaddset(&mask, SIGUSR2);
571 #define SIGNAL(s, handler) do { \
572 sa.sa_handler = handler; \
573 if (sigaction(s, &sa, NULL) < 0) \
574 fatal("Couldn't establish signal handler (%d): %m", s); \
579 SIGNAL(SIGHUP, hup); /* Hangup */
580 SIGNAL(SIGINT, term); /* Interrupt */
581 SIGNAL(SIGTERM, term); /* Terminate */
582 SIGNAL(SIGCHLD, chld);
584 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
585 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
588 * Install a handler for other signals which would otherwise
589 * cause pppd to exit without cleaning up.
591 SIGNAL(SIGABRT, bad_signal);
592 SIGNAL(SIGALRM, bad_signal);
593 SIGNAL(SIGFPE, bad_signal);
594 SIGNAL(SIGILL, bad_signal);
595 SIGNAL(SIGPIPE, bad_signal);
596 SIGNAL(SIGQUIT, bad_signal);
597 SIGNAL(SIGSEGV, bad_signal);
599 SIGNAL(SIGBUS, bad_signal);
602 SIGNAL(SIGEMT, bad_signal);
605 SIGNAL(SIGPOLL, bad_signal);
608 SIGNAL(SIGPROF, bad_signal);
611 SIGNAL(SIGSYS, bad_signal);
614 SIGNAL(SIGTRAP, bad_signal);
617 SIGNAL(SIGVTALRM, bad_signal);
620 SIGNAL(SIGXCPU, bad_signal);
623 SIGNAL(SIGXFSZ, bad_signal);
627 * Apparently we can get a SIGPIPE when we call syslog, if
628 * syslogd has died and been restarted. Ignoring it seems
631 signal(SIGPIPE, SIG_IGN);
635 * set_ifunit - do things we need to do once we know which ppp
642 info("Using interface %s%d", PPP_DRV_NAME, ifunit);
643 slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
644 script_setenv("IFNAME", ifname, iskey);
646 create_pidfile(); /* write pid to file */
647 create_linkpidfile();
652 * detach - detach us from the controlling terminal.
662 if ((pid = fork()) < 0) {
663 error("Couldn't detach (fork failed: %m)");
664 die(1); /* or just return? */
668 exit(0); /* parent dies */
678 /* update pid files if they have been written already */
682 create_linkpidfile();
683 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
684 script_setenv("PPPD_PID", numbuf, 1);
688 * reopen_log - (re)open our connection to syslog.
694 openlog("pppd", LOG_PID);
696 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
697 setlogmask(LOG_UPTO(LOG_INFO));
702 * Create a file containing our process ID.
709 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
710 _PATH_VARRUN, ifname);
711 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
712 fprintf(pidfile, "%d\n", getpid());
713 (void) fclose(pidfile);
715 error("Failed to create pid file %s: %m", pidfilename);
725 if (linkname[0] == 0)
727 script_setenv("LINKNAME", linkname, 1);
728 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
729 _PATH_VARRUN, linkname);
730 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
731 fprintf(pidfile, "%d\n", getpid());
733 fprintf(pidfile, "%s\n", ifname);
734 (void) fclose(pidfile);
736 error("Failed to create pid file %s: %m", linkpidfile);
742 * holdoff_end - called via a timeout when the holdoff period ends.
748 new_phase(PHASE_DORMANT);
752 * get_input - called when incoming data is available.
760 struct protent *protp;
762 p = inpacket_buf; /* point to beginning of packet buffer */
764 len = read_packet(inpacket_buf);
769 notice("Modem hangup");
771 status = EXIT_HANGUP;
772 lcp_lowerdown(0); /* serial link is no longer available */
777 if (debug /*&& (debugflags & DBG_INPACKET)*/)
778 dbglog("rcvd %P", p, len);
780 if (len < PPP_HDRLEN) {
781 MAINDEBUG(("io(): Received short packet."));
785 p += 2; /* Skip address and control */
786 GETSHORT(protocol, p);
790 * Toss all non-LCP packets unless LCP is OPEN.
792 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
793 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
798 * Until we get past the authentication phase, toss all packets
799 * except LCP, LQR and authentication packets.
801 if (phase <= PHASE_AUTHENTICATE
802 && !(protocol == PPP_LCP || protocol == PPP_LQR
803 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
804 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
810 * Upcall the proper protocol input routine.
812 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
813 if (protp->protocol == protocol && protp->enabled_flag) {
814 (*protp->input)(0, p, len);
817 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
818 && protp->datainput != NULL) {
819 (*protp->datainput)(0, p, len);
825 warn("Unsupported protocol 0x%x received", protocol);
827 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
831 * new_phase - signal the start of a new phase of pppd's operation.
839 (*new_phase_hook)(p);
843 * die - clean up state and exit with the specified status.
850 syslog(LOG_INFO, "Exit.");
855 * cleanup - restore anything which needs to be restored before we exit
864 the_channel->disestablish_ppp(devfd);
865 if (the_channel->cleanup)
866 (*the_channel->cleanup)();
868 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
869 warn("unable to delete pid file %s: %m", pidfilename);
871 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
872 warn("unable to delete pid file %s: %m", linkpidfile);
877 * update_link_stats - get stats at link termination.
886 if (!get_ppp_stats(u, &link_stats)
887 || gettimeofday(&now, NULL) < 0)
889 link_connect_time = now.tv_sec - start_time.tv_sec;
890 link_stats_valid = 1;
892 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
893 script_setenv("CONNECT_TIME", numbuf, 0);
894 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
895 script_setenv("BYTES_SENT", numbuf, 0);
896 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
897 script_setenv("BYTES_RCVD", numbuf, 0);
902 struct timeval c_time; /* time at which to call routine */
903 void *c_arg; /* argument to routine */
904 void (*c_func) __P((void *)); /* routine */
905 struct callout *c_next;
908 static struct callout *callout = NULL; /* Callout list */
909 static struct timeval timenow; /* Current time */
912 * timeout - Schedule a timeout.
914 * Note that this timeout takes the number of milliseconds, NOT hz (as in
918 timeout(func, arg, secs, usecs)
919 void (*func) __P((void *));
923 struct callout *newp, *p, **pp;
925 MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
926 time / 1000, time % 1000));
931 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
932 fatal("Out of memory in timeout()!");
935 gettimeofday(&timenow, NULL);
936 newp->c_time.tv_sec = timenow.tv_sec + secs;
937 newp->c_time.tv_usec = timenow.tv_usec + usecs;
938 if (newp->c_time.tv_usec >= 1000000) {
939 newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
940 newp->c_time.tv_usec %= 1000000;
944 * Find correct place and link it in.
946 for (pp = &callout; (p = *pp); pp = &p->c_next)
947 if (newp->c_time.tv_sec < p->c_time.tv_sec
948 || (newp->c_time.tv_sec == p->c_time.tv_sec
949 && newp->c_time.tv_usec < p->c_time.tv_usec))
957 * untimeout - Unschedule a timeout.
961 void (*func) __P((void *));
964 struct callout **copp, *freep;
966 MAINDEBUG(("Untimeout %p:%p.", func, arg));
969 * Find first matching timeout and remove it from the list.
971 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
972 if (freep->c_func == func && freep->c_arg == arg) {
973 *copp = freep->c_next;
974 free((char *) freep);
981 * calltimeout - Call any timeout routines which are now due.
988 while (callout != NULL) {
991 if (gettimeofday(&timenow, NULL) < 0)
992 fatal("Failed to get time of day: %m");
993 if (!(p->c_time.tv_sec < timenow.tv_sec
994 || (p->c_time.tv_sec == timenow.tv_sec
995 && p->c_time.tv_usec <= timenow.tv_usec)))
996 break; /* no, it's not time yet */
999 (*p->c_func)(p->c_arg);
1007 * timeleft - return the length of time until the next timeout is due.
1009 static struct timeval *
1011 struct timeval *tvp;
1013 if (callout == NULL)
1016 gettimeofday(&timenow, NULL);
1017 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1018 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1019 if (tvp->tv_usec < 0) {
1020 tvp->tv_usec += 1000000;
1023 if (tvp->tv_sec < 0)
1024 tvp->tv_sec = tvp->tv_usec = 0;
1031 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1037 struct sigaction act, oldact;
1039 act.sa_handler = SIG_IGN;
1042 sigaction(sig, &act, &oldact);
1043 sigaction(sig, &oldact, NULL);
1048 * hup - Catch SIGHUP signal.
1050 * Indicates that the physical layer has been disconnected.
1051 * We don't rely on this indication; if the user has sent this
1052 * signal, we just take the link down.
1058 info("Hangup (SIGHUP)");
1061 /* Send the signal to the [dis]connector process(es) also */
1064 siglongjmp(sigjmp, 1);
1069 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1071 * Indicates that we should initiate a graceful disconnect and exit.
1078 info("Terminating on signal %d.", sig);
1081 /* Send the signal to the [dis]connector process(es) also */
1084 siglongjmp(sigjmp, 1);
1089 * chld - Catch SIGCHLD signal.
1090 * Sets a flag so we will call reap_kids in the mainline.
1098 siglongjmp(sigjmp, 1);
1103 * toggle_debug - Catch SIGUSR1 signal.
1105 * Toggle debug flag.
1114 setlogmask(LOG_UPTO(LOG_DEBUG));
1116 setlogmask(LOG_UPTO(LOG_WARNING));
1122 * open_ccp - Catch SIGUSR2 signal.
1124 * Try to (re)negotiate compression.
1133 siglongjmp(sigjmp, 1);
1138 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1144 static int crashed = 0;
1149 error("Fatal signal %d", sig);
1151 kill_my_pg(SIGTERM);
1156 * run-program - execute a program with given arguments,
1157 * but don't wait for it.
1158 * If the program can't be executed, logs an error unless
1159 * must_exist is 0 and the program file doesn't exist.
1160 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1161 * or isn't an executable plain file, or the process ID of the child.
1162 * If done != NULL, (*done)(arg) will be called later (within
1163 * reap_kids) iff the return value is > 0.
1166 run_program(prog, args, must_exist, done, arg)
1170 void (*done) __P((void *));
1177 * First check if the file exists and is executable.
1178 * We don't use access() because that would use the
1179 * real user-id, which might not be root, and the script
1180 * might be accessible only to root.
1183 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1184 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1185 if (must_exist || errno != ENOENT)
1186 warn("Can't execute %s: %m", prog);
1192 error("Failed to create child process for %s: %m", prog);
1198 /* Leave the current location */
1199 (void) setsid(); /* No controlling tty. */
1200 (void) umask (S_IRWXG|S_IRWXO);
1201 (void) chdir ("/"); /* no current directory. */
1202 setuid(0); /* set real UID = root */
1205 /* Ensure that nothing of our device environment is inherited. */
1211 if (the_channel->close)
1212 (*the_channel->close)();
1214 /* Don't pass handles to the PPP device, even by accident. */
1215 new_fd = open (_PATH_DEVNULL, O_RDWR);
1218 dup2 (new_fd, 0); /* stdin <- /dev/null */
1221 dup2 (0, 1); /* stdout -> /dev/null */
1222 dup2 (0, 2); /* stderr -> /dev/null */
1226 /* Force the priority back to zero if pppd is running higher. */
1227 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1228 warn("can't reset priority to 0: %m");
1231 /* SysV recommends a second fork at this point. */
1233 /* run the program */
1234 execve(prog, args, script_env);
1235 if (must_exist || errno != ENOENT) {
1236 /* have to reopen the log, there's nowhere else
1237 for the message to go. */
1239 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1246 dbglog("Script %s started (pid %d)", prog, pid);
1247 record_child(pid, prog, done, arg);
1254 * record_child - add a child process to the list for reap_kids
1258 record_child(pid, prog, done, arg)
1261 void (*done) __P((void *));
1264 struct subprocess *chp;
1268 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1270 warn("losing track of %s process", prog);
1276 chp->next = children;
1283 * reap_kids - get status from any dead child processes,
1284 * and log a message for abnormal terminations.
1291 struct subprocess *chp, **prevp;
1293 if (n_children == 0)
1295 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1297 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1298 if (chp->pid == pid) {
1304 if (WIFSIGNALED(status)) {
1305 warn("Child process %s (pid %d) terminated with signal %d",
1306 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1308 dbglog("Script %s finished (pid %d), status = 0x%x",
1309 (chp? chp->prog: "??"), pid, status);
1310 if (chp && chp->done)
1311 (*chp->done)(chp->arg);
1316 if (errno == ECHILD)
1319 error("Error waiting for child process: %m");
1325 * script_setenv - set an environment variable value to be used
1326 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1329 script_setenv(var, value, iskey)
1333 size_t varl = strlen(var);
1334 size_t vl = varl + strlen(value) + 2;
1336 char *p, *newstring;
1338 newstring = (char *) malloc(vl+1);
1341 *newstring++ = iskey;
1342 slprintf(newstring, vl, "%s=%s", var, value);
1344 /* check if this variable is already set */
1345 if (script_env != 0) {
1346 for (i = 0; (p = script_env[i]) != 0; ++i) {
1347 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1348 if (p[-1] && pppdb != NULL)
1351 script_env[i] = newstring;
1352 if (iskey && pppdb != NULL)
1353 add_db_key(newstring);
1359 /* no space allocated for script env. ptrs. yet */
1361 script_env = (char **) malloc(16 * sizeof(char *));
1362 if (script_env == 0)
1367 /* reallocate script_env with more space if needed */
1368 if (i + 1 >= s_env_nalloc) {
1370 char **newenv = (char **) realloc((void *)script_env,
1371 new_n * sizeof(char *));
1374 script_env = newenv;
1375 s_env_nalloc = new_n;
1378 script_env[i] = newstring;
1379 script_env[i+1] = 0;
1381 if (pppdb != NULL) {
1383 add_db_key(newstring);
1389 * script_unsetenv - remove a variable from the environment
1393 script_unsetenv(var)
1396 int vl = strlen(var);
1400 if (script_env == 0)
1402 for (i = 0; (p = script_env[i]) != 0; ++i) {
1403 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1404 if (p[-1] && pppdb != NULL)
1407 while ((script_env[i] = script_env[i+1]) != 0)