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.19 1994/09/21 06:47:37 paulus Exp $";
33 #include <sys/param.h>
34 #include <sys/types.h>
37 #include <sys/resource.h>
39 #include <sys/socket.h>
50 #include "pathnames.h"
51 #include "patchlevel.h"
54 * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
55 * /etc/ppp/options exists.
57 #ifndef REQ_SYSOPTIONS
58 #define REQ_SYSOPTIONS 1
62 char ifname[IFNAMSIZ]; /* Interface name */
63 int ifunit; /* Interface unit number */
65 char *progname; /* Name of this program */
66 char hostname[MAXNAMELEN]; /* Our hostname */
67 static char pidfilename[MAXPATHLEN];
69 static pid_t pid; /* Our pid */
70 static pid_t pgrpid; /* Process Group ID */
71 static uid_t uid; /* Our real user-id */
73 int fd = -1; /* Device file descriptor */
74 int s; /* Socket file descriptor */
76 int phase; /* where the link is at */
80 static int initfdflags = -1; /* Initial file descriptor flags */
82 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
83 static u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
85 int hungup; /* terminal has been hung up */
86 static int n_children; /* # child processes still running */
91 static void hup __P((int));
92 static void term __P((int));
93 static void chld __P((int));
94 static void toggle_debug __P((int));
95 static void open_ccp __P((int));
97 static void get_input __P((void));
98 void establish_ppp __P((void));
99 void calltimeout __P((void));
100 struct timeval *timeleft __P((struct timeval *));
101 void reap_kids __P((void));
102 void cleanup __P((int, caddr_t));
103 void close_fd __P((void));
105 void novm __P((char *));
107 void log_packet __P((u_char *, int, char *));
108 void format_packet __P((u_char *, int,
109 void (*) (void *, char *, ...), void *));
110 void pr_log __P((void *, char *, ...));
112 extern char *ttyname __P((int));
113 extern char *getlogin __P((void));
116 * PPP Data Link Layer "protocol" table.
117 * One entry per supported protocol.
119 static struct protent {
128 { PPP_LCP, lcp_init, lcp_input, lcp_protrej,
129 lcp_printpkt, NULL, "LCP" },
130 { PPP_IPCP, ipcp_init, ipcp_input, ipcp_protrej,
131 ipcp_printpkt, NULL, "IPCP" },
132 { PPP_PAP, upap_init, upap_input, upap_protrej,
133 upap_printpkt, NULL, "PAP" },
134 { PPP_CHAP, ChapInit, ChapInput, ChapProtocolReject,
135 ChapPrintPkt, NULL, "CHAP" },
136 { PPP_CCP, ccp_init, ccp_input, ccp_protrej,
137 ccp_printpkt, ccp_datainput, "CCP" },
140 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
159 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
160 perror("couldn't get hostname");
163 hostname[MAXNAMELEN-1] = 0;
167 if (!ppp_available()) {
168 fprintf(stderr, "Sorry - PPP is not available on this system\n");
173 * Initialize to the standard option set, then parse, in order,
174 * the system options file, the user's options file, and the command
177 for (i = 0; i < N_PROTO; i++)
178 (*prottbl[i].init)(0);
182 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
183 !options_from_user() ||
184 !parse_args(argc-1, argv+1) ||
187 check_auth_options();
191 * Initialize system-dependent stuff and magic number package.
197 * Detach ourselves from the terminal, if required,
198 * and identify who is running us.
200 if (!default_device && !nodetach && daemon(0, 0) < 0) {
201 perror("Couldn't detach from controlling terminal");
208 if (pw != NULL && pw->pw_name != NULL)
213 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
214 VERSION, PATCHLEVEL, p, uid);
216 /* Get an internet socket for doing socket ioctl's on. */
217 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
218 syslog(LOG_ERR, "Couldn't create IP socket: %m");
223 * Compute mask of all interesting signals and install signal handlers
224 * for each. Only one signal handler may be active at a time. Therefore,
225 * all other signals should be masked when any handler is executing.
228 sigaddset(&mask, SIGHUP);
229 sigaddset(&mask, SIGINT);
230 sigaddset(&mask, SIGTERM);
231 sigaddset(&mask, SIGCHLD);
233 #define SIGNAL(s, handler) { \
234 sa.sa_handler = handler; \
235 if (sigaction(s, &sa, NULL) < 0) { \
236 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
243 SIGNAL(SIGHUP, hup); /* Hangup */
244 SIGNAL(SIGINT, term); /* Interrupt */
245 SIGNAL(SIGTERM, term); /* Terminate */
246 SIGNAL(SIGCHLD, chld);
248 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
249 signal(SIGUSR2, open_ccp); /* Reopen CCP */
252 * Lock the device if we've been asked to.
254 if (lockflag && !default_device)
255 if (lock(devnam) < 0)
261 * Open the serial device and set it up to be the ppp interface.
262 * If we're dialling out, or we don't want to use the modem lines,
263 * we open it in non-blocking mode, but then we need to clear
264 * the non-blocking I/O bit.
266 nonblock = (connector || !modem)? O_NONBLOCK: 0;
267 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
268 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
271 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
272 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
276 initfdflags &= ~O_NONBLOCK;
277 fcntl(fd, F_SETFL, initfdflags);
282 /* run connection script */
283 if (connector && connector[0]) {
284 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
286 /* set line speed, flow control, etc.; set CLOCAL for now */
289 /* drop dtr to hang up in case modem is off hook */
290 if (!default_device && modem) {
296 if (device_script(connector, fd, fd) < 0) {
297 syslog(LOG_ERR, "Connect script failed");
302 syslog(LOG_INFO, "Connected...");
303 sleep(1); /* give it time to set up its terminal */
306 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
309 /* set up the serial device as a ppp interface */
312 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
313 (void) sprintf(ifname, "ppp%d", ifunit);
315 /* write pid to file */
316 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
317 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
318 fprintf(pidfile, "%d\n", pid);
319 (void) fclose(pidfile);
321 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
326 * Set device for non-blocking reads.
328 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
329 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
334 * Block all signals, start opening the connection, and wait for
335 * incoming events (reply, timeout, etc.).
337 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
339 lcp_open(0); /* Start protocol */
340 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
341 wait_input(timeleft(&timo));
348 if (phase == PHASE_NETWORK) {
349 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
355 reap_kids(); /* Don't leave dead kids lying around */
359 * Run disconnector script, if requested
362 if (device_script(disconnector, fd, fd) < 0) {
363 syslog(LOG_WARNING, "disconnect script failed");
367 syslog(LOG_INFO, "Disconnected...");
371 if (unlink(pidfilename) < 0 && errno != ENOENT)
372 syslog(LOG_WARNING, "unable to delete pid file: %m");
377 if (lockflag && !default_device)
385 * get_input - called when incoming data is available.
394 for (;;) { /* Read all available packets */
395 p = inpacket_buf; /* point to beginning of packet buffer */
397 len = read_packet(inpacket_buf);
402 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
404 lcp_lowerdown(0); /* serial link is no longer available */
409 if (debug /*&& (debugflags & DBG_INPACKET)*/)
410 log_packet(p, len, "rcvd ");
412 if (len < PPP_HDRLEN) {
413 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
417 p += 2; /* Skip address and control */
418 GETSHORT(protocol, p);
422 * Toss all non-LCP packets unless LCP is OPEN.
424 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
426 "io(): Received non-LCP packet when LCP not open."));
431 * Upcall the proper protocol input routine.
433 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
434 if (prottbl[i].protocol == protocol) {
435 (*prottbl[i].input)(0, p, len);
437 } else if (protocol == (prottbl[i].protocol & ~0x8000)
438 && prottbl[i].datainput != NULL) {
439 (*prottbl[i].datainput)(0, p, len);
443 if (i == sizeof (prottbl) / sizeof (struct protent)) {
445 syslog(LOG_WARNING, "Unknown protocol (0x%x) received",
447 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
454 * demuxprotrej - Demultiplex a Protocol-Reject.
457 demuxprotrej(unit, protocol)
464 * Upcall the proper Protocol-Reject routine.
466 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
467 if (prottbl[i].protocol == protocol) {
468 (*prottbl[i].protrej)(unit);
473 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
479 * quit - Clean up state and exit.
488 * die - like quit, except we can specify an exit status.
495 syslog(LOG_INFO, "Exit.");
500 * cleanup - restore anything which needs to be restored before we exit
511 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
512 syslog(LOG_WARNING, "unable to delete pid file: %m");
515 if (lockflag && !default_device)
520 * close_fd - restore the terminal device and close it.
525 /* drop dtr to hang up */
529 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
530 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
543 struct timeval c_time; /* time at which to call routine */
544 caddr_t c_arg; /* argument to routine */
545 void (*c_func)(); /* routine */
546 struct callout *c_next;
549 static struct callout *callout = NULL; /* Callout list */
550 static struct timeval timenow; /* Current time */
553 * timeout - Schedule a timeout.
555 * Note that this timeout takes the number of seconds, NOT hz (as in
559 timeout(func, arg, time)
564 struct callout *newp, *p, **pp;
566 MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
567 (int) func, (int) arg, time));
572 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
573 syslog(LOG_ERR, "Out of memory in timeout()!");
578 gettimeofday(&timenow, NULL);
579 newp->c_time.tv_sec = timenow.tv_sec + time;
580 newp->c_time.tv_usec = timenow.tv_usec;
583 * Find correct place and link it in.
585 for (pp = &callout; (p = *pp); pp = &p->c_next)
586 if (p->c_time.tv_sec < newp->c_time.tv_sec
587 || (p->c_time.tv_sec == newp->c_time.tv_sec
588 && p->c_time.tv_usec <= newp->c_time.tv_sec))
596 * untimeout - Unschedule a timeout.
603 struct itimerval itv;
604 struct callout **copp, *freep;
607 MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
610 * Find first matching timeout and remove it from the list.
612 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
613 if (freep->c_func == func && freep->c_arg == arg) {
614 *copp = freep->c_next;
615 (void) free((char *) freep);
622 * calltimeout - Call any timeout routines which are now due.
629 while (callout != NULL) {
632 if (gettimeofday(&timenow, NULL) < 0) {
633 syslog(LOG_ERR, "Failed to get time of day: %m");
636 if (!(p->c_time.tv_sec < timenow.tv_sec
637 || (p->c_time.tv_sec == timenow.tv_sec
638 && p->c_time.tv_usec <= timenow.tv_usec)))
639 break; /* no, it's not time yet */
642 (*p->c_func)(p->c_arg);
650 * timeleft - return the length of time until the next timeout is due.
659 gettimeofday(&timenow, NULL);
660 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
661 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
662 if (tvp->tv_usec < 0) {
663 tvp->tv_usec += 1000000;
667 tvp->tv_sec = tvp->tv_usec = 0;
674 * hup - Catch SIGHUP signal.
676 * Indicates that the physical layer has been disconnected.
677 * We don't rely on this indication; if the user has sent this
678 * signal, we just take the link down.
684 syslog(LOG_INFO, "Hangup (SIGHUP)");
690 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
692 * Indicates that we should initiate a graceful disconnect and exit.
699 syslog(LOG_INFO, "Terminating on signal %d.", sig);
700 persist = 0; /* don't try to restart */
706 * chld - Catch SIGCHLD signal.
707 * Calls reap_kids to get status for any dead kids.
718 * toggle_debug - Catch SIGUSR1 signal.
733 * open_ccp - Catch SIGUSR2 signal.
735 * Try to (re)negotiate compression.
747 * device_script - run a program to connect or disconnect the
751 device_script(program, in, out)
760 sigaddset(&mask, SIGINT);
761 sigaddset(&mask, SIGHUP);
762 sigprocmask(SIG_BLOCK, &mask, &mask);
767 syslog(LOG_ERR, "Failed to create child process: %m");
772 setreuid(getuid(), getuid());
773 setregid(getgid(), getgid());
774 sigprocmask(SIG_SETMASK, &mask, NULL);
777 execl("/bin/sh", "sh", "-c", program, (char *)0);
778 syslog(LOG_ERR, "could not exec /bin/sh: %m");
783 while (waitpid(pid, &status, 0) < 0) {
786 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
789 sigprocmask(SIG_SETMASK, &mask, NULL);
791 return (status == 0 ? 0 : -1);
796 * run-program - execute a program with given arguments,
797 * but don't wait for it.
798 * If the program can't be executed, logs an error unless
799 * must_exist is 0 and the program file doesn't exist.
802 run_program(prog, args, must_exist)
811 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
817 /* Leave the current location */
818 (void) setsid(); /* No controlling tty. */
819 (void) umask (0); /* no umask. Must change in script. */
820 (void) chdir ("/"); /* no current directory. */
822 /* Ensure that nothing of our device environment is inherited. */
826 close (s); /* Socket interface to the ppp device */
827 close (fd); /* tty interface to the ppp device */
829 /* Don't pass handles to the PPP device, even by accident. */
830 new_fd = open (_PATH_DEVNULL, O_RDWR);
833 dup2 (new_fd, 0); /* stdin <- /dev/null */
836 dup2 (0, 1); /* stdout -> /dev/null */
837 dup2 (0, 2); /* stderr -> /dev/null */
840 /* Force the priority back to zero if pppd is running higher. */
841 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
842 syslog (LOG_WARNING, "can't reset priority to 0: %m");
844 /* SysV recommends a second fork at this point. */
846 /* run the program */
848 if (must_exist || errno != ENOENT)
849 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
852 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
859 * reap_kids - get status from any dead child processes,
860 * and log a message for abnormal terminations.
869 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
871 syslog(LOG_ERR, "Error waiting for child process: %m");
876 if (WIFSIGNALED(status)) {
877 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
878 pid, WTERMSIG(status));
885 * log_packet - format a packet and log it.
888 char line[256]; /* line to be logged accumulated here */
892 log_packet(p, len, prefix)
897 strcpy(line, prefix);
898 linep = line + strlen(line);
899 format_packet(p, len, pr_log, NULL);
901 syslog(LOG_DEBUG, "%s", line);
905 * format_packet - make a readable representation of a packet,
906 * calling `printer(arg, format, ...)' to output it.
909 format_packet(p, len, printer, arg)
912 void (*printer) __P((void *, char *, ...));
919 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
923 for (i = 0; i < N_PROTO; ++i)
924 if (proto == prottbl[i].protocol)
927 printer(arg, "[%s", prottbl[i].name);
928 n = (*prottbl[i].printpkt)(p, len, printer, arg);
933 printer(arg, "[proto=0x%x]", proto);
937 for (; len > 0; --len) {
939 printer(arg, " %.2x", x);
947 pr_log(void *arg, char *fmt, ...)
954 vsprintf(buf, fmt, pvar);
958 if (linep + n + 1 > line + sizeof(line)) {
959 syslog(LOG_DEBUG, "%s", line);
970 pr_log(arg, fmt, va_alist)
980 vsprintf(buf, fmt, pvar);
984 if (linep + n + 1 > line + sizeof(line)) {
985 syslog(LOG_DEBUG, "%s", line);
994 * print_string - print a readable representation of a string using
998 print_string(p, len, printer, arg)
1001 void (*printer) __P((void *, char *, ...));
1007 for (; len > 0; --len) {
1009 if (' ' <= c && c <= '~')
1010 printer(arg, "%c", c);
1012 printer(arg, "\\%.3o", c);
1018 * novm - log an error message saying we ran out of memory, and die.
1024 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);