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.119 2002/11/02 19:48:12 carlsonj 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>
58 #include "pathnames.h"
70 #endif /* IPX_CHANGE */
75 static const char rcsid[] = RCSID;
78 char ifname[32]; /* Interface name */
79 int ifunit; /* Interface unit number */
81 struct channel *the_channel;
83 char *progname; /* Name of this program */
84 char hostname[MAXNAMELEN]; /* Our hostname */
85 static char pidfilename[MAXPATHLEN]; /* name of pid file */
86 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
87 char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
88 uid_t uid; /* Our real user-id */
89 struct notifier *pidchange = NULL;
90 struct notifier *phasechange = NULL;
91 struct notifier *exitnotify = NULL;
92 struct notifier *sigreceived = NULL;
94 int hungup; /* terminal has been hung up */
95 int privileged; /* we're running as real uid root */
96 int need_holdoff; /* need holdoff period before restarting */
97 int detached; /* have detached from terminal */
98 volatile int status; /* exit status for pppd */
99 int unsuccess; /* # unsuccessful connection attempts */
100 int do_callback; /* != 0 if we should do callback next */
101 int doing_callback; /* != 0 if we are doing callback */
102 int ppp_session_number; /* Session number, for channels with such a
103 concept (eg PPPoE) */
105 TDB_CONTEXT *pppdb; /* database for storing status etc. */
110 int (*holdoff_hook) __P((void)) = NULL;
111 int (*new_phase_hook) __P((int)) = NULL;
112 void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
113 void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
115 static int conn_running; /* we have a [dis]connector running */
116 static int devfd; /* fd of underlying device */
117 static int fd_ppp = -1; /* fd for talking PPP */
118 static int fd_loop; /* fd for getting demand-dial packets */
120 int phase; /* where the link is at */
129 static sigjmp_buf sigjmp;
131 char **script_env; /* Env. variable values for scripts */
132 int s_env_nalloc; /* # words avail at script_env */
134 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
135 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
137 static int n_children; /* # child processes still running */
138 static int got_sigchld; /* set if we have received a SIGCHLD */
140 int privopen; /* don't lock, open device as root */
142 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
144 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
145 int ngroups; /* How many groups valid in groups */
147 static struct timeval start_time; /* Time when link was started. */
149 struct pppd_stats link_stats;
150 unsigned link_connect_time;
151 int link_stats_valid;
154 * We maintain a list of child process pids and
155 * functions to call when they exit.
160 void (*done) __P((void *));
162 struct subprocess *next;
165 static struct subprocess *children;
167 /* Prototypes for procedures local to this file. */
169 static void setup_signals __P((void));
170 static void create_pidfile __P((void));
171 static void create_linkpidfile __P((void));
172 static void cleanup __P((void));
173 static void get_input __P((void));
174 static void calltimeout __P((void));
175 static struct timeval *timeleft __P((struct timeval *));
176 static void kill_my_pg __P((int));
177 static void hup __P((int));
178 static void term __P((int));
179 static void chld __P((int));
180 static void toggle_debug __P((int));
181 static void open_ccp __P((int));
182 static void bad_signal __P((int));
183 static void holdoff_end __P((void *));
184 static int reap_kids __P((int waitfor));
187 static void update_db_entry __P((void));
188 static void add_db_key __P((const char *));
189 static void delete_db_key __P((const char *));
190 static void cleanup_db __P((void));
193 static void handle_events __P((void));
194 static void print_link_stats __P((void));
196 extern char *ttyname __P((int));
197 extern char *getlogin __P((void));
198 int main __P((int, char *[]));
202 #define O_NONBLOCK O_NDELAY
206 #define setlogmask(x)
210 * PPP Data Link Layer "protocol" table.
211 * One entry per supported protocol.
212 * The last entry must be NULL.
214 struct protent *protocols[] = {
238 * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
240 #if !defined(PPP_DRV_NAME)
241 #define PPP_DRV_NAME "ppp"
242 #endif /* !defined(PPP_DRV_NAME) */
252 struct protent *protp;
255 link_stats_valid = 0;
256 new_phase(PHASE_INITIALIZE);
259 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
260 * This way we can close 0, 1, 2 in detach() without clobbering
261 * a fd that we are using.
263 if ((i = open("/dev/null", O_RDWR)) >= 0) {
264 while (0 <= i && i <= 2)
272 /* Initialize syslog facilities */
275 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
276 option_error("Couldn't get hostname: %m");
279 hostname[MAXNAMELEN-1] = 0;
281 /* make sure we don't create world or group writable files. */
282 umask(umask(0777) | 022);
285 privileged = uid == 0;
286 slprintf(numbuf, sizeof(numbuf), "%d", uid);
287 script_setenv("ORIG_UID", numbuf, 0);
289 ngroups = getgroups(NGROUPS_MAX, groups);
292 * Initialize magic number generator now so that protocols may
293 * use magic numbers in initialization.
298 * Initialize each protocol.
300 for (i = 0; (protp = protocols[i]) != NULL; ++i)
304 * Initialize the default channel.
311 * Parse, in order, the system options file, the user's options file,
312 * and the command line arguments.
314 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
315 || !options_from_user()
316 || !parse_args(argc-1, argv+1))
317 exit(EXIT_OPTION_ERROR);
318 devnam_fixed = 1; /* can no longer change device name */
321 * Work out the device name, if it hasn't already been specified,
322 * and parse the tty's options file.
324 if (the_channel->process_extra_options)
325 (*the_channel->process_extra_options)();
328 setlogmask(LOG_UPTO(LOG_DEBUG));
331 * Check that we are running as root.
333 if (geteuid() != 0) {
334 option_error("must be root to run %s, since it is not setuid-root",
339 if (!ppp_available()) {
340 option_error("%s", no_ppp_msg);
341 exit(EXIT_NO_KERNEL_SUPPORT);
345 * Check that the options given are valid and consistent.
348 if (!sys_check_options())
349 exit(EXIT_OPTION_ERROR);
350 auth_check_options();
351 #ifdef HAVE_MULTILINK
354 for (i = 0; (protp = protocols[i]) != NULL; ++i)
355 if (protp->check_options != NULL)
356 (*protp->check_options)();
357 if (the_channel->check_options)
358 (*the_channel->check_options)();
361 if (dump_options || dryrun) {
362 init_pr_log(NULL, LOG_INFO);
363 print_options(pr_log, NULL);
368 * Early check for remote number authorization.
370 if (!auth_number()) {
371 warn("calling number %q is not authorized", remote_number);
372 exit(EXIT_CNID_AUTH_FAILED);
379 * Initialize system-dependent stuff.
384 pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
386 slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
389 warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
391 warn("Warning: disabling multilink");
398 * Detach ourselves from the terminal, if required,
399 * and identify who is running us.
401 if (!nodetach && !updetach)
406 if (pw != NULL && pw->pw_name != NULL)
411 syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
412 script_setenv("PPPLOGNAME", p, 0);
415 script_setenv("DEVICE", devnam, 1);
416 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
417 script_setenv("PPPD_PID", numbuf, 1);
423 create_linkpidfile();
426 * If we're doing dial-on-demand, set up the interface now.
430 * Open the loopback channel and set it up to be the ppp interface.
433 tdb_writelock(pppdb);
435 fd_loop = open_ppp_loopback();
438 tdb_writeunlock(pppdb);
441 * Configure the interface and mark it up, etc.
454 doing_callback = do_callback;
457 if (demand && !doing_callback) {
459 * Don't do anything until we see some activity.
461 new_phase(PHASE_DORMANT);
466 if (kill_link && !persist)
468 if (get_loop_output())
472 if (kill_link && !persist)
476 * Now we want to bring up the link.
479 info("Starting link");
482 new_phase(PHASE_SERIALCONN);
484 devfd = the_channel->connect();
488 /* set up the serial device as a ppp interface */
490 tdb_writelock(pppdb);
492 fd_ppp = the_channel->establish_ppp(devfd);
495 tdb_writeunlock(pppdb);
497 status = EXIT_FATAL_ERROR;
501 if (!demand && ifunit >= 0)
504 tdb_writeunlock(pppdb);
508 * Start opening the connection and wait for
509 * incoming events (reply, timeout, etc.).
512 notice("Connect: %s <--> %s", ifname, ppp_devnam);
514 notice("Starting negotiation on %s", ppp_devnam);
515 gettimeofday(&start_time, NULL);
516 script_unsetenv("CONNECT_TIME");
517 script_unsetenv("BYTES_SENT");
518 script_unsetenv("BYTES_RCVD");
522 lcp_open(0); /* Start protocol */
523 status = EXIT_NEGOTIATION_FAILED;
524 new_phase(PHASE_ESTABLISH);
525 while (phase != PHASE_DEAD) {
529 lcp_close(0, "User request");
531 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
532 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
533 (*ccp_protent.open)(0);
541 * Delete pid file before disestablishing ppp. Otherwise it
542 * can happen that another pppd gets the same unit and then
543 * we delete its pid file.
546 if (pidfilename[0] != 0
547 && unlink(pidfilename) < 0 && errno != ENOENT)
548 warn("unable to delete pid file %s: %m", pidfilename);
553 * If we may want to bring the link up again, transfer
554 * the ppp unit back to the loopback. Set the
555 * real serial device back to its normal mode of operation.
559 the_channel->disestablish_ppp(devfd);
564 script_unsetenv("IFNAME");
567 * Run disconnector script, if requested.
568 * XXX we may not be able to do this if the line has hung up!
571 new_phase(PHASE_DISCONNECT);
572 the_channel->disconnect();
575 if (the_channel->cleanup)
576 (*the_channel->cleanup)();
579 if (pidfilename[0] != 0
580 && unlink(pidfilename) < 0 && errno != ENOENT)
581 warn("unable to delete pid file %s: %m", pidfilename);
585 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
590 t = need_holdoff? holdoff: 0;
592 t = (*holdoff_hook)();
594 new_phase(PHASE_HOLDOFF);
595 TIMEOUT(holdoff_end, NULL, t);
599 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
600 } while (phase == PHASE_HOLDOFF);
606 /* Wait for scripts to finish */
607 /* XXX should have a timeout here */
608 while (n_children > 0) {
610 struct subprocess *chp;
611 dbglog("Waiting for %d child processes...", n_children);
612 for (chp = children; chp != NULL; chp = chp->next)
613 dbglog(" script %s, pid %d", chp->prog, chp->pid);
615 if (reap_kids(1) < 0)
624 * handle_events - wait for something to happen and respond to it.
632 kill_link = open_ccp_flag = 0;
633 if (sigsetjmp(sigjmp, 1) == 0) {
634 sigprocmask(SIG_BLOCK, &mask, NULL);
635 if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
636 sigprocmask(SIG_UNBLOCK, &mask, NULL);
639 sigprocmask(SIG_UNBLOCK, &mask, NULL);
640 wait_input(timeleft(&timo));
648 if (status != EXIT_HANGUP)
649 status = EXIT_USER_REQUEST;
654 status = EXIT_USER_REQUEST;
658 reap_kids(0); /* Don't leave dead kids lying around */
668 * setup_signals - initialize signal handling.
677 * Compute mask of all interesting signals and install signal handlers
678 * for each. Only one signal handler may be active at a time. Therefore,
679 * all other signals should be masked when any handler is executing.
682 sigaddset(&mask, SIGHUP);
683 sigaddset(&mask, SIGINT);
684 sigaddset(&mask, SIGTERM);
685 sigaddset(&mask, SIGCHLD);
686 sigaddset(&mask, SIGUSR2);
688 #define SIGNAL(s, handler) do { \
689 sa.sa_handler = handler; \
690 if (sigaction(s, &sa, NULL) < 0) \
691 fatal("Couldn't establish signal handler (%d): %m", s); \
696 SIGNAL(SIGHUP, hup); /* Hangup */
697 SIGNAL(SIGINT, term); /* Interrupt */
698 SIGNAL(SIGTERM, term); /* Terminate */
699 SIGNAL(SIGCHLD, chld);
701 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
702 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
705 * Install a handler for other signals which would otherwise
706 * cause pppd to exit without cleaning up.
708 SIGNAL(SIGABRT, bad_signal);
709 SIGNAL(SIGALRM, bad_signal);
710 SIGNAL(SIGFPE, bad_signal);
711 SIGNAL(SIGILL, bad_signal);
712 SIGNAL(SIGPIPE, bad_signal);
713 SIGNAL(SIGQUIT, bad_signal);
714 SIGNAL(SIGSEGV, bad_signal);
716 SIGNAL(SIGBUS, bad_signal);
719 SIGNAL(SIGEMT, bad_signal);
722 SIGNAL(SIGPOLL, bad_signal);
725 SIGNAL(SIGPROF, bad_signal);
728 SIGNAL(SIGSYS, bad_signal);
731 SIGNAL(SIGTRAP, bad_signal);
734 SIGNAL(SIGVTALRM, bad_signal);
737 SIGNAL(SIGXCPU, bad_signal);
740 SIGNAL(SIGXFSZ, bad_signal);
744 * Apparently we can get a SIGPIPE when we call syslog, if
745 * syslogd has died and been restarted. Ignoring it seems
748 signal(SIGPIPE, SIG_IGN);
752 * set_ifunit - do things we need to do once we know which ppp
759 info("Using interface %s%d", PPP_DRV_NAME, ifunit);
760 slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
761 script_setenv("IFNAME", ifname, iskey);
763 create_pidfile(); /* write pid to file */
764 create_linkpidfile();
769 * detach - detach us from the controlling terminal.
779 if ((pid = fork()) < 0) {
780 error("Couldn't detach (fork failed: %m)");
781 die(1); /* or just return? */
785 notify(pidchange, pid);
786 exit(0); /* parent dies */
796 /* update pid files if they have been written already */
800 create_linkpidfile();
801 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
802 script_setenv("PPPD_PID", numbuf, 1);
806 * reopen_log - (re)open our connection to syslog.
812 openlog("pppd", LOG_PID);
814 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
815 setlogmask(LOG_UPTO(LOG_INFO));
820 * Create a file containing our process ID.
827 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
828 _PATH_VARRUN, ifname);
829 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
830 fprintf(pidfile, "%d\n", getpid());
831 (void) fclose(pidfile);
833 error("Failed to create pid file %s: %m", pidfilename);
843 if (linkname[0] == 0)
845 script_setenv("LINKNAME", linkname, 1);
846 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
847 _PATH_VARRUN, linkname);
848 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
849 fprintf(pidfile, "%d\n", getpid());
851 fprintf(pidfile, "%s\n", ifname);
852 (void) fclose(pidfile);
854 error("Failed to create pid file %s: %m", linkpidfile);
860 * holdoff_end - called via a timeout when the holdoff period ends.
866 new_phase(PHASE_DORMANT);
869 /* List of protocol names, to make our messages a little more informative. */
870 struct protocol_list {
873 } protocol_list[] = {
875 { 0x23, "OSI Network Layer" },
876 { 0x25, "Xerox NS IDP" },
877 { 0x27, "DECnet Phase IV" },
878 { 0x29, "Appletalk" },
879 { 0x2b, "Novell IPX" },
880 { 0x2d, "VJ compressed TCP/IP" },
881 { 0x2f, "VJ uncompressed TCP/IP" },
882 { 0x31, "Bridging PDU" },
883 { 0x33, "Stream Protocol ST-II" },
884 { 0x35, "Banyan Vines" },
885 { 0x39, "AppleTalk EDDP" },
886 { 0x3b, "AppleTalk SmartBuffered" },
887 { 0x3d, "Multi-Link" },
888 { 0x3f, "NETBIOS Framing" },
889 { 0x41, "Cisco Systems" },
890 { 0x43, "Ascom Timeplex" },
891 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
892 { 0x47, "DCA Remote Lan" },
893 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
894 { 0x4b, "SNA over 802.2" },
896 { 0x4f, "IP6 Header Compression" },
897 { 0x6f, "Stampede Bridging" },
898 { 0xfb, "single-link compression" },
899 { 0xfd, "1st choice compression" },
900 { 0x0201, "802.1d Hello Packets" },
901 { 0x0203, "IBM Source Routing BPDU" },
902 { 0x0205, "DEC LANBridge100 Spanning Tree" },
903 { 0x0231, "Luxcom" },
904 { 0x0233, "Sigma Network Systems" },
905 { 0x8021, "Internet Protocol Control Protocol" },
906 { 0x8023, "OSI Network Layer Control Protocol" },
907 { 0x8025, "Xerox NS IDP Control Protocol" },
908 { 0x8027, "DECnet Phase IV Control Protocol" },
909 { 0x8029, "Appletalk Control Protocol" },
910 { 0x802b, "Novell IPX Control Protocol" },
911 { 0x8031, "Bridging NCP" },
912 { 0x8033, "Stream Protocol Control Protocol" },
913 { 0x8035, "Banyan Vines Control Protocol" },
914 { 0x803d, "Multi-Link Control Protocol" },
915 { 0x803f, "NETBIOS Framing Control Protocol" },
916 { 0x8041, "Cisco Systems Control Protocol" },
917 { 0x8043, "Ascom Timeplex" },
918 { 0x8045, "Fujitsu LBLB Control Protocol" },
919 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
920 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
921 { 0x804b, "SNA over 802.2 Control Protocol" },
922 { 0x804d, "SNA Control Protocol" },
923 { 0x804f, "IP6 Header Compression Control Protocol" },
924 { 0x006f, "Stampede Bridging Control Protocol" },
925 { 0x80fb, "Single Link Compression Control Protocol" },
926 { 0x80fd, "Compression Control Protocol" },
927 { 0xc021, "Link Control Protocol" },
928 { 0xc023, "Password Authentication Protocol" },
929 { 0xc025, "Link Quality Report" },
930 { 0xc027, "Shiva Password Authentication Protocol" },
931 { 0xc029, "CallBack Control Protocol (CBCP)" },
932 { 0xc081, "Container Control Protocol" },
933 { 0xc223, "Challenge Handshake Authentication Protocol" },
934 { 0xc281, "Proprietary Authentication Protocol" },
939 * protocol_name - find a name for a PPP protocol.
945 struct protocol_list *lp;
947 for (lp = protocol_list; lp->proto != 0; ++lp)
948 if (proto == lp->proto)
954 * get_input - called when incoming data is available.
962 struct protent *protp;
964 p = inpacket_buf; /* point to beginning of packet buffer */
966 len = read_packet(inpacket_buf);
971 notice("Modem hangup");
973 status = EXIT_HANGUP;
974 lcp_lowerdown(0); /* serial link is no longer available */
979 if (len < PPP_HDRLEN) {
980 dbglog("received short packet:%.*B", len, p);
984 dump_packet("rcvd", p, len);
985 if (snoop_recv_hook) snoop_recv_hook(p, len);
987 p += 2; /* Skip address and control */
988 GETSHORT(protocol, p);
992 * Toss all non-LCP packets unless LCP is OPEN.
994 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
995 dbglog("Discarded non-LCP packet when LCP not open");
1000 * Until we get past the authentication phase, toss all packets
1001 * except LCP, LQR and authentication packets.
1003 if (phase <= PHASE_AUTHENTICATE
1004 && !(protocol == PPP_LCP || protocol == PPP_LQR
1005 || protocol == PPP_PAP || protocol == PPP_CHAP ||
1006 protocol == PPP_EAP)) {
1007 dbglog("discarding proto 0x%x in phase %d",
1013 * Upcall the proper protocol input routine.
1015 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1016 if (protp->protocol == protocol && protp->enabled_flag) {
1017 (*protp->input)(0, p, len);
1020 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1021 && protp->datainput != NULL) {
1022 (*protp->datainput)(0, p, len);
1028 const char *pname = protocol_name(protocol);
1030 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1032 warn("Unsupported protocol 0x%x received", protocol);
1034 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1038 * new_phase - signal the start of a new phase of pppd's operation.
1046 (*new_phase_hook)(p);
1047 notify(phasechange, p);
1051 * die - clean up state and exit with the specified status.
1059 notify(exitnotify, status);
1060 syslog(LOG_INFO, "Exit.");
1065 * cleanup - restore anything which needs to be restored before we exit
1074 the_channel->disestablish_ppp(devfd);
1075 if (the_channel->cleanup)
1076 (*the_channel->cleanup)();
1078 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1079 warn("unable to delete pid file %s: %m", pidfilename);
1081 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1082 warn("unable to delete pid file %s: %m", linkpidfile);
1096 * Print connect time and statistics.
1098 if (link_stats_valid) {
1099 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
1100 info("Connect time %d.%d minutes.", t/10, t%10);
1101 info("Sent %u bytes, received %u bytes.",
1102 link_stats.bytes_out, link_stats.bytes_in);
1107 * update_link_stats - get stats at link termination.
1110 update_link_stats(u)
1116 if (!get_ppp_stats(u, &link_stats)
1117 || gettimeofday(&now, NULL) < 0)
1119 link_connect_time = now.tv_sec - start_time.tv_sec;
1120 link_stats_valid = 1;
1122 slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
1123 script_setenv("CONNECT_TIME", numbuf, 0);
1124 slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
1125 script_setenv("BYTES_SENT", numbuf, 0);
1126 slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
1127 script_setenv("BYTES_RCVD", numbuf, 0);
1132 struct timeval c_time; /* time at which to call routine */
1133 void *c_arg; /* argument to routine */
1134 void (*c_func) __P((void *)); /* routine */
1135 struct callout *c_next;
1138 static struct callout *callout = NULL; /* Callout list */
1139 static struct timeval timenow; /* Current time */
1142 * timeout - Schedule a timeout.
1145 timeout(func, arg, secs, usecs)
1146 void (*func) __P((void *));
1150 struct callout *newp, *p, **pp;
1152 MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
1158 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1159 fatal("Out of memory in timeout()!");
1161 newp->c_func = func;
1162 gettimeofday(&timenow, NULL);
1163 newp->c_time.tv_sec = timenow.tv_sec + secs;
1164 newp->c_time.tv_usec = timenow.tv_usec + usecs;
1165 if (newp->c_time.tv_usec >= 1000000) {
1166 newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1167 newp->c_time.tv_usec %= 1000000;
1171 * Find correct place and link it in.
1173 for (pp = &callout; (p = *pp); pp = &p->c_next)
1174 if (newp->c_time.tv_sec < p->c_time.tv_sec
1175 || (newp->c_time.tv_sec == p->c_time.tv_sec
1176 && newp->c_time.tv_usec < p->c_time.tv_usec))
1184 * untimeout - Unschedule a timeout.
1187 untimeout(func, arg)
1188 void (*func) __P((void *));
1191 struct callout **copp, *freep;
1193 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1196 * Find first matching timeout and remove it from the list.
1198 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1199 if (freep->c_func == func && freep->c_arg == arg) {
1200 *copp = freep->c_next;
1201 free((char *) freep);
1208 * calltimeout - Call any timeout routines which are now due.
1215 while (callout != NULL) {
1218 if (gettimeofday(&timenow, NULL) < 0)
1219 fatal("Failed to get time of day: %m");
1220 if (!(p->c_time.tv_sec < timenow.tv_sec
1221 || (p->c_time.tv_sec == timenow.tv_sec
1222 && p->c_time.tv_usec <= timenow.tv_usec)))
1223 break; /* no, it's not time yet */
1225 callout = p->c_next;
1226 (*p->c_func)(p->c_arg);
1234 * timeleft - return the length of time until the next timeout is due.
1236 static struct timeval *
1238 struct timeval *tvp;
1240 if (callout == NULL)
1243 gettimeofday(&timenow, NULL);
1244 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1245 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1246 if (tvp->tv_usec < 0) {
1247 tvp->tv_usec += 1000000;
1250 if (tvp->tv_sec < 0)
1251 tvp->tv_sec = tvp->tv_usec = 0;
1258 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1264 struct sigaction act, oldact;
1266 act.sa_handler = SIG_IGN;
1269 sigaction(sig, &act, &oldact);
1270 sigaction(sig, &oldact, NULL);
1275 * hup - Catch SIGHUP signal.
1277 * Indicates that the physical layer has been disconnected.
1278 * We don't rely on this indication; if the user has sent this
1279 * signal, we just take the link down.
1285 info("Hangup (SIGHUP)");
1288 /* Send the signal to the [dis]connector process(es) also */
1290 notify(sigreceived, sig);
1292 siglongjmp(sigjmp, 1);
1297 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1299 * Indicates that we should initiate a graceful disconnect and exit.
1306 info("Terminating on signal %d.", sig);
1309 /* Send the signal to the [dis]connector process(es) also */
1311 notify(sigreceived, sig);
1313 siglongjmp(sigjmp, 1);
1318 * chld - Catch SIGCHLD signal.
1319 * Sets a flag so we will call reap_kids in the mainline.
1327 siglongjmp(sigjmp, 1);
1332 * toggle_debug - Catch SIGUSR1 signal.
1334 * Toggle debug flag.
1343 setlogmask(LOG_UPTO(LOG_DEBUG));
1345 setlogmask(LOG_UPTO(LOG_WARNING));
1351 * open_ccp - Catch SIGUSR2 signal.
1353 * Try to (re)negotiate compression.
1362 siglongjmp(sigjmp, 1);
1367 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1373 static int crashed = 0;
1378 error("Fatal signal %d", sig);
1380 kill_my_pg(SIGTERM);
1381 notify(sigreceived, sig);
1387 * device_script - run a program to talk to the specified fds
1388 * (e.g. to run the connector or disconnector script).
1389 * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1392 device_script(program, in, out, dont_wait)
1406 error("Failed to create child process: %m");
1412 record_child(pid, program, NULL, NULL);
1415 while (waitpid(pid, &status, 0) < 0) {
1418 fatal("error waiting for (dis)connection process: %m");
1422 return (status == 0 ? 0 : -1);
1425 /* here we are executing in the child */
1426 /* make sure fds 0, 1, 2 are occupied */
1427 while ((fd = dup(in)) >= 0) {
1434 /* dup in and out to fds > 2 */
1437 if (log_to_fd >= 0) {
1438 errfd = dup(log_to_fd);
1440 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1443 /* close fds 0 - 2 and any others we can think of */
1448 if (the_channel->close)
1449 (*the_channel->close)();
1452 /* dup the in, out, err fds to 0, 1, 2 */
1463 if (getuid() != uid) {
1464 error("setuid failed");
1468 execl("/bin/sh", "sh", "-c", program, (char *)0);
1469 error("could not exec /bin/sh: %m");
1476 * run-program - execute a program with given arguments,
1477 * but don't wait for it.
1478 * If the program can't be executed, logs an error unless
1479 * must_exist is 0 and the program file doesn't exist.
1480 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1481 * or isn't an executable plain file, or the process ID of the child.
1482 * If done != NULL, (*done)(arg) will be called later (within
1483 * reap_kids) iff the return value is > 0.
1486 run_program(prog, args, must_exist, done, arg)
1490 void (*done) __P((void *));
1497 * First check if the file exists and is executable.
1498 * We don't use access() because that would use the
1499 * real user-id, which might not be root, and the script
1500 * might be accessible only to root.
1503 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1504 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1505 if (must_exist || errno != ENOENT)
1506 warn("Can't execute %s: %m", prog);
1512 error("Failed to create child process for %s: %m", prog);
1518 /* Leave the current location */
1519 (void) setsid(); /* No controlling tty. */
1520 (void) umask (S_IRWXG|S_IRWXO);
1521 (void) chdir ("/"); /* no current directory. */
1522 setuid(0); /* set real UID = root */
1525 /* Ensure that nothing of our device environment is inherited. */
1531 if (the_channel->close)
1532 (*the_channel->close)();
1534 /* Don't pass handles to the PPP device, even by accident. */
1535 new_fd = open (_PATH_DEVNULL, O_RDWR);
1538 dup2 (new_fd, 0); /* stdin <- /dev/null */
1541 dup2 (0, 1); /* stdout -> /dev/null */
1542 dup2 (0, 2); /* stderr -> /dev/null */
1546 /* Force the priority back to zero if pppd is running higher. */
1547 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1548 warn("can't reset priority to 0: %m");
1551 /* SysV recommends a second fork at this point. */
1553 /* run the program */
1554 execve(prog, args, script_env);
1555 if (must_exist || errno != ENOENT) {
1556 /* have to reopen the log, there's nowhere else
1557 for the message to go. */
1559 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1566 dbglog("Script %s started (pid %d)", prog, pid);
1567 record_child(pid, prog, done, arg);
1574 * record_child - add a child process to the list for reap_kids
1578 record_child(pid, prog, done, arg)
1581 void (*done) __P((void *));
1584 struct subprocess *chp;
1588 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1590 warn("losing track of %s process", prog);
1596 chp->next = children;
1603 * reap_kids - get status from any dead child processes,
1604 * and log a message for abnormal terminations.
1611 struct subprocess *chp, **prevp;
1613 if (n_children == 0)
1615 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1617 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1618 if (chp->pid == pid) {
1624 if (WIFSIGNALED(status)) {
1625 warn("Child process %s (pid %d) terminated with signal %d",
1626 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1628 dbglog("Script %s finished (pid %d), status = 0x%x",
1629 (chp? chp->prog: "??"), pid,
1630 WIFEXITED(status) ? WEXITSTATUS(status) : status);
1631 if (chp && chp->done)
1632 (*chp->done)(chp->arg);
1637 if (errno == ECHILD)
1640 error("Error waiting for child process: %m");
1646 * add_notifier - add a new function to be called when something happens.
1649 add_notifier(notif, func, arg)
1650 struct notifier **notif;
1654 struct notifier *np;
1656 np = malloc(sizeof(struct notifier));
1658 novm("notifier struct");
1666 * remove_notifier - remove a function from the list of things to
1667 * be called when something happens.
1670 remove_notifier(notif, func, arg)
1671 struct notifier **notif;
1675 struct notifier *np;
1677 for (; (np = *notif) != 0; notif = &np->next) {
1678 if (np->func == func && np->arg == arg) {
1687 * notify - call a set of functions registered with add_notifier.
1691 struct notifier *notif;
1694 struct notifier *np;
1696 while ((np = notif) != 0) {
1698 (*np->func)(np->arg, val);
1703 * novm - log an error message saying we ran out of memory, and die.
1709 fatal("Virtual memory exhausted allocating %s\n", msg);
1713 * script_setenv - set an environment variable value to be used
1714 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1717 script_setenv(var, value, iskey)
1721 size_t varl = strlen(var);
1722 size_t vl = varl + strlen(value) + 2;
1724 char *p, *newstring;
1726 newstring = (char *) malloc(vl+1);
1729 *newstring++ = iskey;
1730 slprintf(newstring, vl, "%s=%s", var, value);
1732 /* check if this variable is already set */
1733 if (script_env != 0) {
1734 for (i = 0; (p = script_env[i]) != 0; ++i) {
1735 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1737 if (p[-1] && pppdb != NULL)
1741 script_env[i] = newstring;
1743 if (iskey && pppdb != NULL)
1744 add_db_key(newstring);
1751 /* no space allocated for script env. ptrs. yet */
1753 script_env = (char **) malloc(16 * sizeof(char *));
1754 if (script_env == 0)
1759 /* reallocate script_env with more space if needed */
1760 if (i + 1 >= s_env_nalloc) {
1762 char **newenv = (char **) realloc((void *)script_env,
1763 new_n * sizeof(char *));
1766 script_env = newenv;
1767 s_env_nalloc = new_n;
1770 script_env[i] = newstring;
1771 script_env[i+1] = 0;
1774 if (pppdb != NULL) {
1776 add_db_key(newstring);
1783 * script_unsetenv - remove a variable from the environment
1787 script_unsetenv(var)
1790 int vl = strlen(var);
1794 if (script_env == 0)
1796 for (i = 0; (p = script_env[i]) != 0; ++i) {
1797 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1799 if (p[-1] && pppdb != NULL)
1803 while ((script_env[i] = script_env[i+1]) != 0)
1816 * update_db_entry - update our entry in the database.
1825 if (script_env == NULL)
1828 for (i = 0; (p = script_env[i]) != 0; ++i)
1829 vlen += strlen(p) + 1;
1830 vbuf = malloc(vlen);
1832 novm("database entry");
1834 for (i = 0; (p = script_env[i]) != 0; ++i)
1835 q += slprintf(q, vbuf + vlen - q, "%s;", p);
1838 key.dsize = strlen(db_key);
1841 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1842 error("tdb_store failed: %s", tdb_error(pppdb));
1850 * add_db_key - add a key that we can use to look up our database entry.
1858 key.dptr = (char *) str;
1859 key.dsize = strlen(str);
1861 dbuf.dsize = strlen(db_key);
1862 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1863 error("tdb_store key failed: %s", tdb_error(pppdb));
1867 * delete_db_key - delete a key for looking up our database entry.
1875 key.dptr = (char *) str;
1876 key.dsize = strlen(str);
1877 tdb_delete(pppdb, key);
1881 * cleanup_db - delete all the entries we put in the database.
1891 key.dsize = strlen(db_key);
1892 tdb_delete(pppdb, key);
1893 for (i = 0; (p = script_env[i]) != 0; ++i)
1897 #endif /* USE_TDB */