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.15 1994/08/22 00:40:48 paulus Exp $";
36 * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
37 * /etc/ppp/options exists.
39 #ifndef REQ_SYSOPTIONS
40 #define REQ_SYSOPTIONS 1
47 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <sys/types.h>
55 #include <sys/socket.h>
70 #include "pathnames.h"
71 #include "patchlevel.h"
83 static char *pidpath = PIDPATH; /* filename in which pid will be stored */
85 static char *pidpath = _PATH_PIDFILE;
89 char ifname[IFNAMSIZ]; /* Interface name */
90 int ifunit; /* Interface unit number */
92 char *progname; /* Name of this program */
93 char hostname[MAXNAMELEN]; /* Our hostname */
94 char our_name[MAXNAMELEN];
95 char remote_name[MAXNAMELEN];
96 static char pidfilename[MAXPATHLEN];
98 static pid_t pid; /* Our pid */
99 static pid_t pgrpid; /* Process Group ID */
100 uid_t uid; /* Our real user-id */
102 char devnam[MAXPATHLEN] = "/dev/tty"; /* Device name */
103 int default_device = TRUE; /* use default device (stdin/out) */
105 int fd = -1; /* Device file descriptor */
106 int s; /* Socket file descriptor */
108 int phase; /* where the link is at */
112 static struct sgttyb initsgttyb; /* Initial TTY sgttyb */
114 static struct termios inittermios; /* Initial TTY termios */
117 static int initfdflags = -1; /* Initial file descriptor flags */
119 int restore_term; /* 1 => we've munged the terminal */
121 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
122 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
124 int hungup; /* terminal has been hung up */
125 static int n_children; /* # child processes still running */
127 /* configured variables */
129 int debug = 0; /* Debug flag */
130 int kdebugflag = 0; /* Kernel debugging flag */
131 char user[MAXNAMELEN]; /* username for PAP */
132 char passwd[MAXSECRETLEN]; /* password for PAP */
133 char *connector = NULL; /* "connect" command */
134 char *disconnector = NULL; /* "disconnect" command */
135 int inspeed = 0; /* Input/Output speed requested */
136 int baud_rate; /* bits/sec currently used */
137 u_long netmask = 0; /* netmask to use on ppp interface */
138 int crtscts = 0; /* use h/w flow control */
139 int nodetach = 0; /* don't fork */
140 int modem = 0; /* use modem control lines */
141 int auth_required = 0; /* require peer to authenticate */
142 int defaultroute = 0; /* assign default route through interface */
143 int proxyarp = 0; /* set entry in arp table */
144 int persist = 0; /* re-initiate on termination */
145 int answer = 0; /* wait for incoming call */
146 int uselogin = 0; /* check PAP info against /etc/passwd */
147 int lockflag = 0; /* lock the serial device */
151 static void hup __ARGS((int));
152 static void term __ARGS((int));
153 static void chld __ARGS((int));
154 static void incdebug __ARGS((int));
155 static void nodebug __ARGS((int));
157 static void get_input __ARGS((void));
158 void establish_ppp __ARGS((void));
159 void calltimeout __ARGS((void));
160 struct timeval *timeleft __ARGS((struct timeval *));
161 void reap_kids __ARGS((void));
162 void cleanup __ARGS((int, caddr_t));
163 void close_fd __ARGS((void));
164 void die __ARGS((int));
165 void novm __ARGS((char *));
167 void log_packet __ARGS((u_char *, int, char *));
168 void format_packet __ARGS((u_char *, int,
169 void (*) (void *, char *, ...), void *));
170 void pr_log __ARGS((void *, char *, ...));
172 extern char *ttyname __ARGS((int));
173 extern char *getlogin __ARGS((void));
176 * PPP Data Link Layer "protocol" table.
177 * One entry per supported protocol.
179 static struct protent {
188 { LCP, lcp_init, lcp_input, lcp_protrej, lcp_printpkt, NULL, "LCP" },
189 { IPCP, ipcp_init, ipcp_input, ipcp_protrej, ipcp_printpkt, NULL, "IPCP" },
190 { UPAP, upap_init, upap_input, upap_protrej, upap_printpkt, NULL, "PAP" },
191 { CHAP, ChapInit, ChapInput, ChapProtocolReject, ChapPrintPkt, NULL, "CHAP" },
192 { CCP, ccp_init, ccp_input, ccp_protrej, ccp_printpkt, ccp_datainput, "CCP" },
195 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
213 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
214 perror("couldn't get hostname");
217 hostname[MAXNAMELEN-1] = 0;
221 if (!ppp_available()) {
222 fprintf(stderr, "Sorry - PPP is not available on this system\n");
227 * Initialize to the standard option set, then parse, in order,
228 * the system options file, the user's options file, and the command
231 for (i = 0; i < N_PROTO; i++)
232 (*prottbl[i].init)(0);
236 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
237 !options_from_user() ||
238 !parse_args(argc-1, argv+1) ||
241 check_auth_options();
245 * Initialize syslog system and magic number package.
248 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
249 setlogmask(LOG_UPTO(LOG_INFO));
251 openlog("pppd", LOG_PID);
252 #define LOG_UPTO(x) (x)
253 #define setlogmask(x) (x)
256 setlogmask(LOG_UPTO(LOG_DEBUG));
261 * Detach ourselves from the terminal, if required,
262 * and identify who is running us.
264 if (!default_device && !nodetach && daemon(0, 0) < 0) {
272 if (pw != NULL && pw->pw_name != NULL)
277 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
278 VERSION, PATCHLEVEL, p, uid);
280 /* Get an internet socket for doing socket ioctl's on. */
281 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
282 syslog(LOG_ERR, "socket : %m");
287 * Compute mask of all interesting signals and install signal handlers
288 * for each. Only one signal handler may be active at a time. Therefore,
289 * all other signals should be masked when any handler is executing.
292 sigaddset(&mask, SIGHUP);
293 sigaddset(&mask, SIGINT);
294 sigaddset(&mask, SIGTERM);
295 sigaddset(&mask, SIGCHLD);
297 #define SIGNAL(s, handler) { \
298 sa.sa_handler = handler; \
299 if (sigaction(s, &sa, NULL) < 0) { \
300 syslog(LOG_ERR, "sigaction(%d): %m", s); \
307 SIGNAL(SIGHUP, hup); /* Hangup */
308 SIGNAL(SIGINT, term); /* Interrupt */
309 SIGNAL(SIGTERM, term); /* Terminate */
310 SIGNAL(SIGCHLD, chld);
312 signal(SIGUSR1, incdebug); /* Increment debug flag */
313 signal(SIGUSR2, nodebug); /* Reset debug flag */
316 * Lock the device if we've been asked to.
318 if (lockflag && !default_device)
319 if (lock(devnam) < 0)
325 * Open the serial device and set it up to be the ppp interface.
327 if ((fd = open(devnam, O_RDWR, 0)) < 0) {
328 syslog(LOG_ERR, "open(%s): %m", devnam);
334 /* run connection script */
336 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
338 /* set line speed, flow control, etc.; set CLOCAL for now */
341 /* drop dtr to hang up in case modem is off hook */
342 if (!default_device && modem) {
348 if (device_script(connector, fd, fd) < 0) {
349 syslog(LOG_ERR, "could not set up connection");
354 syslog(LOG_INFO, "Connected...");
355 sleep(1); /* give it time to set up its terminal */
358 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
361 /* set up the serial device as a ppp interface */
364 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
365 (void) sprintf(ifname, "ppp%d", ifunit);
367 /* write pid to file */
368 (void) sprintf(pidfilename, "%s/%s.pid", pidpath, ifname);
369 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
370 fprintf(pidfile, "%d\n", pid);
371 (void) fclose(pidfile);
373 syslog(LOG_ERR, "unable to create pid file: %m");
378 * Record initial device flags, then set device for
379 * non-blocking reads.
381 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
382 syslog(LOG_ERR, "fcntl(F_GETFL): %m");
385 if (fcntl(fd, F_SETFL, FNDELAY) == -1) {
386 syslog(LOG_ERR, "fcntl(F_SETFL, FNDELAY): %m");
391 * Block all signals, start opening the connection, and wait for
392 * incoming events (reply, timeout, etc.).
394 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
396 lcp_open(0); /* Start protocol */
397 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
398 wait_input(timeleft(&timo));
405 reap_kids(); /* Don't leave dead kids lying around */
409 * Run disconnector script, if requested
412 if (device_script(disconnector, fd, fd) < 0) {
413 syslog(LOG_WARNING, "disconnect script failed");
417 syslog(LOG_INFO, "Disconnected...");
421 if (unlink(pidfilename) < 0)
422 syslog(LOG_WARNING, "unable to unlink pid file: %m");
427 if (lockflag && !default_device)
435 * get_input - called when incoming data is available.
444 for (;;) { /* Read all available packets */
445 p = inpacket_buf; /* point to beginning of packet buffer */
447 len = read_packet(inpacket_buf);
452 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
454 lcp_lowerdown(0); /* serial link is no longer available */
459 if (debug /*&& (debugflags & DBG_INPACKET)*/)
460 log_packet(p, len, "rcvd ");
462 if (len < DLLHEADERLEN) {
463 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
467 p += 2; /* Skip address and control */
468 GETSHORT(protocol, p);
472 * Toss all non-LCP packets unless LCP is OPEN.
474 if (protocol != LCP && lcp_fsm[0].state != OPENED) {
476 "io(): Received non-LCP packet when LCP not open."));
481 * Upcall the proper protocol input routine.
483 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
484 if (prottbl[i].protocol == protocol) {
485 (*prottbl[i].input)(0, p, len);
487 } else if (protocol == (prottbl[i].protocol & ~0x8000)
488 && prottbl[i].datainput != NULL) {
489 (*prottbl[i].datainput)(0, p, len);
493 if (i == sizeof (prottbl) / sizeof (struct protent)) {
494 syslog(LOG_WARNING, "input: Unknown protocol (%x) received!",
496 lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
503 * demuxprotrej - Demultiplex a Protocol-Reject.
506 demuxprotrej(unit, protocol)
513 * Upcall the proper Protocol-Reject routine.
515 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
516 if (prottbl[i].protocol == protocol) {
517 (*prottbl[i].protrej)(unit);
522 "demuxprotrej: Unrecognized Protocol-Reject for protocol %d!",
529 * XXX assume speed_t values numerically equal bits per second
530 * (so we can ask for any speed).
532 #define translate_speed(bps) (bps)
533 #define baud_rate_of(speed) (speed)
537 * List of valid speeds.
540 int speed_int, speed_val;
612 * Translate from bits/second to a speed_t.
618 struct speed *speedp;
622 for (speedp = speeds; speedp->speed_int; speedp++)
623 if (bps == speedp->speed_int)
624 return speedp->speed_val;
625 syslog(LOG_WARNING, "speed %d not supported", bps);
630 * Translate from a speed_t to bits/second.
636 struct speed *speedp;
640 for (speedp = speeds; speedp->speed_int; speedp++)
641 if (speed == speedp->speed_val)
642 return speedp->speed_int;
648 * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
649 * at the requested speed, etc. If `local' is true, set CLOCAL
650 * regardless of whether the modem option was specified.
652 set_up_tty(fd, local)
659 if (tcgetattr(fd, &tios) < 0) {
660 syslog(LOG_ERR, "tcgetattr: %m");
668 tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL | CRTSCTS);
670 tios.c_cflag |= CRTSCTS;
672 tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
675 tios.c_cflag |= CS8 | CREAD | HUPCL;
677 tios.c_cflag |= CLOCAL;
678 tios.c_iflag = IGNBRK | IGNPAR;
682 tios.c_cc[VTIME] = 0;
685 tios.c_iflag |= IXOFF;
686 tios.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */
687 tios.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */
690 speed = translate_speed(inspeed);
692 cfsetospeed(&tios, speed);
693 cfsetispeed(&tios, speed);
695 speed = cfgetospeed(&tios);
698 if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
699 syslog(LOG_ERR, "tcsetattr: %m");
705 if (ioctl(fd, (crtscts || modem)? TIOCMODEM: TIOCNMODEM, &x) < 0)
706 syslog(LOG_WARNING, "TIOC(N)MODEM: %m");
707 if (ioctl(fd, (local || !modem)? TIOCNCAR: TIOCCAR) < 0)
708 syslog(LOG_WARNING, "TIOC(N)CAR: %m");
713 struct sgttyb sgttyb;
716 * Put the tty in raw mode.
718 if (ioctl(fd, TIOCGETP, &sgttyb) < 0) {
719 syslog(LOG_ERR, "ioctl(TIOCGETP): %m");
726 sgttyb.sg_flags = RAW | ANYP;
727 speed = translate_speed(inspeed);
729 sgttyb.sg_ispeed = speed;
731 speed = sgttyb.sg_ispeed;
733 if (ioctl(fd, TIOCSETP, &sgttyb) < 0) {
734 syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
739 baud_rate = inspeed = baud_rate_of(speed);
744 * setdtr - control the DTR line on the serial port.
745 * This is called from die(), so it shouldn't call die().
750 int modembits = TIOCM_DTR;
752 ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
757 * quit - Clean up state and exit.
766 * die - like quit, except we can specify an exit status.
773 syslog(LOG_INFO, "Exit.");
778 * cleanup - restore anything which needs to be restored before we exit
789 if (pidfilename[0] != 0 && unlink(pidfilename) < 0)
790 syslog(LOG_WARNING, "unable to unlink pid file: %m");
793 if (lockflag && !default_device)
798 * close_fd - restore the terminal device and close it.
803 /* drop dtr to hang up */
807 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
808 syslog(LOG_WARNING, "fcntl(F_SETFL, fdflags): %m");
815 if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
817 syslog(LOG_WARNING, "tcsetattr: %m");
819 if (ioctl(fd, TIOCSETP, &initsgttyb) < 0)
820 syslog(LOG_WARNING, "ioctl(TIOCSETP): %m");
830 struct timeval c_time; /* time at which to call routine */
831 caddr_t c_arg; /* argument to routine */
832 void (*c_func)(); /* routine */
833 struct callout *c_next;
836 static struct callout *callout = NULL; /* Callout list */
837 static struct timeval timenow; /* Current time */
840 * timeout - Schedule a timeout.
842 * Note that this timeout takes the number of seconds, NOT hz (as in
846 timeout(func, arg, time)
851 struct callout *newp, *p, **pp;
853 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
854 (int) func, (int) arg, time));
859 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
860 syslog(LOG_ERR, "Out of memory in timeout()!");
865 gettimeofday(&timenow, NULL);
866 newp->c_time.tv_sec = timenow.tv_sec + time;
867 newp->c_time.tv_usec = timenow.tv_usec;
870 * Find correct place and link it in.
872 for (pp = &callout; (p = *pp); pp = &p->c_next)
873 if (p->c_time.tv_sec < newp->c_time.tv_sec
874 || (p->c_time.tv_sec == newp->c_time.tv_sec
875 && p->c_time.tv_usec <= newp->c_time.tv_sec))
883 * untimeout - Unschedule a timeout.
890 struct itimerval itv;
891 struct callout **copp, *freep;
894 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
897 * Find first matching timeout and remove it from the list.
899 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
900 if (freep->c_func == func && freep->c_arg == arg) {
901 *copp = freep->c_next;
902 (void) free((char *) freep);
909 * calltimeout - Call any timeout routines which are now due.
916 while (callout != NULL) {
919 if (gettimeofday(&timenow, NULL) < 0) {
920 syslog(LOG_ERR, "gettimeofday: %m");
923 if (!(p->c_time.tv_sec < timenow.tv_sec
924 || (p->c_time.tv_sec == timenow.tv_sec
925 && p->c_time.tv_usec <= timenow.tv_usec)))
926 break; /* no, it's not time yet */
929 (*p->c_func)(p->c_arg);
937 * timeleft - return the length of time until the next timeout is due.
946 gettimeofday(&timenow, NULL);
947 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
948 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
949 if (tvp->tv_usec < 0) {
950 tvp->tv_usec += 1000000;
954 tvp->tv_sec = tvp->tv_usec = 0;
961 * hup - Catch SIGHUP signal.
963 * Indicates that the physical layer has been disconnected.
964 * We don't rely on this indication; if the user has sent this
965 * signal, we just take the link down.
971 syslog(LOG_INFO, "Hangup (SIGHUP)");
977 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
979 * Indicates that we should initiate a graceful disconnect and exit.
986 syslog(LOG_INFO, "Terminating on signal %d.", sig);
987 persist = 0; /* don't try to restart */
993 * chld - Catch SIGCHLD signal.
994 * Calls reap_kids to get status for any dead kids.
1005 * incdebug - Catch SIGUSR1 signal.
1007 * Increment debug flag.
1014 syslog(LOG_INFO, "Debug turned ON, Level %d", debug);
1015 setlogmask(LOG_UPTO(LOG_DEBUG));
1021 * nodebug - Catch SIGUSR2 signal.
1023 * Turn off debugging.
1030 setlogmask(LOG_UPTO(LOG_WARNING));
1036 * device_script - run a program to connect or disconnect the
1040 device_script(program, in, out)
1049 sigaddset(&mask, SIGINT);
1050 sigaddset(&mask, SIGHUP);
1051 sigprocmask(SIG_BLOCK, &mask, &mask);
1056 syslog(LOG_ERR, "fork: %m");
1061 setreuid(getuid(), getuid());
1062 setregid(getgid(), getgid());
1063 sigprocmask(SIG_SETMASK, &mask, NULL);
1066 execl("/bin/sh", "sh", "-c", program, (char *)0);
1067 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1072 while (waitpid(pid, &status, 0) < 0) {
1075 syslog(LOG_ERR, "waiting for (dis)connection process: %m");
1078 sigprocmask(SIG_SETMASK, &mask, NULL);
1080 return (status == 0 ? 0 : -1);
1085 * run-program - execute a program with given arguments,
1086 * but don't wait for it.
1087 * If the program can't be executed, logs an error unless
1088 * must_exist is 0 and the program file doesn't exist.
1091 run_program(prog, args, must_exist)
1100 syslog(LOG_ERR, "can't fork to run %s: %m", prog);
1105 if (must_exist || errno != ENOENT)
1106 syslog(LOG_WARNING, "can't execute %s: %m", prog);
1109 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1116 * reap_kids - get status from any dead child processes,
1117 * and log a message for abnormal terminations.
1124 if (n_children == 0)
1126 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1127 if (errno != ECHILD)
1128 syslog(LOG_ERR, "waitpid: %m");
1133 if (WIFSIGNALED(status)) {
1134 syslog(LOG_WARNING, "child process %d terminated with signal %d",
1135 pid, WTERMSIG(status));
1142 * log_packet - format a packet and log it.
1145 char line[256]; /* line to be logged accumulated here */
1149 log_packet(p, len, prefix)
1154 strcpy(line, prefix);
1155 linep = line + strlen(line);
1156 format_packet(p, len, pr_log, NULL);
1158 syslog(LOG_DEBUG, "%s", line);
1162 * format_packet - make a readable representation of a packet,
1163 * calling `printer(arg, format, ...)' to output it.
1166 format_packet(p, len, printer, arg)
1169 void (*printer) __ARGS((void *, char *, ...));
1176 if (len >= DLLHEADERLEN && p[0] == ALLSTATIONS && p[1] == UI) {
1179 len -= DLLHEADERLEN;
1180 for (i = 0; i < N_PROTO; ++i)
1181 if (proto == prottbl[i].protocol)
1184 printer(arg, "[%s", prottbl[i].name);
1185 n = (*prottbl[i].printpkt)(p, len, printer, arg);
1190 printer(arg, "[proto=0x%x]", proto);
1194 for (; len > 0; --len) {
1196 printer(arg, " %.2x", x);
1204 pr_log(void *arg, char *fmt, ...)
1210 va_start(pvar, fmt);
1211 vsprintf(buf, fmt, pvar);
1215 if (linep + n + 1 > line + sizeof(line)) {
1216 syslog(LOG_DEBUG, "%s", line);
1223 #else /* __STDC__ */
1224 #include <varargs.h>
1227 pr_log(arg, fmt, va_alist)
1237 vsprintf(buf, fmt, pvar);
1241 if (linep + n + 1 > line + sizeof(line)) {
1242 syslog(LOG_DEBUG, "%s", line);
1251 * print_string - print a readable representation of a string using
1255 print_string(p, len, printer, arg)
1258 void (*printer) __ARGS((void *, char *, ...));
1264 for (; len > 0; --len) {
1266 if (' ' <= c && c <= '~')
1267 printer(arg, "%c", c);
1269 printer(arg, "\\%.3o", c);
1275 * novm - log an error message saying we ran out of memory, and die.
1281 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);