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.2 1995/06/06 12:11:43 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.
304 * Don't do anything until we see some activity.
306 phase = PHASE_DORMANT;
311 wait_loop_output(timeleft(&timo));
318 if (get_loop_output())
324 * Now we want to bring up the link.
327 syslog(LOG_INFO, "Starting link");
331 * Lock the device if we've been asked to.
333 if (lockflag && !default_device) {
334 if (lock(devnam) < 0)
340 * Open the serial device and set it up to be the ppp interface.
341 * If we're dialling out, or we don't want to use the modem lines,
342 * we open it in non-blocking mode, but then we need to clear
343 * the non-blocking I/O bit.
345 nonblock = (connector || !modem)? O_NONBLOCK: 0;
346 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
347 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
350 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
351 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
355 initfdflags &= ~O_NONBLOCK;
356 fcntl(fd, F_SETFL, initfdflags);
361 /* run connection script */
362 if (connector && connector[0]) {
363 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
365 /* set line speed, flow control, etc.; set CLOCAL for now */
368 /* drop dtr to hang up in case modem is off hook */
369 if (!default_device && modem) {
375 if (device_script(connector, fd, fd) < 0) {
376 syslog(LOG_ERR, "Connect script failed");
381 syslog(LOG_INFO, "Serial connection established.");
382 sleep(1); /* give it time to set up its terminal */
385 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
389 * Set device for non-blocking reads.
391 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
392 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
397 /* set up the serial device as a ppp interface */
400 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
401 (void) sprintf(ifname, "ppp%d", ifunit);
403 /* write pid to file */
404 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
405 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
406 fprintf(pidfile, "%d\n", pid);
407 (void) fclose(pidfile);
409 syslog(LOG_ERR, "Failed to create pid file %s: %m",
416 * Transfer the PPP unit over to the real serial device.
422 * Start opening the connection and wait for
423 * incoming events (reply, timeout, etc.).
425 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
427 lcp_open(0); /* Start protocol */
428 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
429 wait_input(timeleft(&timo));
436 if (phase == PHASE_NETWORK) {
437 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
443 reap_kids(); /* Don't leave dead kids lying around */
447 * If we may want to bring the link up again, transfer
448 * the ppp unit back to the loopback. Set the
449 * real serial device back to its normal mode of operation.
453 transfer_ppp(loop_fd);
455 disestablish_ppp(fd);
459 * Run disconnector script, if requested.
460 * First we need to reset non-blocking mode.
461 * XXX we may not be able to do this if the line has hung up!
463 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
465 if (disconnector && !hungup) {
467 if (device_script(disconnector, fd, fd) < 0) {
468 syslog(LOG_WARNING, "disconnect script failed");
470 syslog(LOG_INFO, "Serial link disconnected.");
482 if (unlink(pidfilename) < 0 && errno != ENOENT)
483 syslog(LOG_WARNING, "unable to delete pid file: %m");
492 phase = PHASE_HOLDOFF;
493 TIMEOUT(holdoff_end, NULL, holdoff);
495 wait_time(timeleft(&timo));
501 phase = PHASE_DORMANT; /* allow signal to end holdoff */
504 } while (phase == PHASE_HOLDOFF);
512 * holdoff_end - called via a timeout when the holdoff period ends.
518 phase = PHASE_DORMANT;
522 * get_input - called when incoming data is available.
531 p = inpacket_buf; /* point to beginning of packet buffer */
533 len = read_packet(inpacket_buf);
538 syslog(LOG_NOTICE, "Modem hangup");
540 lcp_lowerdown(0); /* serial link is no longer available */
545 if (debug /*&& (debugflags & DBG_INPACKET)*/)
546 log_packet(p, len, "rcvd ");
548 if (len < PPP_HDRLEN) {
549 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
553 p += 2; /* Skip address and control */
554 GETSHORT(protocol, p);
558 * Toss all non-LCP packets unless LCP is OPEN.
560 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
562 "io(): Received non-LCP packet when LCP not open."));
567 * Upcall the proper protocol input routine.
569 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
570 if (prottbl[i].protocol == protocol) {
571 (*prottbl[i].input)(0, p, len);
573 } else if (protocol == (prottbl[i].protocol & ~0x8000)
574 && prottbl[i].datainput != NULL) {
575 (*prottbl[i].datainput)(0, p, len);
579 if (i == sizeof (prottbl) / sizeof (struct protent)) {
581 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
582 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
588 * demuxprotrej - Demultiplex a Protocol-Reject.
591 demuxprotrej(unit, protocol)
598 * Upcall the proper Protocol-Reject routine.
600 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
601 if (prottbl[i].protocol == protocol) {
602 (*prottbl[i].protrej)(unit);
607 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
613 * quit - Clean up state and exit.
622 * die - like quit, except we can specify an exit status.
629 syslog(LOG_INFO, "Exit.");
634 * cleanup - restore anything which needs to be restored before we exit
645 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
646 syslog(LOG_WARNING, "unable to delete pid file: %m");
657 * close_fd - restore the terminal device and close it.
662 /* drop dtr to hang up */
666 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
667 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
670 disestablish_ppp(fd);
680 struct timeval c_time; /* time at which to call routine */
681 caddr_t c_arg; /* argument to routine */
682 void (*c_func)(); /* routine */
683 struct callout *c_next;
686 static struct callout *callout = NULL; /* Callout list */
687 static struct timeval timenow; /* Current time */
690 * timeout - Schedule a timeout.
692 * Note that this timeout takes the number of seconds, NOT hz (as in
696 timeout(func, arg, time)
701 struct callout *newp, *p, **pp;
703 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
704 (long) func, (long) arg, time));
709 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
710 syslog(LOG_ERR, "Out of memory in timeout()!");
715 gettimeofday(&timenow, NULL);
716 newp->c_time.tv_sec = timenow.tv_sec + time;
717 newp->c_time.tv_usec = timenow.tv_usec;
720 * Find correct place and link it in.
722 for (pp = &callout; (p = *pp); pp = &p->c_next)
723 if (newp->c_time.tv_sec < p->c_time.tv_sec
724 || (newp->c_time.tv_sec == p->c_time.tv_sec
725 && newp->c_time.tv_usec < p->c_time.tv_sec))
733 * untimeout - Unschedule a timeout.
740 struct itimerval itv;
741 struct callout **copp, *freep;
744 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
747 * Find first matching timeout and remove it from the list.
749 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
750 if (freep->c_func == func && freep->c_arg == arg) {
751 *copp = freep->c_next;
752 (void) free((char *) freep);
759 * calltimeout - Call any timeout routines which are now due.
766 while (callout != NULL) {
769 if (gettimeofday(&timenow, NULL) < 0) {
770 syslog(LOG_ERR, "Failed to get time of day: %m");
773 if (!(p->c_time.tv_sec < timenow.tv_sec
774 || (p->c_time.tv_sec == timenow.tv_sec
775 && p->c_time.tv_usec <= timenow.tv_usec)))
776 break; /* no, it's not time yet */
779 (*p->c_func)(p->c_arg);
787 * timeleft - return the length of time until the next timeout is due.
796 gettimeofday(&timenow, NULL);
797 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
798 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
799 if (tvp->tv_usec < 0) {
800 tvp->tv_usec += 1000000;
804 tvp->tv_sec = tvp->tv_usec = 0;
811 * hup - Catch SIGHUP signal.
813 * Indicates that the physical layer has been disconnected.
814 * We don't rely on this indication; if the user has sent this
815 * signal, we just take the link down.
821 syslog(LOG_INFO, "Hangup (SIGHUP)");
827 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
829 * Indicates that we should initiate a graceful disconnect and exit.
836 syslog(LOG_INFO, "Terminating on signal %d.", sig);
837 persist = 0; /* don't try to restart */
843 * chld - Catch SIGCHLD signal.
844 * Calls reap_kids to get status for any dead kids.
855 * toggle_debug - Catch SIGUSR1 signal.
870 * open_ccp - Catch SIGUSR2 signal.
872 * Try to (re)negotiate compression.
884 * device_script - run a program to connect or disconnect the
888 device_script(program, in, out)
899 syslog(LOG_ERR, "Failed to create child process: %m");
907 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
912 execl("/bin/sh", "sh", "-c", program, (char *)0);
913 syslog(LOG_ERR, "could not exec /bin/sh: %m");
918 while (waitpid(pid, &status, 0) < 0) {
921 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
925 return (status == 0 ? 0 : -1);
930 * run-program - execute a program with given arguments,
931 * but don't wait for it.
932 * If the program can't be executed, logs an error unless
933 * must_exist is 0 and the program file doesn't exist.
936 run_program(prog, args, must_exist)
946 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
952 /* Leave the current location */
953 (void) setsid(); /* No controlling tty. */
954 (void) umask (S_IRWXG|S_IRWXO);
955 (void) chdir ("/"); /* no current directory. */
959 /* Ensure that nothing of our device environment is inherited. */
964 close (fd); /* tty interface to the ppp device */
966 /* Don't pass handles to the PPP device, even by accident. */
967 new_fd = open (_PATH_DEVNULL, O_RDWR);
970 dup2 (new_fd, 0); /* stdin <- /dev/null */
973 dup2 (0, 1); /* stdout -> /dev/null */
974 dup2 (0, 2); /* stderr -> /dev/null */
978 /* Force the priority back to zero if pppd is running higher. */
979 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
980 syslog (LOG_WARNING, "can't reset priority to 0: %m");
983 /* SysV recommends a second fork at this point. */
985 /* run the program; give it a null environment */
987 execve(prog, args, nullenv);
988 if (must_exist || errno != ENOENT)
989 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
992 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
999 * reap_kids - get status from any dead child processes,
1000 * and log a message for abnormal terminations.
1007 if (n_children == 0)
1009 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1010 if (errno != ECHILD)
1011 syslog(LOG_ERR, "Error waiting for child process: %m");
1016 if (WIFSIGNALED(status)) {
1017 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1018 pid, WTERMSIG(status));
1025 * log_packet - format a packet and log it.
1028 char line[256]; /* line to be logged accumulated here */
1032 log_packet(p, len, prefix)
1037 strcpy(line, prefix);
1038 linep = line + strlen(line);
1039 format_packet(p, len, pr_log, NULL);
1041 syslog(LOG_DEBUG, "%s", line);
1045 * format_packet - make a readable representation of a packet,
1046 * calling `printer(arg, format, ...)' to output it.
1049 format_packet(p, len, printer, arg)
1052 void (*printer) __P((void *, char *, ...));
1059 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1063 for (i = 0; i < N_PROTO; ++i)
1064 if (proto == prottbl[i].protocol)
1067 printer(arg, "[%s", prottbl[i].name);
1068 n = (*prottbl[i].printpkt)(p, len, printer, arg);
1073 printer(arg, "[proto=0x%x]", proto);
1077 for (; len > 0; --len) {
1079 printer(arg, " %.2x", x);
1087 pr_log(void *arg, char *fmt, ...)
1093 va_start(pvar, fmt);
1094 vsprintf(buf, fmt, pvar);
1098 if (linep + n + 1 > line + sizeof(line)) {
1099 syslog(LOG_DEBUG, "%s", line);
1106 #else /* __STDC__ */
1107 #include <varargs.h>
1110 pr_log(arg, fmt, va_alist)
1120 vsprintf(buf, fmt, pvar);
1124 if (linep + n + 1 > line + sizeof(line)) {
1125 syslog(LOG_DEBUG, "%s", line);
1134 * print_string - print a readable representation of a string using
1138 print_string(p, len, printer, arg)
1141 void (*printer) __P((void *, char *, ...));
1147 for (; len > 0; --len) {
1149 if (' ' <= c && c <= '~')
1150 printer(arg, "%c", c);
1152 printer(arg, "\\%.3o", c);
1158 * novm - log an error message saying we ran out of memory, and die.
1164 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);