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.17 1994/09/01 00:28:14 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
62 static char *pidpath = _PATH_PIDFILE;
65 char ifname[IFNAMSIZ]; /* Interface name */
66 int ifunit; /* Interface unit number */
68 char *progname; /* Name of this program */
69 char hostname[MAXNAMELEN]; /* Our hostname */
70 static char pidfilename[MAXPATHLEN];
72 static pid_t pid; /* Our pid */
73 static pid_t pgrpid; /* Process Group ID */
74 static uid_t uid; /* Our real user-id */
76 int fd = -1; /* Device file descriptor */
77 int s; /* Socket file descriptor */
79 int phase; /* where the link is at */
83 static int initfdflags = -1; /* Initial file descriptor flags */
85 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
86 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
88 int hungup; /* terminal has been hung up */
89 static int n_children; /* # child processes still running */
94 static void hup __ARGS((int));
95 static void term __ARGS((int));
96 static void chld __ARGS((int));
97 static void toggle_debug __ARGS((int));
98 static void open_ccp __ARGS((int));
100 static void get_input __ARGS((void));
101 void establish_ppp __ARGS((void));
102 void calltimeout __ARGS((void));
103 struct timeval *timeleft __ARGS((struct timeval *));
104 void reap_kids __ARGS((void));
105 void cleanup __ARGS((int, caddr_t));
106 void close_fd __ARGS((void));
107 void die __ARGS((int));
108 void novm __ARGS((char *));
110 void log_packet __ARGS((u_char *, int, char *));
111 void format_packet __ARGS((u_char *, int,
112 void (*) (void *, char *, ...), void *));
113 void pr_log __ARGS((void *, char *, ...));
115 extern char *ttyname __ARGS((int));
116 extern char *getlogin __ARGS((void));
119 * PPP Data Link Layer "protocol" table.
120 * One entry per supported protocol.
122 static struct protent {
131 { LCP, lcp_init, lcp_input, lcp_protrej, lcp_printpkt, NULL, "LCP" },
132 { IPCP, ipcp_init, ipcp_input, ipcp_protrej, ipcp_printpkt, NULL, "IPCP" },
133 { UPAP, upap_init, upap_input, upap_protrej, upap_printpkt, NULL, "PAP" },
134 { CHAP, ChapInit, ChapInput, ChapProtocolReject, ChapPrintPkt, NULL, "CHAP" },
135 { CCP, ccp_init, ccp_input, ccp_protrej, ccp_printpkt, ccp_datainput, "CCP" },
138 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
157 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
158 perror("couldn't get hostname");
161 hostname[MAXNAMELEN-1] = 0;
165 if (!ppp_available()) {
166 fprintf(stderr, "Sorry - PPP is not available on this system\n");
171 * Initialize to the standard option set, then parse, in order,
172 * the system options file, the user's options file, and the command
175 for (i = 0; i < N_PROTO; i++)
176 (*prottbl[i].init)(0);
180 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
181 !options_from_user() ||
182 !parse_args(argc-1, argv+1) ||
185 check_auth_options();
189 * Initialize system-dependent stuff and magic number package.
195 * Detach ourselves from the terminal, if required,
196 * and identify who is running us.
198 if (!default_device && !nodetach && daemon(0, 0) < 0) {
199 perror("Couldn't detach from controlling terminal");
206 if (pw != NULL && pw->pw_name != NULL)
211 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
212 VERSION, PATCHLEVEL, p, uid);
214 /* Get an internet socket for doing socket ioctl's on. */
215 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
216 syslog(LOG_ERR, "Couldn't create IP socket: %m");
221 * Compute mask of all interesting signals and install signal handlers
222 * for each. Only one signal handler may be active at a time. Therefore,
223 * all other signals should be masked when any handler is executing.
226 sigaddset(&mask, SIGHUP);
227 sigaddset(&mask, SIGINT);
228 sigaddset(&mask, SIGTERM);
229 sigaddset(&mask, SIGCHLD);
231 #define SIGNAL(s, handler) { \
232 sa.sa_handler = handler; \
233 if (sigaction(s, &sa, NULL) < 0) { \
234 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
241 SIGNAL(SIGHUP, hup); /* Hangup */
242 SIGNAL(SIGINT, term); /* Interrupt */
243 SIGNAL(SIGTERM, term); /* Terminate */
244 SIGNAL(SIGCHLD, chld);
246 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
247 signal(SIGUSR2, open_ccp); /* Reopen CCP */
250 * Lock the device if we've been asked to.
252 if (lockflag && !default_device)
253 if (lock(devnam) < 0)
259 * Open the serial device and set it up to be the ppp interface.
260 * If we're dialling out, or we don't want to use the modem lines,
261 * we open it in non-blocking mode, but then we need to clear
262 * the non-blocking I/O bit.
264 nonblock = (connector || !modem)? O_NONBLOCK: 0;
265 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
266 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
269 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
270 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
274 initfdflags &= ~O_NONBLOCK;
275 fcntl(fd, F_SETFL, initfdflags);
280 /* run connection script */
281 if (connector && connector[0]) {
282 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
284 /* set line speed, flow control, etc.; set CLOCAL for now */
287 /* drop dtr to hang up in case modem is off hook */
288 if (!default_device && modem) {
294 if (device_script(connector, fd, fd) < 0) {
295 syslog(LOG_ERR, "Connect script failed");
300 syslog(LOG_INFO, "Connected...");
301 sleep(1); /* give it time to set up its terminal */
304 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
307 /* set up the serial device as a ppp interface */
310 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
311 (void) sprintf(ifname, "ppp%d", ifunit);
313 /* write pid to file */
314 (void) sprintf(pidfilename, "%s/%s.pid", pidpath, ifname);
315 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
316 fprintf(pidfile, "%d\n", pid);
317 (void) fclose(pidfile);
319 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
324 * Set device for non-blocking reads.
326 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
327 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
332 * Block all signals, start opening the connection, and wait for
333 * incoming events (reply, timeout, etc.).
335 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
337 lcp_open(0); /* Start protocol */
338 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
339 wait_input(timeleft(&timo));
346 if (phase == PHASE_NETWORK) {
347 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
353 reap_kids(); /* Don't leave dead kids lying around */
357 * Run disconnector script, if requested
360 if (device_script(disconnector, fd, fd) < 0) {
361 syslog(LOG_WARNING, "disconnect script failed");
365 syslog(LOG_INFO, "Disconnected...");
369 if (unlink(pidfilename) < 0 && errno != ENOENT)
370 syslog(LOG_WARNING, "unable to delete pid file: %m");
375 if (lockflag && !default_device)
383 * get_input - called when incoming data is available.
392 for (;;) { /* Read all available packets */
393 p = inpacket_buf; /* point to beginning of packet buffer */
395 len = read_packet(inpacket_buf);
400 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
402 lcp_lowerdown(0); /* serial link is no longer available */
407 if (debug /*&& (debugflags & DBG_INPACKET)*/)
408 log_packet(p, len, "rcvd ");
410 if (len < DLLHEADERLEN) {
411 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
415 p += 2; /* Skip address and control */
416 GETSHORT(protocol, p);
420 * Toss all non-LCP packets unless LCP is OPEN.
422 if (protocol != LCP && lcp_fsm[0].state != OPENED) {
424 "io(): Received non-LCP packet when LCP not open."));
429 * Upcall the proper protocol input routine.
431 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
432 if (prottbl[i].protocol == protocol) {
433 (*prottbl[i].input)(0, p, len);
435 } else if (protocol == (prottbl[i].protocol & ~0x8000)
436 && prottbl[i].datainput != NULL) {
437 (*prottbl[i].datainput)(0, p, len);
441 if (i == sizeof (prottbl) / sizeof (struct protent)) {
443 syslog(LOG_WARNING, "Unknown protocol (0x%x) received",
445 lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
452 * demuxprotrej - Demultiplex a Protocol-Reject.
455 demuxprotrej(unit, protocol)
462 * Upcall the proper Protocol-Reject routine.
464 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
465 if (prottbl[i].protocol == protocol) {
466 (*prottbl[i].protrej)(unit);
471 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
477 * quit - Clean up state and exit.
486 * die - like quit, except we can specify an exit status.
493 syslog(LOG_INFO, "Exit.");
498 * cleanup - restore anything which needs to be restored before we exit
509 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
510 syslog(LOG_WARNING, "unable to delete pid file: %m");
513 if (lockflag && !default_device)
518 * close_fd - restore the terminal device and close it.
523 /* drop dtr to hang up */
527 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
528 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
541 struct timeval c_time; /* time at which to call routine */
542 caddr_t c_arg; /* argument to routine */
543 void (*c_func)(); /* routine */
544 struct callout *c_next;
547 static struct callout *callout = NULL; /* Callout list */
548 static struct timeval timenow; /* Current time */
551 * timeout - Schedule a timeout.
553 * Note that this timeout takes the number of seconds, NOT hz (as in
557 timeout(func, arg, time)
562 struct callout *newp, *p, **pp;
564 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
565 (int) func, (int) arg, time));
570 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
571 syslog(LOG_ERR, "Out of memory in timeout()!");
576 gettimeofday(&timenow, NULL);
577 newp->c_time.tv_sec = timenow.tv_sec + time;
578 newp->c_time.tv_usec = timenow.tv_usec;
581 * Find correct place and link it in.
583 for (pp = &callout; (p = *pp); pp = &p->c_next)
584 if (p->c_time.tv_sec < newp->c_time.tv_sec
585 || (p->c_time.tv_sec == newp->c_time.tv_sec
586 && p->c_time.tv_usec <= newp->c_time.tv_sec))
594 * untimeout - Unschedule a timeout.
601 struct itimerval itv;
602 struct callout **copp, *freep;
605 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
608 * Find first matching timeout and remove it from the list.
610 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
611 if (freep->c_func == func && freep->c_arg == arg) {
612 *copp = freep->c_next;
613 (void) free((char *) freep);
620 * calltimeout - Call any timeout routines which are now due.
627 while (callout != NULL) {
630 if (gettimeofday(&timenow, NULL) < 0) {
631 syslog(LOG_ERR, "Failed to get time of day: %m");
634 if (!(p->c_time.tv_sec < timenow.tv_sec
635 || (p->c_time.tv_sec == timenow.tv_sec
636 && p->c_time.tv_usec <= timenow.tv_usec)))
637 break; /* no, it's not time yet */
640 (*p->c_func)(p->c_arg);
648 * timeleft - return the length of time until the next timeout is due.
657 gettimeofday(&timenow, NULL);
658 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
659 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
660 if (tvp->tv_usec < 0) {
661 tvp->tv_usec += 1000000;
665 tvp->tv_sec = tvp->tv_usec = 0;
672 * hup - Catch SIGHUP signal.
674 * Indicates that the physical layer has been disconnected.
675 * We don't rely on this indication; if the user has sent this
676 * signal, we just take the link down.
682 syslog(LOG_INFO, "Hangup (SIGHUP)");
688 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
690 * Indicates that we should initiate a graceful disconnect and exit.
697 syslog(LOG_INFO, "Terminating on signal %d.", sig);
698 persist = 0; /* don't try to restart */
704 * chld - Catch SIGCHLD signal.
705 * Calls reap_kids to get status for any dead kids.
716 * toggle_debug - Catch SIGUSR1 signal.
731 * open_ccp - Catch SIGUSR2 signal.
733 * Try to (re)negotiate compression.
745 * device_script - run a program to connect or disconnect the
749 device_script(program, in, out)
758 sigaddset(&mask, SIGINT);
759 sigaddset(&mask, SIGHUP);
760 sigprocmask(SIG_BLOCK, &mask, &mask);
765 syslog(LOG_ERR, "Failed to create child process: %m");
770 setreuid(getuid(), getuid());
771 setregid(getgid(), getgid());
772 sigprocmask(SIG_SETMASK, &mask, NULL);
775 execl("/bin/sh", "sh", "-c", program, (char *)0);
776 syslog(LOG_ERR, "could not exec /bin/sh: %m");
781 while (waitpid(pid, &status, 0) < 0) {
784 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
787 sigprocmask(SIG_SETMASK, &mask, NULL);
789 return (status == 0 ? 0 : -1);
794 * run-program - execute a program with given arguments,
795 * but don't wait for it.
796 * If the program can't be executed, logs an error unless
797 * must_exist is 0 and the program file doesn't exist.
800 run_program(prog, args, must_exist)
809 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
815 /* Leave the current location */
816 (void) setsid(); /* No controlling tty. */
817 (void) umask (0); /* no umask. Must change in script. */
818 (void) chdir ("/"); /* no current directory. */
820 /* Ensure that nothing of our device environment is inherited. */
824 close (s); /* Socket interface to the ppp device */
825 close (fd); /* tty interface to the ppp device */
827 /* Don't pass handles to the PPP device, even by accident. */
828 new_fd = open (_PATH_DEVNULL, O_RDWR);
831 dup2 (new_fd, 0); /* stdin <- /dev/null */
834 dup2 (0, 1); /* stdout -> /dev/null */
835 dup2 (0, 2); /* stderr -> /dev/null */
838 /* Force the priority back to zero if pppd is running higher. */
839 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
840 syslog (LOG_WARNING, "can't reset priority to 0: %m");
842 /* SysV recommends a second fork at this point. */
844 /* run the program */
846 if (must_exist || errno != ENOENT)
847 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
850 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
857 * reap_kids - get status from any dead child processes,
858 * and log a message for abnormal terminations.
867 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
869 syslog(LOG_ERR, "Error waiting for child process: %m");
874 if (WIFSIGNALED(status)) {
875 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
876 pid, WTERMSIG(status));
883 * log_packet - format a packet and log it.
886 char line[256]; /* line to be logged accumulated here */
890 log_packet(p, len, prefix)
895 strcpy(line, prefix);
896 linep = line + strlen(line);
897 format_packet(p, len, pr_log, NULL);
899 syslog(LOG_DEBUG, "%s", line);
903 * format_packet - make a readable representation of a packet,
904 * calling `printer(arg, format, ...)' to output it.
907 format_packet(p, len, printer, arg)
910 void (*printer) __ARGS((void *, char *, ...));
917 if (len >= DLLHEADERLEN && p[0] == ALLSTATIONS && p[1] == UI) {
921 for (i = 0; i < N_PROTO; ++i)
922 if (proto == prottbl[i].protocol)
925 printer(arg, "[%s", prottbl[i].name);
926 n = (*prottbl[i].printpkt)(p, len, printer, arg);
931 printer(arg, "[proto=0x%x]", proto);
935 for (; len > 0; --len) {
937 printer(arg, " %.2x", x);
945 pr_log(void *arg, char *fmt, ...)
952 vsprintf(buf, fmt, pvar);
956 if (linep + n + 1 > line + sizeof(line)) {
957 syslog(LOG_DEBUG, "%s", line);
968 pr_log(arg, fmt, va_alist)
978 vsprintf(buf, fmt, pvar);
982 if (linep + n + 1 > line + sizeof(line)) {
983 syslog(LOG_DEBUG, "%s", line);
992 * print_string - print a readable representation of a string using
996 print_string(p, len, printer, arg)
999 void (*printer) __ARGS((void *, char *, ...));
1005 for (; len > 0; --len) {
1007 if (' ' <= c && c <= '~')
1008 printer(arg, "%c", c);
1010 printer(arg, "\\%.3o", c);
1016 * novm - log an error message saying we ran out of memory, and die.
1022 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);