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.
21 static char rcsid[] = "$Id: main.c,v 1.23.2.1 1995/06/01 07:01:31 paulus Exp $";
34 #include <sys/param.h>
35 #include <sys/types.h>
38 #include <sys/resource.h>
40 #include <sys/socket.h>
51 #include "pathnames.h"
52 #include "patchlevel.h"
55 * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
56 * /etc/ppp/options exists.
58 #ifndef REQ_SYSOPTIONS
59 #define REQ_SYSOPTIONS 1
63 char ifname[IFNAMSIZ]; /* Interface name */
64 int ifunit; /* Interface unit number */
66 char *progname; /* Name of this program */
67 char hostname[MAXNAMELEN]; /* Our hostname */
68 static char pidfilename[MAXPATHLEN]; /* name of pid file */
69 static char default_devnam[MAXPATHLEN]; /* name of default device */
70 static pid_t pid; /* Our pid */
71 static pid_t pgrpid; /* Process Group ID */
72 static uid_t uid; /* Our real user-id */
74 int fd = -1; /* Device file descriptor */
76 int phase; /* where the link is at */
80 static int initfdflags = -1; /* Initial file descriptor flags */
81 static int loop_fd = -1; /* fd for loopback device */
83 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
84 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
86 int hungup; /* terminal has been hung up */
87 static int n_children; /* # child processes still running */
94 static void hup __P((int));
95 static void term __P((int));
96 static void chld __P((int));
97 static void toggle_debug __P((int));
98 static void open_ccp __P((int));
99 static void holdoff_end __P((void *));
101 static void get_input __P((void));
102 void establish_ppp __P((int));
103 void calltimeout __P((void));
104 struct timeval *timeleft __P((struct timeval *));
105 void reap_kids __P((void));
106 void cleanup __P((int, caddr_t));
107 void close_fd __P((void));
109 void novm __P((char *));
111 void log_packet __P((u_char *, int, char *));
112 void format_packet __P((u_char *, int,
113 void (*) (void *, char *, ...), void *));
114 void pr_log __P((void *, char *, ...));
116 extern char *ttyname __P((int));
117 extern char *getlogin __P((void));
121 #define O_NONBLOCK O_NDELAY
125 * PPP Data Link Layer "protocol" table.
126 * One entry per supported protocol.
128 static struct protent {
137 { PPP_LCP, lcp_init, lcp_input, lcp_protrej,
138 lcp_printpkt, NULL, "LCP" },
139 { PPP_IPCP, ipcp_init, ipcp_input, ipcp_protrej,
140 ipcp_printpkt, NULL, "IPCP" },
141 { PPP_PAP, upap_init, upap_input, upap_protrej,
142 upap_printpkt, NULL, "PAP" },
143 { PPP_CHAP, ChapInit, ChapInput, ChapProtocolReject,
144 ChapPrintPkt, NULL, "CHAP" },
145 { PPP_CCP, ccp_init, ccp_input, ccp_protrej,
146 ccp_printpkt, ccp_datainput, "CCP" },
149 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
167 strcpy(default_devnam, devnam);
169 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
170 perror("couldn't get hostname");
173 hostname[MAXNAMELEN-1] = 0;
177 if (!ppp_available()) {
178 fprintf(stderr, "Sorry - PPP is not available on this system\n");
183 * Initialize to the standard option set, then parse, in order,
184 * the system options file, the user's options file, and the command
187 for (i = 0; i < N_PROTO; i++)
188 (*prottbl[i].init)(0);
192 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
193 !options_from_user() ||
194 !parse_args(argc-1, argv+1) ||
197 check_auth_options();
201 * If the user has specified the default device name explicitly,
202 * pretend they hadn't.
204 if (!default_device && strcmp(devnam, default_devnam) == 0)
208 * Initialize system-dependent stuff and magic number package.
214 * For dial-on-demand, we need to know the remote address.
216 if (demand && ipcp_wantoptions[0].hisaddr == 0) {
217 fprintf(stderr, "Remote IP address must be specified for dial-on-demand\n");
222 * Detach ourselves from the terminal, if required,
223 * and identify who is running us.
225 if (!default_device && !nodetach && daemon(0, 0) < 0) {
226 perror("Couldn't detach from controlling terminal");
233 if (pw != NULL && pw->pw_name != NULL)
238 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
239 VERSION, PATCHLEVEL, p, uid);
242 * Compute mask of all interesting signals and install signal handlers
243 * for each. Only one signal handler may be active at a time. Therefore,
244 * all other signals should be masked when any handler is executing.
247 sigaddset(&mask, SIGHUP);
248 sigaddset(&mask, SIGINT);
249 sigaddset(&mask, SIGTERM);
250 sigaddset(&mask, SIGCHLD);
252 #define SIGNAL(s, handler) { \
253 sa.sa_handler = handler; \
254 if (sigaction(s, &sa, NULL) < 0) { \
255 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
262 SIGNAL(SIGHUP, hup); /* Hangup */
263 SIGNAL(SIGINT, term); /* Interrupt */
264 SIGNAL(SIGTERM, term); /* Terminate */
265 SIGNAL(SIGCHLD, chld);
267 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
268 signal(SIGUSR2, open_ccp); /* Reopen CCP */
271 * If we're doing dial-on-demand, set up the interface now.
275 * Open the loopback channel and set it up to be the ppp interface.
277 loop_fd = open_loopback();
278 establish_ppp(loop_fd);
280 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
281 (void) sprintf(ifname, "ppp%d", ifunit);
283 /* write pid to file */
284 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
285 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
286 fprintf(pidfile, "%d\n", pid);
287 (void) fclose(pidfile);
289 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
294 * Configure the interface and mark it up, etc.
303 * Don't do anything until we see some activity.
305 phase = PHASE_DORMANT;
310 wait_loop_output(timeleft(&timo));
317 if (get_loop_output())
323 * Now we want to bring up the link.
326 syslog(LOG_INFO, "Starting link");
330 * Lock the device if we've been asked to.
332 if (lockflag && !default_device) {
333 if (lock(devnam) < 0)
339 * Open the serial device and set it up to be the ppp interface.
340 * If we're dialling out, or we don't want to use the modem lines,
341 * we open it in non-blocking mode, but then we need to clear
342 * the non-blocking I/O bit.
344 nonblock = (connector || !modem)? O_NONBLOCK: 0;
345 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
346 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
349 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
350 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
354 initfdflags &= ~O_NONBLOCK;
355 fcntl(fd, F_SETFL, initfdflags);
360 /* run connection script */
361 if (connector && connector[0]) {
362 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
364 /* set line speed, flow control, etc.; set CLOCAL for now */
367 /* drop dtr to hang up in case modem is off hook */
368 if (!default_device && modem) {
374 if (device_script(connector, fd, fd) < 0) {
375 syslog(LOG_ERR, "Connect script failed");
380 syslog(LOG_INFO, "Serial connection established.");
381 sleep(1); /* give it time to set up its terminal */
384 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
388 * Set device for non-blocking reads.
390 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
391 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
396 /* set up the serial device as a ppp interface */
399 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
400 (void) sprintf(ifname, "ppp%d", ifunit);
402 /* write pid to file */
403 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
404 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
405 fprintf(pidfile, "%d\n", pid);
406 (void) fclose(pidfile);
408 syslog(LOG_ERR, "Failed to create pid file %s: %m",
415 * Transfer the PPP unit over to the real serial device.
421 * Start opening the connection and wait for
422 * incoming events (reply, timeout, etc.).
424 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
426 lcp_open(0); /* Start protocol */
427 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
428 wait_input(timeleft(&timo));
435 if (phase == PHASE_NETWORK) {
436 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
442 reap_kids(); /* Don't leave dead kids lying around */
446 * If we may want to bring the link up again, transfer
447 * the ppp unit back to the loopback. Set the
448 * real serial device back to its normal mode of operation.
452 transfer_ppp(loop_fd);
454 disestablish_ppp(fd);
458 * Run disconnector script, if requested.
459 * First we need to reset non-blocking mode.
460 * XXX we may not be able to do this if the line has hung up!
462 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
464 if (disconnector && !hungup) {
466 if (device_script(disconnector, fd, fd) < 0) {
467 syslog(LOG_WARNING, "disconnect script failed");
469 syslog(LOG_INFO, "Serial link disconnected.");
481 if (unlink(pidfilename) < 0 && errno != ENOENT)
482 syslog(LOG_WARNING, "unable to delete pid file: %m");
491 phase = PHASE_HOLDOFF;
492 TIMEOUT(holdoff_end, NULL, holdoff);
494 wait_time(timeleft(&timo));
500 phase = PHASE_DORMANT; /* allow signal to end holdoff */
503 } while (phase == PHASE_HOLDOFF);
511 * holdoff_end - called via a timeout when the holdoff period ends.
517 phase = PHASE_DORMANT;
521 * get_input - called when incoming data is available.
530 p = inpacket_buf; /* point to beginning of packet buffer */
532 len = read_packet(inpacket_buf);
537 syslog(LOG_NOTICE, "Modem hangup");
539 lcp_lowerdown(0); /* serial link is no longer available */
544 if (debug /*&& (debugflags & DBG_INPACKET)*/)
545 log_packet(p, len, "rcvd ");
547 if (len < PPP_HDRLEN) {
548 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
552 p += 2; /* Skip address and control */
553 GETSHORT(protocol, p);
557 * Toss all non-LCP packets unless LCP is OPEN.
559 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
561 "io(): Received non-LCP packet when LCP not open."));
566 * Upcall the proper protocol input routine.
568 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
569 if (prottbl[i].protocol == protocol) {
570 (*prottbl[i].input)(0, p, len);
572 } else if (protocol == (prottbl[i].protocol & ~0x8000)
573 && prottbl[i].datainput != NULL) {
574 (*prottbl[i].datainput)(0, p, len);
578 if (i == sizeof (prottbl) / sizeof (struct protent)) {
580 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
581 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
587 * demuxprotrej - Demultiplex a Protocol-Reject.
590 demuxprotrej(unit, protocol)
597 * Upcall the proper Protocol-Reject routine.
599 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
600 if (prottbl[i].protocol == protocol) {
601 (*prottbl[i].protrej)(unit);
606 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
612 * quit - Clean up state and exit.
621 * die - like quit, except we can specify an exit status.
628 syslog(LOG_INFO, "Exit.");
633 * cleanup - restore anything which needs to be restored before we exit
644 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
645 syslog(LOG_WARNING, "unable to delete pid file: %m");
656 * close_fd - restore the terminal device and close it.
661 /* drop dtr to hang up */
665 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
666 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
669 disestablish_ppp(fd);
679 struct timeval c_time; /* time at which to call routine */
680 caddr_t c_arg; /* argument to routine */
681 void (*c_func)(); /* routine */
682 struct callout *c_next;
685 static struct callout *callout = NULL; /* Callout list */
686 static struct timeval timenow; /* Current time */
689 * timeout - Schedule a timeout.
691 * Note that this timeout takes the number of seconds, NOT hz (as in
695 timeout(func, arg, time)
700 struct callout *newp, *p, **pp;
702 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
703 (long) func, (long) arg, time));
708 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
709 syslog(LOG_ERR, "Out of memory in timeout()!");
714 gettimeofday(&timenow, NULL);
715 newp->c_time.tv_sec = timenow.tv_sec + time;
716 newp->c_time.tv_usec = timenow.tv_usec;
719 * Find correct place and link it in.
721 for (pp = &callout; (p = *pp); pp = &p->c_next)
722 if (newp->c_time.tv_sec < p->c_time.tv_sec
723 || (newp->c_time.tv_sec == p->c_time.tv_sec
724 && newp->c_time.tv_usec < p->c_time.tv_sec))
732 * untimeout - Unschedule a timeout.
739 struct itimerval itv;
740 struct callout **copp, *freep;
743 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
746 * Find first matching timeout and remove it from the list.
748 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
749 if (freep->c_func == func && freep->c_arg == arg) {
750 *copp = freep->c_next;
751 (void) free((char *) freep);
758 * calltimeout - Call any timeout routines which are now due.
765 while (callout != NULL) {
768 if (gettimeofday(&timenow, NULL) < 0) {
769 syslog(LOG_ERR, "Failed to get time of day: %m");
772 if (!(p->c_time.tv_sec < timenow.tv_sec
773 || (p->c_time.tv_sec == timenow.tv_sec
774 && p->c_time.tv_usec <= timenow.tv_usec)))
775 break; /* no, it's not time yet */
778 (*p->c_func)(p->c_arg);
786 * timeleft - return the length of time until the next timeout is due.
795 gettimeofday(&timenow, NULL);
796 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
797 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
798 if (tvp->tv_usec < 0) {
799 tvp->tv_usec += 1000000;
803 tvp->tv_sec = tvp->tv_usec = 0;
810 * hup - Catch SIGHUP signal.
812 * Indicates that the physical layer has been disconnected.
813 * We don't rely on this indication; if the user has sent this
814 * signal, we just take the link down.
820 syslog(LOG_INFO, "Hangup (SIGHUP)");
826 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
828 * Indicates that we should initiate a graceful disconnect and exit.
835 syslog(LOG_INFO, "Terminating on signal %d.", sig);
836 persist = 0; /* don't try to restart */
842 * chld - Catch SIGCHLD signal.
843 * Calls reap_kids to get status for any dead kids.
854 * toggle_debug - Catch SIGUSR1 signal.
869 * open_ccp - Catch SIGUSR2 signal.
871 * Try to (re)negotiate compression.
883 * device_script - run a program to connect or disconnect the
887 device_script(program, in, out)
898 syslog(LOG_ERR, "Failed to create child process: %m");
906 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
911 execl("/bin/sh", "sh", "-c", program, (char *)0);
912 syslog(LOG_ERR, "could not exec /bin/sh: %m");
917 while (waitpid(pid, &status, 0) < 0) {
920 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
924 return (status == 0 ? 0 : -1);
929 * run-program - execute a program with given arguments,
930 * but don't wait for it.
931 * If the program can't be executed, logs an error unless
932 * must_exist is 0 and the program file doesn't exist.
935 run_program(prog, args, must_exist)
945 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
951 /* Leave the current location */
952 (void) setsid(); /* No controlling tty. */
953 (void) umask (S_IRWXG|S_IRWXO);
954 (void) chdir ("/"); /* no current directory. */
958 /* Ensure that nothing of our device environment is inherited. */
963 close (fd); /* tty interface to the ppp device */
965 /* Don't pass handles to the PPP device, even by accident. */
966 new_fd = open (_PATH_DEVNULL, O_RDWR);
969 dup2 (new_fd, 0); /* stdin <- /dev/null */
972 dup2 (0, 1); /* stdout -> /dev/null */
973 dup2 (0, 2); /* stderr -> /dev/null */
977 /* Force the priority back to zero if pppd is running higher. */
978 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
979 syslog (LOG_WARNING, "can't reset priority to 0: %m");
982 /* SysV recommends a second fork at this point. */
984 /* run the program; give it a null environment */
986 execve(prog, args, nullenv);
987 if (must_exist || errno != ENOENT)
988 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
991 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
998 * reap_kids - get status from any dead child processes,
999 * and log a message for abnormal terminations.
1006 if (n_children == 0)
1008 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1009 if (errno != ECHILD)
1010 syslog(LOG_ERR, "Error waiting for child process: %m");
1015 if (WIFSIGNALED(status)) {
1016 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1017 pid, WTERMSIG(status));
1024 * log_packet - format a packet and log it.
1027 char line[256]; /* line to be logged accumulated here */
1031 log_packet(p, len, prefix)
1036 strcpy(line, prefix);
1037 linep = line + strlen(line);
1038 format_packet(p, len, pr_log, NULL);
1040 syslog(LOG_DEBUG, "%s", line);
1044 * format_packet - make a readable representation of a packet,
1045 * calling `printer(arg, format, ...)' to output it.
1048 format_packet(p, len, printer, arg)
1051 void (*printer) __P((void *, char *, ...));
1058 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1062 for (i = 0; i < N_PROTO; ++i)
1063 if (proto == prottbl[i].protocol)
1066 printer(arg, "[%s", prottbl[i].name);
1067 n = (*prottbl[i].printpkt)(p, len, printer, arg);
1072 printer(arg, "[proto=0x%x]", proto);
1076 for (; len > 0; --len) {
1078 printer(arg, " %.2x", x);
1086 pr_log(void *arg, char *fmt, ...)
1092 va_start(pvar, fmt);
1093 vsprintf(buf, fmt, pvar);
1097 if (linep + n + 1 > line + sizeof(line)) {
1098 syslog(LOG_DEBUG, "%s", line);
1105 #else /* __STDC__ */
1106 #include <varargs.h>
1109 pr_log(arg, fmt, va_alist)
1119 vsprintf(buf, fmt, pvar);
1123 if (linep + n + 1 > line + sizeof(line)) {
1124 syslog(LOG_DEBUG, "%s", line);
1133 * print_string - print a readable representation of a string using
1137 print_string(p, len, printer, arg)
1140 void (*printer) __P((void *, char *, ...));
1146 for (; len > 0; --len) {
1148 if (' ' <= c && c <= '~')
1149 printer(arg, "%c", c);
1151 printer(arg, "\\%.3o", c);
1157 * novm - log an error message saying we ran out of memory, and die.
1163 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);