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.18 1994/09/01 00:32:24 paulus Exp $";
33 #include <sys/param.h>
34 #include <sys/types.h>
37 #include <sys/resource.h>
39 #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];
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 */
75 int s; /* Socket file descriptor */
77 int phase; /* where the link is at */
81 static int initfdflags = -1; /* Initial file descriptor flags */
83 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
84 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
86 int hungup; /* terminal has been hung up */
87 static int n_children; /* # child processes still running */
92 static void hup __ARGS((int));
93 static void term __ARGS((int));
94 static void chld __ARGS((int));
95 static void toggle_debug __ARGS((int));
96 static void open_ccp __ARGS((int));
98 static void get_input __ARGS((void));
99 void establish_ppp __ARGS((void));
100 void calltimeout __ARGS((void));
101 struct timeval *timeleft __ARGS((struct timeval *));
102 void reap_kids __ARGS((void));
103 void cleanup __ARGS((int, caddr_t));
104 void close_fd __ARGS((void));
105 void die __ARGS((int));
106 void novm __ARGS((char *));
108 void log_packet __ARGS((u_char *, int, char *));
109 void format_packet __ARGS((u_char *, int,
110 void (*) (void *, char *, ...), void *));
111 void pr_log __ARGS((void *, char *, ...));
113 extern char *ttyname __ARGS((int));
114 extern char *getlogin __ARGS((void));
117 * PPP Data Link Layer "protocol" table.
118 * One entry per supported protocol.
120 static struct protent {
129 { LCP, lcp_init, lcp_input, lcp_protrej, lcp_printpkt, NULL, "LCP" },
130 { IPCP, ipcp_init, ipcp_input, ipcp_protrej, ipcp_printpkt, NULL, "IPCP" },
131 { UPAP, upap_init, upap_input, upap_protrej, upap_printpkt, NULL, "PAP" },
132 { CHAP, ChapInit, ChapInput, ChapProtocolReject, ChapPrintPkt, NULL, "CHAP" },
133 { CCP, ccp_init, ccp_input, ccp_protrej, ccp_printpkt, ccp_datainput, "CCP" },
136 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
155 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
156 perror("couldn't get hostname");
159 hostname[MAXNAMELEN-1] = 0;
163 if (!ppp_available()) {
164 fprintf(stderr, "Sorry - PPP is not available on this system\n");
169 * Initialize to the standard option set, then parse, in order,
170 * the system options file, the user's options file, and the command
173 for (i = 0; i < N_PROTO; i++)
174 (*prottbl[i].init)(0);
178 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
179 !options_from_user() ||
180 !parse_args(argc-1, argv+1) ||
183 check_auth_options();
187 * Initialize system-dependent stuff and magic number package.
193 * Detach ourselves from the terminal, if required,
194 * and identify who is running us.
196 if (!default_device && !nodetach && daemon(0, 0) < 0) {
197 perror("Couldn't detach from controlling terminal");
204 if (pw != NULL && pw->pw_name != NULL)
209 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
210 VERSION, PATCHLEVEL, p, uid);
212 /* Get an internet socket for doing socket ioctl's on. */
213 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
214 syslog(LOG_ERR, "Couldn't create IP socket: %m");
219 * Compute mask of all interesting signals and install signal handlers
220 * for each. Only one signal handler may be active at a time. Therefore,
221 * all other signals should be masked when any handler is executing.
224 sigaddset(&mask, SIGHUP);
225 sigaddset(&mask, SIGINT);
226 sigaddset(&mask, SIGTERM);
227 sigaddset(&mask, SIGCHLD);
229 #define SIGNAL(s, handler) { \
230 sa.sa_handler = handler; \
231 if (sigaction(s, &sa, NULL) < 0) { \
232 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
239 SIGNAL(SIGHUP, hup); /* Hangup */
240 SIGNAL(SIGINT, term); /* Interrupt */
241 SIGNAL(SIGTERM, term); /* Terminate */
242 SIGNAL(SIGCHLD, chld);
244 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
245 signal(SIGUSR2, open_ccp); /* Reopen CCP */
248 * Lock the device if we've been asked to.
250 if (lockflag && !default_device)
251 if (lock(devnam) < 0)
257 * Open the serial device and set it up to be the ppp interface.
258 * If we're dialling out, or we don't want to use the modem lines,
259 * we open it in non-blocking mode, but then we need to clear
260 * the non-blocking I/O bit.
262 nonblock = (connector || !modem)? O_NONBLOCK: 0;
263 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
264 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
267 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
268 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
272 initfdflags &= ~O_NONBLOCK;
273 fcntl(fd, F_SETFL, initfdflags);
278 /* run connection script */
279 if (connector && connector[0]) {
280 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
282 /* set line speed, flow control, etc.; set CLOCAL for now */
285 /* drop dtr to hang up in case modem is off hook */
286 if (!default_device && modem) {
292 if (device_script(connector, fd, fd) < 0) {
293 syslog(LOG_ERR, "Connect script failed");
298 syslog(LOG_INFO, "Connected...");
299 sleep(1); /* give it time to set up its terminal */
302 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
305 /* set up the serial device as a ppp interface */
308 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
309 (void) sprintf(ifname, "ppp%d", ifunit);
311 /* write pid to file */
312 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
313 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
314 fprintf(pidfile, "%d\n", pid);
315 (void) fclose(pidfile);
317 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
322 * Set device for non-blocking reads.
324 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
325 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
330 * Block all signals, start opening the connection, and wait for
331 * incoming events (reply, timeout, etc.).
333 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
335 lcp_open(0); /* Start protocol */
336 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
337 wait_input(timeleft(&timo));
344 if (phase == PHASE_NETWORK) {
345 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
351 reap_kids(); /* Don't leave dead kids lying around */
355 * Run disconnector script, if requested
358 if (device_script(disconnector, fd, fd) < 0) {
359 syslog(LOG_WARNING, "disconnect script failed");
363 syslog(LOG_INFO, "Disconnected...");
367 if (unlink(pidfilename) < 0 && errno != ENOENT)
368 syslog(LOG_WARNING, "unable to delete pid file: %m");
373 if (lockflag && !default_device)
381 * get_input - called when incoming data is available.
390 for (;;) { /* Read all available packets */
391 p = inpacket_buf; /* point to beginning of packet buffer */
393 len = read_packet(inpacket_buf);
398 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
400 lcp_lowerdown(0); /* serial link is no longer available */
405 if (debug /*&& (debugflags & DBG_INPACKET)*/)
406 log_packet(p, len, "rcvd ");
408 if (len < DLLHEADERLEN) {
409 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
413 p += 2; /* Skip address and control */
414 GETSHORT(protocol, p);
418 * Toss all non-LCP packets unless LCP is OPEN.
420 if (protocol != LCP && lcp_fsm[0].state != OPENED) {
422 "io(): Received non-LCP packet when LCP not open."));
427 * Upcall the proper protocol input routine.
429 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
430 if (prottbl[i].protocol == protocol) {
431 (*prottbl[i].input)(0, p, len);
433 } else if (protocol == (prottbl[i].protocol & ~0x8000)
434 && prottbl[i].datainput != NULL) {
435 (*prottbl[i].datainput)(0, p, len);
439 if (i == sizeof (prottbl) / sizeof (struct protent)) {
441 syslog(LOG_WARNING, "Unknown protocol (0x%x) received",
443 lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
450 * demuxprotrej - Demultiplex a Protocol-Reject.
453 demuxprotrej(unit, protocol)
460 * Upcall the proper Protocol-Reject routine.
462 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
463 if (prottbl[i].protocol == protocol) {
464 (*prottbl[i].protrej)(unit);
469 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
475 * quit - Clean up state and exit.
484 * die - like quit, except we can specify an exit status.
491 syslog(LOG_INFO, "Exit.");
496 * cleanup - restore anything which needs to be restored before we exit
507 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
508 syslog(LOG_WARNING, "unable to delete pid file: %m");
511 if (lockflag && !default_device)
516 * close_fd - restore the terminal device and close it.
521 /* drop dtr to hang up */
525 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
526 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
539 struct timeval c_time; /* time at which to call routine */
540 caddr_t c_arg; /* argument to routine */
541 void (*c_func)(); /* routine */
542 struct callout *c_next;
545 static struct callout *callout = NULL; /* Callout list */
546 static struct timeval timenow; /* Current time */
549 * timeout - Schedule a timeout.
551 * Note that this timeout takes the number of seconds, NOT hz (as in
555 timeout(func, arg, time)
560 struct callout *newp, *p, **pp;
562 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
563 (int) func, (int) arg, time));
568 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
569 syslog(LOG_ERR, "Out of memory in timeout()!");
574 gettimeofday(&timenow, NULL);
575 newp->c_time.tv_sec = timenow.tv_sec + time;
576 newp->c_time.tv_usec = timenow.tv_usec;
579 * Find correct place and link it in.
581 for (pp = &callout; (p = *pp); pp = &p->c_next)
582 if (p->c_time.tv_sec < newp->c_time.tv_sec
583 || (p->c_time.tv_sec == newp->c_time.tv_sec
584 && p->c_time.tv_usec <= newp->c_time.tv_sec))
592 * untimeout - Unschedule a timeout.
599 struct itimerval itv;
600 struct callout **copp, *freep;
603 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
606 * Find first matching timeout and remove it from the list.
608 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
609 if (freep->c_func == func && freep->c_arg == arg) {
610 *copp = freep->c_next;
611 (void) free((char *) freep);
618 * calltimeout - Call any timeout routines which are now due.
625 while (callout != NULL) {
628 if (gettimeofday(&timenow, NULL) < 0) {
629 syslog(LOG_ERR, "Failed to get time of day: %m");
632 if (!(p->c_time.tv_sec < timenow.tv_sec
633 || (p->c_time.tv_sec == timenow.tv_sec
634 && p->c_time.tv_usec <= timenow.tv_usec)))
635 break; /* no, it's not time yet */
638 (*p->c_func)(p->c_arg);
646 * timeleft - return the length of time until the next timeout is due.
655 gettimeofday(&timenow, NULL);
656 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
657 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
658 if (tvp->tv_usec < 0) {
659 tvp->tv_usec += 1000000;
663 tvp->tv_sec = tvp->tv_usec = 0;
670 * hup - Catch SIGHUP signal.
672 * Indicates that the physical layer has been disconnected.
673 * We don't rely on this indication; if the user has sent this
674 * signal, we just take the link down.
680 syslog(LOG_INFO, "Hangup (SIGHUP)");
686 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
688 * Indicates that we should initiate a graceful disconnect and exit.
695 syslog(LOG_INFO, "Terminating on signal %d.", sig);
696 persist = 0; /* don't try to restart */
702 * chld - Catch SIGCHLD signal.
703 * Calls reap_kids to get status for any dead kids.
714 * toggle_debug - Catch SIGUSR1 signal.
729 * open_ccp - Catch SIGUSR2 signal.
731 * Try to (re)negotiate compression.
743 * device_script - run a program to connect or disconnect the
747 device_script(program, in, out)
756 sigaddset(&mask, SIGINT);
757 sigaddset(&mask, SIGHUP);
758 sigprocmask(SIG_BLOCK, &mask, &mask);
763 syslog(LOG_ERR, "Failed to create child process: %m");
768 setreuid(getuid(), getuid());
769 setregid(getgid(), getgid());
770 sigprocmask(SIG_SETMASK, &mask, NULL);
773 execl("/bin/sh", "sh", "-c", program, (char *)0);
774 syslog(LOG_ERR, "could not exec /bin/sh: %m");
779 while (waitpid(pid, &status, 0) < 0) {
782 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
785 sigprocmask(SIG_SETMASK, &mask, NULL);
787 return (status == 0 ? 0 : -1);
792 * run-program - execute a program with given arguments,
793 * but don't wait for it.
794 * If the program can't be executed, logs an error unless
795 * must_exist is 0 and the program file doesn't exist.
798 run_program(prog, args, must_exist)
807 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
813 /* Leave the current location */
814 (void) setsid(); /* No controlling tty. */
815 (void) umask (0); /* no umask. Must change in script. */
816 (void) chdir ("/"); /* no current directory. */
818 /* Ensure that nothing of our device environment is inherited. */
822 close (s); /* Socket interface to the ppp device */
823 close (fd); /* tty interface to the ppp device */
825 /* Don't pass handles to the PPP device, even by accident. */
826 new_fd = open (_PATH_DEVNULL, O_RDWR);
829 dup2 (new_fd, 0); /* stdin <- /dev/null */
832 dup2 (0, 1); /* stdout -> /dev/null */
833 dup2 (0, 2); /* stderr -> /dev/null */
836 /* Force the priority back to zero if pppd is running higher. */
837 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
838 syslog (LOG_WARNING, "can't reset priority to 0: %m");
840 /* SysV recommends a second fork at this point. */
842 /* run the program */
844 if (must_exist || errno != ENOENT)
845 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
848 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
855 * reap_kids - get status from any dead child processes,
856 * and log a message for abnormal terminations.
865 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
867 syslog(LOG_ERR, "Error waiting for child process: %m");
872 if (WIFSIGNALED(status)) {
873 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
874 pid, WTERMSIG(status));
881 * log_packet - format a packet and log it.
884 char line[256]; /* line to be logged accumulated here */
888 log_packet(p, len, prefix)
893 strcpy(line, prefix);
894 linep = line + strlen(line);
895 format_packet(p, len, pr_log, NULL);
897 syslog(LOG_DEBUG, "%s", line);
901 * format_packet - make a readable representation of a packet,
902 * calling `printer(arg, format, ...)' to output it.
905 format_packet(p, len, printer, arg)
908 void (*printer) __ARGS((void *, char *, ...));
915 if (len >= DLLHEADERLEN && p[0] == ALLSTATIONS && p[1] == UI) {
919 for (i = 0; i < N_PROTO; ++i)
920 if (proto == prottbl[i].protocol)
923 printer(arg, "[%s", prottbl[i].name);
924 n = (*prottbl[i].printpkt)(p, len, printer, arg);
929 printer(arg, "[proto=0x%x]", proto);
933 for (; len > 0; --len) {
935 printer(arg, " %.2x", x);
943 pr_log(void *arg, char *fmt, ...)
950 vsprintf(buf, fmt, pvar);
954 if (linep + n + 1 > line + sizeof(line)) {
955 syslog(LOG_DEBUG, "%s", line);
966 pr_log(arg, fmt, va_alist)
976 vsprintf(buf, fmt, pvar);
980 if (linep + n + 1 > line + sizeof(line)) {
981 syslog(LOG_DEBUG, "%s", line);
990 * print_string - print a readable representation of a string using
994 print_string(p, len, printer, arg)
997 void (*printer) __ARGS((void *, char *, ...));
1003 for (; len > 0; --len) {
1005 if (' ' <= c && c <= '~')
1006 printer(arg, "%c", c);
1008 printer(arg, "\\%.3o", c);
1014 * novm - log an error message saying we ran out of memory, and die.
1020 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);