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.2 1993/11/23 23:40:53 paulus Exp $";
35 * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
36 * /etc/ppp/options exists.
38 #ifndef REQ_SYSOPTIONS
39 #define REQ_SYSOPTIONS 0
50 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <sys/types.h>
58 #include <sys/socket.h>
64 #include <net/if_ppp.h>
81 #include "pathnames.h"
82 #include "patchlevel.h"
94 static char *pidpath = PIDPATH; /* filename in which pid will be stored */
96 static char *pidpath = _PATH_PIDFILE;
100 char ifname[IFNAMSIZ]; /* Interface name */
101 int ifunit; /* Interface unit number */
103 char *progname; /* Name of this program */
104 char hostname[MAXNAMELEN]; /* Our hostname */
105 char our_name[MAXNAMELEN];
106 char remote_name[MAXNAMELEN];
108 static pid_t pid; /* Our pid */
109 static pid_t pgrpid; /* Process Group ID */
110 static char pidfilename[MAXPATHLEN];
112 char devname[MAXPATHLEN] = "/dev/tty"; /* Device name */
113 int default_device = TRUE; /* use default device (stdin/out) */
115 int fd; /* Device file descriptor */
116 int s; /* Socket file descriptor */
119 static struct sgttyb initsgttyb; /* Initial TTY sgttyb */
121 static struct termios inittermios; /* Initial TTY termios */
124 static int initfdflags = -1; /* Initial file descriptor flags */
126 static int restore_term; /* 1 => we've munged the terminal */
128 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
129 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
131 int hungup; /* terminal has been hung up */
133 /* configured variables */
135 int debug = 0; /* Debug flag */
136 char user[MAXNAMELEN]; /* username for PAP */
137 char passwd[MAXSECRETLEN]; /* password for PAP */
138 char *connector = NULL; /* "connect" command */
139 int inspeed = 0; /* Input/Output speed */
140 u_long netmask = 0; /* netmask to use on ppp interface */
141 int crtscts = 0; /* use h/w flow control */
142 int nodetach = 0; /* don't fork */
143 int modem = 0; /* use modem control lines */
144 int auth_required = 0; /* require peer to authenticate */
145 int defaultroute = 0; /* assign default route through interface */
146 int proxyarp = 0; /* set entry in arp table */
147 int persist = 0; /* re-initiate on termination */
148 int answer = 0; /* wait for incoming call */
149 int uselogin = 0; /* check PAP info against /etc/passwd */
153 static void hup __ARGS((int, int, struct sigcontext *, char *));
154 static void intr __ARGS((int, int, struct sigcontext *, char *));
155 static void term __ARGS((int, int, struct sigcontext *, char *));
156 static void alrm __ARGS((int, int, struct sigcontext *, char *));
157 static void io __ARGS((int, int, struct sigcontext *, char *));
158 static void incdebug __ARGS((int));
159 static void nodebug __ARGS((int));
160 void establish_ppp __ARGS((void));
162 void cleanup __ARGS((int, caddr_t));
163 void die __ARGS((int));
164 void dumpbuffer __ARGS((unsigned char *, int, int));
167 extern char *ttyname __ARGS((int));
169 extern char *getlogin __ARGS((void));
172 * PPP Data Link Layer "protocol" table.
173 * One entry per supported protocol.
175 static struct protent {
181 { LCP, lcp_init, lcp_input, lcp_protrej },
182 { IPCP, ipcp_init, ipcp_input, ipcp_protrej },
183 { UPAP, upap_init, upap_input, upap_protrej },
184 { CHAP, ChapInit, ChapInput, ChapProtocolReject },
199 * Initialize syslog system and magic number package.
201 #if BSD >= 43 || defined(sun)
202 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
203 setlogmask(LOG_UPTO(LOG_INFO));
205 openlog("pppd", LOG_PID);
206 #define LOG_UPTO(x) (x)
207 #define setlogmask(x) (x)
211 p = ttyname(fileno(stdin));
218 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
219 syslog(LOG_ERR, "couldn't get hostname: %m");
222 hostname[MAXNAMELEN-1] = 0;
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 < sizeof (prottbl) / sizeof (struct protent); i++)
232 (*prottbl[i].init)(0);
236 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS) ||
237 !options_from_user() ||
238 !parse_args(argc-1, argv+1))
240 check_auth_options();
246 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
247 VERSION, PATCHLEVEL, p, getuid());
251 * Make sure we can set the serial device to be our controlling terminal.
253 if (default_device) {
255 * No device name was specified:
256 * we are in the device's session already.
258 if ((pgrpid = getpgrp(0)) < 0) {
259 syslog(LOG_ERR, "getpgrp(0): %m");
263 syslog(LOG_WARNING, "warning... not a process group leader");
267 * Not default device: make sure we're not a process group leader,
268 * then become session leader of a new session (so we can make
269 * our device its controlling terminal and thus get SIGHUPs).
272 /* fork so we're not a process group leader */
274 exit(0); /* parent is finished */
277 syslog(LOG_ERR, "fork: %m");
280 pid = getpid(); /* otherwise pid is 0 in child */
283 * try to put ourself into our parent's process group,
284 * so we're not a process group leader
286 if (setpgrp(pid, getppid()) < 0)
287 syslog(LOG_WARNING, "setpgrp: %m");
290 /* create new session */
291 if ((pgrpid = setsid()) < 0) {
292 syslog(LOG_ERR, "setsid(): %m");
298 /* Get an internet socket for doing socket ioctl's on. */
299 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
300 syslog(LOG_ERR, "socket : %m");
305 * Compute mask of all interesting signals and install signal handlers
306 * for each. Only one signal handler may be active at a time. Therefore,
307 * all other signals should be masked when any handler is executing.
310 sigaddset(&mask, SIGHUP);
311 sigaddset(&mask, SIGINT);
312 sigaddset(&mask, SIGALRM);
313 sigaddset(&mask, SIGIO);
315 sigaddset(&mask, SIGPOLL);
318 #define SIGNAL(s, handler) { \
319 sv.sv_handler = handler; \
320 if (sigvec(s, &sv, NULL) < 0) { \
321 syslog(LOG_ERR, "sigvec(%d): %m", s); \
328 SIGNAL(SIGHUP, hup); /* Hangup */
329 SIGNAL(SIGINT, intr); /* Interrupt */
330 SIGNAL(SIGTERM, term); /* Terminate */
331 SIGNAL(SIGALRM, alrm); /* Timeout */
332 SIGNAL(SIGIO, io); /* Input available */
334 SIGNAL(SIGPOLL, io); /* Input available */
337 signal(SIGUSR1, incdebug); /* Increment debug flag */
338 signal(SIGUSR2, nodebug); /* Reset debug flag */
342 * Open the serial device and set it up to be the ppp interface.
344 if ((fd = open(devname, O_RDWR /*| O_NDELAY*/)) < 0) {
345 syslog(LOG_ERR, "open(%s): %m", devname);
350 /* set device to be controlling tty */
351 if (!default_device && ioctl(fd, TIOCSCTTY) < 0) {
352 syslog(LOG_ERR, "ioctl(TIOCSCTTY): %m");
356 /* set line speed, flow control, etc. */
359 /* run connection script */
361 syslog(LOG_INFO, "Connecting with <%s>", connector);
363 /* drop dtr to hang up in case modem is off hook */
364 if (!default_device && modem) {
370 if (set_up_connection(connector, fd, fd) < 0) {
371 syslog(LOG_ERR, "could not set up connection");
376 syslog(LOG_INFO, "Connected...");
377 sleep(1); /* give it time to set up its terminal */
380 /* set up the serial device as a ppp interface */
383 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
384 (void) sprintf(ifname, "ppp%d", ifunit);
386 /* write pid to file */
387 (void) sprintf(pidfilename, "%s/%s.pid", pidpath, ifname);
388 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
389 fprintf(pidfile, "%d\n", pid);
390 (void) fclose(pidfile);
392 syslog(LOG_ERR, "unable to create pid file: %m");
397 * Set process group of device to our process group so we can get SIGIOs.
400 if (default_device) {
401 int id = tcgetpgrp(fd);
404 "warning: not foreground process group leader");
407 if (tcsetpgrp(fd, pgrpid) < 0) {
408 syslog(LOG_ERR, "tcsetpgrp(): %m");
413 /* set process group on tty so we get SIGIO's */
414 if (ioctl(fd, TIOCSPGRP, &pgrpid) < 0) {
415 syslog(LOG_ERR, "ioctl(TIOCSPGRP): %m");
421 * Record initial device flags, then set device to cause SIGIO
422 * signals to be generated.
424 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
425 syslog(LOG_ERR, "fcntl(F_GETFL): %m");
428 if (fcntl(fd, F_SETFL, FNDELAY | FASYNC) == -1) {
429 syslog(LOG_ERR, "fcntl(F_SETFL, FNDELAY | FASYNC): %m");
434 * Block all signals, start opening the connection, and wait for
435 * incoming signals (reply, timeout, etc.).
437 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devname);
438 sigprocmask(SIG_BLOCK, &mask, NULL); /* Block signals now */
439 lcp_lowerup(0); /* XXX Well, sort of... */
440 lcp_open(0); /* Start protocol */
442 sigpause(0); /* Wait for next signal */
448 * XXX assume speed_t values numerically equal bits per second
449 * (so we can ask for any speed).
451 #define translate_speed(bps) (bps)
455 * List of valid speeds.
458 int speed_int, speed_val;
530 * Translate from bits/second to a speed_t.
536 struct speed *speedp;
540 for (speedp = speeds; speedp->speed_int; speedp++)
541 if (bps == speedp->speed_int)
542 return speedp->speed_val;
543 syslog(LOG_WARNING, "speed %d not supported", bps);
549 * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
550 * at the requested speed, etc.
559 if (tcgetattr(fd, &tios) < 0) {
560 syslog(LOG_ERR, "tcgetattr: %m");
567 tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL | CRTSCTS);
568 tios.c_cflag |= CS8 | CREAD | HUPCL;
570 tios.c_cflag |= CRTSCTS;
572 tios.c_cflag |= CLOCAL;
573 tios.c_iflag = IGNBRK | IGNPAR;
577 tios.c_cc[VTIME] = 0;
578 speed = translate_speed(inspeed);
580 cfsetospeed(&tios, speed);
581 cfsetispeed(&tios, speed);
584 if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
585 syslog(LOG_ERR, "tcsetattr: %m");
590 struct sgttyb sgttyb;
593 * Put the tty in raw mode.
595 if (ioctl(fd, TIOCGETP, &sgttyb) < 0) {
596 syslog(LOG_ERR, "ioctl(TIOCGETP): %m");
603 sgttyb.sg_flags = RAW | ANYP;
604 speed = translate_speed(inspeed);
606 sgttyb.sg_ispeed = speed;
608 if (ioctl(fd, TIOCSETP, &sgttyb) < 0) {
609 syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
618 * quit - Clean up state and exit.
627 * die - like quit, except we can specify an exit status.
634 syslog(LOG_INFO, "Exit.");
639 * cleanup - restore anything which needs to be restored before we exit
648 /* drop dtr to hang up */
652 if (fcntl(fd, F_SETFL, initfdflags) < 0)
653 syslog(LOG_ERR, "fcntl(F_SETFL, fdflags): %m");
659 if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
660 syslog(LOG_ERR, "tcsetattr: %m");
662 if (ioctl(fd, TIOCSETP, &initsgttyb) < 0)
663 syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
671 if (pidfilename[0] != 0 && unlink(pidfilename) < 0)
672 syslog(LOG_WARNING, "unable to unlink pid file: %m");
677 static struct callout *callout = NULL; /* Callout list */
678 static struct timeval schedtime; /* Time last timeout was set */
681 * timeout - Schedule a timeout.
683 * Note that this timeout takes the number of seconds, NOT hz (as in
687 timeout(func, arg, time)
692 struct itimerval itv;
693 struct callout *newp, **oldpp;
695 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
696 (int) func, (int) arg, time));
701 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
702 syslog(LOG_ERR, "Out of memory in timeout()!");
709 * Find correct place to link it in and decrement its time by the
710 * amount of time used by preceding timeouts.
712 for (oldpp = &callout;
713 *oldpp && (*oldpp)->c_time <= time;
714 oldpp = &(*oldpp)->c_next)
715 time -= (*oldpp)->c_time;
717 newp->c_next = *oldpp;
719 (*oldpp)->c_time -= time;
723 * If this is now the first callout then we have to set a new
726 if (callout == newp) {
727 itv.it_interval.tv_sec = itv.it_interval.tv_usec =
728 itv.it_value.tv_usec = 0;
729 itv.it_value.tv_sec = callout->c_time;
730 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
731 itv.it_value.tv_sec));
732 if (setitimer(ITIMER_REAL, &itv, NULL)) {
733 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
736 if (gettimeofday(&schedtime, NULL)) {
737 syslog(LOG_ERR, "gettimeofday: %m");
745 * untimeout - Unschedule a timeout.
752 struct itimerval itv;
753 struct callout **copp, *freep;
756 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
759 * If the first callout is unscheduled then we have to set a new
763 callout->c_func == func &&
764 callout->c_arg == arg)
768 * Find first matching timeout. Add its time to the next timeouts
771 for (copp = &callout; *copp; copp = &(*copp)->c_next)
772 if ((*copp)->c_func == func &&
773 (*copp)->c_arg == arg) {
775 *copp = freep->c_next;
777 (*copp)->c_time += freep->c_time;
778 (void) free((char *) freep);
783 itv.it_interval.tv_sec = itv.it_interval.tv_usec =
784 itv.it_value.tv_usec = 0;
785 itv.it_value.tv_sec = callout ? callout->c_time : 0;
786 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
787 itv.it_value.tv_sec));
788 if (setitimer(ITIMER_REAL, &itv, NULL)) {
789 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
792 if (gettimeofday(&schedtime, NULL)) {
793 syslog(LOG_ERR, "gettimeofday: %m");
801 * adjtimeout - Decrement the first timeout by the amount of time since
813 * Make sure that the clock hasn't been warped dramatically.
814 * Account for recently expired, but blocked timer by adding
815 * small fudge factor.
817 if (gettimeofday(&tv, NULL)) {
818 syslog(LOG_ERR, "gettimeofday: %m");
821 timediff = tv.tv_sec - schedtime.tv_sec;
823 timediff > callout->c_time + 1)
826 callout->c_time -= timediff; /* OK, Adjust time */
831 * hup - Catch SIGHUP signal.
833 * Indicates that the physical layer has been disconnected.
837 hup(sig, code, scp, addr)
839 struct sigcontext *scp;
842 syslog(LOG_INFO, "Hangup (SIGHUP)");
844 hungup = 1; /* they hung up on us! */
845 persist = 0; /* don't try to restart */
846 adjtimeout(); /* Adjust timeouts */
847 lcp_lowerdown(0); /* Reset connection */
848 quit(); /* and die */
853 * term - Catch SIGTERM signal.
855 * Indicates that we should initiate a graceful disconnect and exit.
859 term(sig, code, scp, addr)
861 struct sigcontext *scp;
864 syslog(LOG_INFO, "Terminating link.");
865 persist = 0; /* don't try to restart */
866 adjtimeout(); /* Adjust timeouts */
867 lcp_close(0); /* Close connection */
872 * intr - Catch SIGINT signal (DEL/^C).
874 * Indicates that we should initiate a graceful disconnect and exit.
878 intr(sig, code, scp, addr)
880 struct sigcontext *scp;
883 syslog(LOG_INFO, "Interrupt received: terminating link");
884 persist = 0; /* don't try to restart */
885 adjtimeout(); /* Adjust timeouts */
886 lcp_close(0); /* Close connection */
891 * alrm - Catch SIGALRM signal.
893 * Indicates a timeout.
897 alrm(sig, code, scp, addr)
899 struct sigcontext *scp;
902 struct itimerval itv;
903 struct callout *freep;
905 MAINDEBUG((LOG_DEBUG, "Alarm"));
908 * Call and free first scheduled timeout and any that were scheduled
912 freep = callout; /* Remove entry before calling */
913 callout = freep->c_next;
914 (*freep->c_func)(freep->c_arg);
915 (void) free((char *) freep);
916 if (callout && callout->c_time)
921 * Set a new itimer if there are more timeouts scheduled.
924 itv.it_interval.tv_sec = itv.it_interval.tv_usec = 0;
925 itv.it_value.tv_usec = 0;
926 itv.it_value.tv_sec = callout->c_time;
927 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
928 itv.it_value.tv_sec));
929 if (setitimer(ITIMER_REAL, &itv, NULL)) {
930 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
933 if (gettimeofday(&schedtime, NULL)) {
934 syslog(LOG_ERR, "gettimeofday: %m");
942 * io - Catch SIGIO signal.
944 * Indicates that incoming data is available.
948 io(sig, code, scp, addr)
950 struct sigcontext *scp;
957 struct timeval notime;
960 MAINDEBUG((LOG_DEBUG, "IO signal received"));
961 adjtimeout(); /* Adjust timeouts */
963 /* we do this to see if the SIGIO handler is being invoked for input */
964 /* ready, or for the socket buffer hitting the low-water mark. */
971 if ((ready = select(32, &fdset, (fd_set *) NULL, (fd_set *) NULL,
973 syslog(LOG_ERR, "Error in io() select: %m");
978 MAINDEBUG((LOG_DEBUG, "IO non-input ready SIGIO occured."));
982 /* Yup, this is for real */
983 for (;;) { /* Read all available packets */
984 p = inpacket_buf; /* point to beginning of packet buffer */
986 len = read_packet(inpacket_buf);
991 syslog(LOG_ERR, "End of file on fd!");
995 if (len < DLLHEADERLEN) {
996 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
1000 p += 2; /* Skip address and control */
1001 GETSHORT(protocol, p);
1002 len -= DLLHEADERLEN;
1005 * Toss all non-LCP packets unless LCP is OPEN.
1007 if (protocol != LCP && lcp_fsm[0].state != OPENED) {
1008 MAINDEBUG((LOG_INFO,
1009 "io(): Received non-LCP packet when LCP not open."));
1011 dumpbuffer(inpacket_buf, len + DLLHEADERLEN, LOG_INFO);
1016 * Upcall the proper protocol input routine.
1018 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1019 if (prottbl[i].protocol == protocol) {
1020 (*prottbl[i].input)(0, p, len);
1024 if (i == sizeof (prottbl) / sizeof (struct protent)) {
1025 syslog(LOG_WARNING, "input: Unknown protocol (%x) received!",
1027 lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
1033 * demuxprotrej - Demultiplex a Protocol-Reject.
1036 demuxprotrej(unit, protocol)
1043 * Upcall the proper Protocol-Reject routine.
1045 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1046 if (prottbl[i].protocol == protocol) {
1047 (*prottbl[i].protrej)(unit);
1052 "demuxprotrej: Unrecognized Protocol-Reject for protocol %d!",
1058 * incdebug - Catch SIGUSR1 signal.
1060 * Increment debug flag.
1067 syslog(LOG_INFO, "Debug turned ON, Level %d", debug);
1068 setlogmask(LOG_UPTO(LOG_DEBUG));
1074 * nodebug - Catch SIGUSR2 signal.
1076 * Turn off debugging.
1083 setlogmask(LOG_UPTO(LOG_WARNING));
1089 * set_up_connection - run a program to initialize the serial connector
1092 set_up_connection(program, in, out)
1101 sigaddset(&mask, SIGINT);
1102 sigaddset(&mask, SIGHUP);
1103 sigprocmask(SIG_BLOCK, &mask, &mask);
1108 syslog(LOG_ERR, "fork: %m");
1113 setreuid(getuid(), getuid());
1114 setregid(getgid(), getgid());
1115 sigprocmask(SIG_SETMASK, &mask, NULL);
1118 execl("/bin/sh", "sh", "-c", program, (char *)0);
1119 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1124 while (waitpid(pid, &status, 0) != pid) {
1127 syslog(LOG_ERR, "waiting for connection process: %m");
1130 sigprocmask(SIG_SETMASK, &mask, NULL);
1132 return (status == 0 ? 0 : -1);
1137 * Return user specified netmask. A value of zero means no netmask has
1149 * dumpbuffer - print contents of a buffer in hex to standard output.
1152 dumpbuffer(buffer, size, level)
1153 unsigned char *buffer;
1160 printf("%d bytes:\n", size);
1164 sprintf(p, "%08lx: ", buffer);
1167 for (i = 0; i < 8; i++, p += 3)
1171 sprintf(p, "%02x ", buffer[i]);
1173 for (i = 0; i < 8; i++)
1177 *p++ = (' ' <= buffer[i] && buffer[i] <= '~') ?
1184 /* syslog(level, "%s\n", line); */
1185 printf("%s\n", line);
1192 * setdtr - control the DTR line on the serial port.
1193 * This is called from die(), so it shouldn't call die().
1198 int modembits = TIOCM_DTR;
1200 ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
1203 #include <varargs.h>
1208 logf(level, fmt, va_alist)
1217 vsprintf(buf, fmt, pvar);
1220 p = line + strlen(line);
1223 if (buf[strlen(buf)-1] == '\n') {
1224 syslog(level, "%s", line);
1233 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);