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.1 1993/11/11 03:54:25 paulus Exp $";
42 #include <sys/ioctl.h>
47 #include <sys/param.h>
48 #include <sys/types.h>
50 #include <sys/socket.h>
56 #include <net/if_ppp.h>
73 #include "pathnames.h"
74 #include "patchlevel.h"
86 static char *pidpath = PIDPATH; /* filename in which pid will be stored */
88 static char *pidpath = _PATH_PIDFILE;
92 char ifname[IFNAMSIZ]; /* Interface name */
93 int ifunit; /* Interface unit number */
95 char *progname; /* Name of this program */
96 char hostname[MAXNAMELEN]; /* Our hostname */
97 char our_name[MAXNAMELEN];
98 char remote_name[MAXNAMELEN];
100 static pid_t pid; /* Our pid */
101 static pid_t pgrpid; /* Process Group ID */
102 static char pidfilename[MAXPATHLEN];
104 char devname[MAXPATHLEN] = "/dev/tty"; /* Device name */
105 int default_device = TRUE; /* use default device (stdin/out) */
107 int fd; /* Device file descriptor */
108 int s; /* Socket file descriptor */
111 static struct sgttyb initsgttyb; /* Initial TTY sgttyb */
113 static struct termios inittermios; /* Initial TTY termios */
116 static int initfdflags = -1; /* Initial file descriptor flags */
118 static int restore_term; /* 1 => we've munged the terminal */
120 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
121 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
123 int hungup; /* terminal has been hung up */
125 /* configured variables */
127 int debug = 0; /* Debug flag */
128 char user[MAXNAMELEN]; /* username for PAP */
129 char passwd[MAXSECRETLEN]; /* password for PAP */
130 char *connector = NULL; /* "connect" command */
131 int inspeed = 0; /* Input/Output speed */
132 u_long netmask = 0; /* netmask to use on ppp interface */
133 int crtscts = 0; /* use h/w flow control */
134 int nodetach = 0; /* don't fork */
135 int modem = 0; /* use modem control lines */
136 int auth_required = 0; /* require peer to authenticate */
137 int defaultroute = 0; /* assign default route through interface */
138 int proxyarp = 0; /* set entry in arp table */
139 int persist = 0; /* re-initiate on termination */
140 int answer = 0; /* wait for incoming call */
141 int uselogin = 0; /* check PAP info against /etc/passwd */
145 static void hup __ARGS((int, int, struct sigcontext *, char *));
146 static void intr __ARGS((int, int, struct sigcontext *, char *));
147 static void term __ARGS((int, int, struct sigcontext *, char *));
148 static void alrm __ARGS((int, int, struct sigcontext *, char *));
149 static void io __ARGS((int, int, struct sigcontext *, char *));
150 static void incdebug __ARGS((int));
151 static void nodebug __ARGS((int));
152 void establish_ppp __ARGS((void));
154 void cleanup __ARGS((int, caddr_t));
155 void die __ARGS((int));
156 void dumpbuffer __ARGS((unsigned char *, int, int));
159 extern char *ttyname __ARGS((int));
161 extern char *getlogin __ARGS((void));
164 * PPP Data Link Layer "protocol" table.
165 * One entry per supported protocol.
167 static struct protent {
173 { LCP, lcp_init, lcp_input, lcp_protrej },
174 { IPCP, ipcp_init, ipcp_input, ipcp_protrej },
175 { UPAP, upap_init, upap_input, upap_protrej },
176 { CHAP, ChapInit, ChapInput, ChapProtocolReject },
191 * Initialize syslog system and magic number package.
193 #if BSD >= 43 || defined(sun)
194 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
195 setlogmask(LOG_UPTO(LOG_INFO));
197 openlog("pppd", LOG_PID);
198 #define LOG_UPTO(x) (x)
199 #define setlogmask(x) (x)
203 p = ttyname(fileno(stdin));
210 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
211 syslog(LOG_ERR, "couldn't get hostname: %m");
214 hostname[MAXNAMELEN-1] = 0;
219 * Initialize to the standard option set, then parse, in order,
220 * the system options file, the user's options file, and the command
223 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
224 (*prottbl[i].init)(0);
228 if (!options_from_file(_PATH_SYSOPTIONS) ||
229 !options_from_user() ||
230 !parse_args(argc-1, argv+1))
232 check_auth_options();
238 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
239 VERSION, PATCHLEVEL, p, getuid());
243 * Make sure we can set the serial device to be our controlling terminal.
245 if (default_device) {
247 * No device name was specified:
248 * we are in the device's session already.
250 if ((pgrpid = getpgrp(0)) < 0) {
251 syslog(LOG_ERR, "getpgrp(0): %m");
255 syslog(LOG_WARNING, "warning... not a process group leader");
259 * Not default device: make sure we're not a process group leader,
260 * then become session leader of a new session (so we can make
261 * our device its controlling terminal and thus get SIGHUPs).
264 /* fork so we're not a process group leader */
266 exit(0); /* parent is finished */
269 syslog(LOG_ERR, "fork: %m");
272 pid = getpid(); /* otherwise pid is 0 in child */
275 * try to put ourself into our parent's process group,
276 * so we're not a process group leader
278 if (setpgrp(pid, getppid()) < 0)
279 syslog(LOG_WARNING, "setpgrp: %m");
282 /* create new session */
283 if ((pgrpid = setsid()) < 0) {
284 syslog(LOG_ERR, "setsid(): %m");
290 /* Get an internet socket for doing socket ioctl's on. */
291 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
292 syslog(LOG_ERR, "socket : %m");
297 * Compute mask of all interesting signals and install signal handlers
298 * for each. Only one signal handler may be active at a time. Therefore,
299 * all other signals should be masked when any handler is executing.
302 sigaddset(&mask, SIGHUP);
303 sigaddset(&mask, SIGINT);
304 sigaddset(&mask, SIGALRM);
305 sigaddset(&mask, SIGIO);
307 sigaddset(&mask, SIGPOLL);
310 #define SIGNAL(s, handler) { \
311 sv.sv_handler = handler; \
312 if (sigvec(s, &sv, NULL) < 0) { \
313 syslog(LOG_ERR, "sigvec(%d): %m", s); \
320 SIGNAL(SIGHUP, hup); /* Hangup */
321 SIGNAL(SIGINT, intr); /* Interrupt */
322 SIGNAL(SIGTERM, term); /* Terminate */
323 SIGNAL(SIGALRM, alrm); /* Timeout */
324 SIGNAL(SIGIO, io); /* Input available */
326 SIGNAL(SIGPOLL, io); /* Input available */
329 signal(SIGUSR1, incdebug); /* Increment debug flag */
330 signal(SIGUSR2, nodebug); /* Reset debug flag */
334 * Open the serial device and set it up to be the ppp interface.
336 if ((fd = open(devname, O_RDWR /*| O_NDELAY*/)) < 0) {
337 syslog(LOG_ERR, "open(%s): %m", devname);
342 /* set device to be controlling tty */
343 if (!default_device && ioctl(fd, TIOCSCTTY) < 0) {
344 syslog(LOG_ERR, "ioctl(TIOCSCTTY): %m");
348 /* set line speed, flow control, etc. */
351 /* run connection script */
353 syslog(LOG_INFO, "Connecting with <%s>", connector);
355 /* drop dtr to hang up in case modem is off hook */
356 if (!default_device && modem) {
362 if (set_up_connection(connector, fd, fd) < 0) {
363 syslog(LOG_ERR, "could not set up connection");
368 syslog(LOG_INFO, "Connected...");
369 sleep(1); /* give it time to set up its terminal */
372 /* set up the serial device as a ppp interface */
375 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
376 (void) sprintf(ifname, "ppp%d", ifunit);
378 /* write pid to file */
379 (void) sprintf(pidfilename, "%s/%s.pid", pidpath, ifname);
380 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
381 fprintf(pidfile, "%d\n", pid);
382 (void) fclose(pidfile);
384 syslog(LOG_ERR, "unable to create pid file: %m");
389 * Set process group of device to our process group so we can get SIGIOs.
392 if (default_device) {
393 int id = tcgetpgrp(fd);
396 "warning: not foreground process group leader");
399 if (tcsetpgrp(fd, pgrpid) < 0) {
400 syslog(LOG_ERR, "tcsetpgrp(): %m");
405 /* set process group on tty so we get SIGIO's */
406 if (ioctl(fd, TIOCSPGRP, &pgrpid) < 0) {
407 syslog(LOG_ERR, "ioctl(TIOCSPGRP): %m");
413 * Record initial device flags, then set device to cause SIGIO
414 * signals to be generated.
416 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
417 syslog(LOG_ERR, "fcntl(F_GETFL): %m");
420 if (fcntl(fd, F_SETFL, FNDELAY | FASYNC) == -1) {
421 syslog(LOG_ERR, "fcntl(F_SETFL, FNDELAY | FASYNC): %m");
426 * Block all signals, start opening the connection, and wait for
427 * incoming signals (reply, timeout, etc.).
429 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devname);
430 sigprocmask(SIG_BLOCK, &mask, NULL); /* Block signals now */
431 lcp_lowerup(0); /* XXX Well, sort of... */
432 lcp_open(0); /* Start protocol */
434 sigpause(0); /* Wait for next signal */
440 * XXX assume speed_t values numerically equal bits per second
441 * (so we can ask for any speed).
443 #define translate_speed(bps) (bps)
447 * List of valid speeds.
450 int speed_int, speed_val;
522 * Translate from bits/second to a speed_t.
528 struct speed *speedp;
532 for (speedp = speeds; speedp->speed_int; speedp++)
533 if (bps == speedp->speed_int)
534 return speedp->speed_val;
535 syslog(LOG_WARNING, "speed %d not supported", bps);
541 * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
542 * at the requested speed, etc.
551 if (tcgetattr(fd, &tios) < 0) {
552 syslog(LOG_ERR, "tcgetattr: %m");
559 tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL | CRTSCTS);
560 tios.c_cflag |= CS8 | CREAD | HUPCL;
562 tios.c_cflag |= CRTSCTS;
564 tios.c_cflag |= CLOCAL;
565 tios.c_iflag = IGNBRK | IGNPAR;
569 tios.c_cc[VTIME] = 0;
570 speed = translate_speed(inspeed);
572 cfsetospeed(&tios, speed);
573 cfsetispeed(&tios, speed);
576 if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
577 syslog(LOG_ERR, "tcsetattr: %m");
582 struct sgttyb sgttyb;
585 * Put the tty in raw mode.
587 if (ioctl(fd, TIOCGETP, &sgttyb) < 0) {
588 syslog(LOG_ERR, "ioctl(TIOCGETP): %m");
595 sgttyb.sg_flags = RAW | ANYP;
596 speed = translate_speed(inspeed);
598 sgttyb.sg_ispeed = speed;
600 if (ioctl(fd, TIOCSETP, &sgttyb) < 0) {
601 syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
610 * quit - Clean up state and exit.
619 * die - like quit, except we can specify an exit status.
626 syslog(LOG_INFO, "Exit.");
631 * cleanup - restore anything which needs to be restored before we exit
640 /* drop dtr to hang up */
644 if (fcntl(fd, F_SETFL, initfdflags) < 0)
645 syslog(LOG_ERR, "fcntl(F_SETFL, fdflags): %m");
651 if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
652 syslog(LOG_ERR, "tcsetattr: %m");
654 if (ioctl(fd, TIOCSETP, &initsgttyb) < 0)
655 syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
663 if (pidfilename[0] != 0 && unlink(pidfilename) < 0)
664 syslog(LOG_WARNING, "unable to unlink pid file: %m");
669 static struct callout *callout = NULL; /* Callout list */
670 static struct timeval schedtime; /* Time last timeout was set */
673 * timeout - Schedule a timeout.
675 * Note that this timeout takes the number of seconds, NOT hz (as in
679 timeout(func, arg, time)
684 struct itimerval itv;
685 struct callout *newp, **oldpp;
687 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
688 (int) func, (int) arg, time));
693 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
694 syslog(LOG_ERR, "Out of memory in timeout()!");
701 * Find correct place to link it in and decrement its time by the
702 * amount of time used by preceding timeouts.
704 for (oldpp = &callout;
705 *oldpp && (*oldpp)->c_time <= time;
706 oldpp = &(*oldpp)->c_next)
707 time -= (*oldpp)->c_time;
709 newp->c_next = *oldpp;
711 (*oldpp)->c_time -= time;
715 * If this is now the first callout then we have to set a new
718 if (callout == newp) {
719 itv.it_interval.tv_sec = itv.it_interval.tv_usec =
720 itv.it_value.tv_usec = 0;
721 itv.it_value.tv_sec = callout->c_time;
722 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
723 itv.it_value.tv_sec));
724 if (setitimer(ITIMER_REAL, &itv, NULL)) {
725 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
728 if (gettimeofday(&schedtime, NULL)) {
729 syslog(LOG_ERR, "gettimeofday: %m");
737 * untimeout - Unschedule a timeout.
744 struct itimerval itv;
745 struct callout **copp, *freep;
748 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
751 * If the first callout is unscheduled then we have to set a new
755 callout->c_func == func &&
756 callout->c_arg == arg)
760 * Find first matching timeout. Add its time to the next timeouts
763 for (copp = &callout; *copp; copp = &(*copp)->c_next)
764 if ((*copp)->c_func == func &&
765 (*copp)->c_arg == arg) {
767 *copp = freep->c_next;
769 (*copp)->c_time += freep->c_time;
770 (void) free((char *) freep);
775 itv.it_interval.tv_sec = itv.it_interval.tv_usec =
776 itv.it_value.tv_usec = 0;
777 itv.it_value.tv_sec = callout ? callout->c_time : 0;
778 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
779 itv.it_value.tv_sec));
780 if (setitimer(ITIMER_REAL, &itv, NULL)) {
781 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
784 if (gettimeofday(&schedtime, NULL)) {
785 syslog(LOG_ERR, "gettimeofday: %m");
793 * adjtimeout - Decrement the first timeout by the amount of time since
805 * Make sure that the clock hasn't been warped dramatically.
806 * Account for recently expired, but blocked timer by adding
807 * small fudge factor.
809 if (gettimeofday(&tv, NULL)) {
810 syslog(LOG_ERR, "gettimeofday: %m");
813 timediff = tv.tv_sec - schedtime.tv_sec;
815 timediff > callout->c_time + 1)
818 callout->c_time -= timediff; /* OK, Adjust time */
823 * hup - Catch SIGHUP signal.
825 * Indicates that the physical layer has been disconnected.
829 hup(sig, code, scp, addr)
831 struct sigcontext *scp;
834 syslog(LOG_INFO, "Hangup (SIGHUP)");
836 hungup = 1; /* they hung up on us! */
837 persist = 0; /* don't try to restart */
838 adjtimeout(); /* Adjust timeouts */
839 lcp_lowerdown(0); /* Reset connection */
840 quit(); /* and die */
845 * term - Catch SIGTERM signal.
847 * Indicates that we should initiate a graceful disconnect and exit.
851 term(sig, code, scp, addr)
853 struct sigcontext *scp;
856 syslog(LOG_INFO, "Terminating link.");
857 persist = 0; /* don't try to restart */
858 adjtimeout(); /* Adjust timeouts */
859 lcp_close(0); /* Close connection */
864 * intr - Catch SIGINT signal (DEL/^C).
866 * Indicates that we should initiate a graceful disconnect and exit.
870 intr(sig, code, scp, addr)
872 struct sigcontext *scp;
875 syslog(LOG_INFO, "Interrupt received: terminating link");
876 persist = 0; /* don't try to restart */
877 adjtimeout(); /* Adjust timeouts */
878 lcp_close(0); /* Close connection */
883 * alrm - Catch SIGALRM signal.
885 * Indicates a timeout.
889 alrm(sig, code, scp, addr)
891 struct sigcontext *scp;
894 struct itimerval itv;
895 struct callout *freep;
897 MAINDEBUG((LOG_DEBUG, "Alarm"));
900 * Call and free first scheduled timeout and any that were scheduled
904 freep = callout; /* Remove entry before calling */
905 callout = freep->c_next;
906 (*freep->c_func)(freep->c_arg);
907 (void) free((char *) freep);
908 if (callout && callout->c_time)
913 * Set a new itimer if there are more timeouts scheduled.
916 itv.it_interval.tv_sec = itv.it_interval.tv_usec = 0;
917 itv.it_value.tv_usec = 0;
918 itv.it_value.tv_sec = callout->c_time;
919 MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds.",
920 itv.it_value.tv_sec));
921 if (setitimer(ITIMER_REAL, &itv, NULL)) {
922 syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
925 if (gettimeofday(&schedtime, NULL)) {
926 syslog(LOG_ERR, "gettimeofday: %m");
934 * io - Catch SIGIO signal.
936 * Indicates that incoming data is available.
940 io(sig, code, scp, addr)
942 struct sigcontext *scp;
949 struct timeval notime;
952 MAINDEBUG((LOG_DEBUG, "IO signal received"));
953 adjtimeout(); /* Adjust timeouts */
955 /* we do this to see if the SIGIO handler is being invoked for input */
956 /* ready, or for the socket buffer hitting the low-water mark. */
963 if ((ready = select(32, &fdset, (fd_set *) NULL, (fd_set *) NULL,
965 syslog(LOG_ERR, "Error in io() select: %m");
970 MAINDEBUG((LOG_DEBUG, "IO non-input ready SIGIO occured."));
974 /* Yup, this is for real */
975 for (;;) { /* Read all available packets */
976 p = inpacket_buf; /* point to beginning of packet buffer */
978 len = read_packet(inpacket_buf);
983 syslog(LOG_ERR, "End of file on fd!");
987 if (len < DLLHEADERLEN) {
988 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
992 p += 2; /* Skip address and control */
993 GETSHORT(protocol, p);
997 * Toss all non-LCP packets unless LCP is OPEN.
999 if (protocol != LCP && lcp_fsm[0].state != OPENED) {
1000 MAINDEBUG((LOG_INFO,
1001 "io(): Received non-LCP packet when LCP not open."));
1003 dumpbuffer(inpacket_buf, len + DLLHEADERLEN, LOG_INFO);
1008 * Upcall the proper protocol input routine.
1010 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1011 if (prottbl[i].protocol == protocol) {
1012 (*prottbl[i].input)(0, p, len);
1016 if (i == sizeof (prottbl) / sizeof (struct protent)) {
1017 syslog(LOG_WARNING, "input: Unknown protocol (%x) received!",
1019 lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
1025 * demuxprotrej - Demultiplex a Protocol-Reject.
1028 demuxprotrej(unit, protocol)
1035 * Upcall the proper Protocol-Reject routine.
1037 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1038 if (prottbl[i].protocol == protocol) {
1039 (*prottbl[i].protrej)(unit);
1044 "demuxprotrej: Unrecognized Protocol-Reject for protocol %d!",
1050 * incdebug - Catch SIGUSR1 signal.
1052 * Increment debug flag.
1059 syslog(LOG_INFO, "Debug turned ON, Level %d", debug);
1060 setlogmask(LOG_UPTO(LOG_DEBUG));
1066 * nodebug - Catch SIGUSR2 signal.
1068 * Turn off debugging.
1075 setlogmask(LOG_UPTO(LOG_WARNING));
1081 * set_up_connection - run a program to initialize the serial connector
1084 set_up_connection(program, in, out)
1093 sigaddset(&mask, SIGINT);
1094 sigaddset(&mask, SIGHUP);
1095 sigprocmask(SIG_BLOCK, &mask, &mask);
1100 syslog(LOG_ERR, "fork: %m");
1105 setreuid(getuid(), getuid());
1106 setregid(getgid(), getgid());
1107 sigprocmask(SIG_SETMASK, &mask, NULL);
1110 execl("/bin/sh", "sh", "-c", program, (char *)0);
1111 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1116 while (waitpid(pid, &status, 0) != pid) {
1119 syslog(LOG_ERR, "waiting for connection process: %m");
1122 sigprocmask(SIG_SETMASK, &mask, NULL);
1124 return (status == 0 ? 0 : -1);
1129 * Return user specified netmask. A value of zero means no netmask has
1141 * dumpbuffer - print contents of a buffer in hex to standard output.
1144 dumpbuffer(buffer, size, level)
1145 unsigned char *buffer;
1152 printf("%d bytes:\n", size);
1156 sprintf(p, "%08lx: ", buffer);
1159 for (i = 0; i < 8; i++, p += 3)
1163 sprintf(p, "%02x ", buffer[i]);
1165 for (i = 0; i < 8; i++)
1169 *p++ = (' ' <= buffer[i] && buffer[i] <= '~') ?
1176 /* syslog(level, "%s\n", line); */
1177 printf("%s\n", line);
1184 * setdtr - control the DTR line on the serial port.
1185 * This is called from die(), so it shouldn't call die().
1190 int modembits = TIOCM_DTR;
1192 ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
1195 #include <varargs.h>
1200 logf(level, fmt, va_alist)
1209 vsprintf(buf, fmt, pvar);
1212 p = line + strlen(line);
1215 if (buf[strlen(buf)-1] == '\n') {
1216 syslog(level, "%s", line);
1225 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);