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.28 1995/10/27 03:41:01 paulus Exp $";
34 #include <sys/param.h>
35 #include <sys/types.h>
38 #include <sys/resource.h>
40 #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]; /* name of pid file */
69 static char default_devnam[MAXPATHLEN]; /* name of default device */
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 */
76 int phase; /* where the link is at */
80 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
81 static u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
83 int hungup; /* terminal has been hung up */
84 static int n_children; /* # child processes still running */
86 int baud_rate; /* Actual bits/second for serial device */
88 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
90 /* Prototypes for procedures local to this file. */
92 static void cleanup __P((void));
93 static void close_fd __P((void));
94 static void get_input __P((void));
95 static void calltimeout __P((void));
96 static struct timeval *timeleft __P((struct timeval *));
97 static void hup __P((int));
98 static void term __P((int));
99 static void chld __P((int));
100 static void toggle_debug __P((int));
101 static void open_ccp __P((int));
102 static void bad_signal __P((int));
103 static int device_script __P((char *, int, int));
104 static void reap_kids __P((void));
105 static void pr_log __P((void *, char *, ...));
107 extern char *ttyname __P((int));
108 extern char *getlogin __P((void));
112 #define O_NONBLOCK O_NDELAY
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]))
146 int i, nonblock, fdflags;
158 strcpy(default_devnam, devnam);
160 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
161 perror("couldn't get hostname");
164 hostname[MAXNAMELEN-1] = 0;
168 if (!ppp_available()) {
169 fprintf(stderr, no_ppp_msg);
174 * Initialize to the standard option set, then parse, in order,
175 * the system options file, the user's options file, and the command
178 for (i = 0; i < N_PROTO; i++)
179 (*prottbl[i].init)(0);
183 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
184 !options_from_user() ||
185 !parse_args(argc-1, argv+1) ||
188 check_auth_options();
192 * If the user has specified the default device name explicitly,
193 * pretend they hadn't.
195 if (!default_device && strcmp(devnam, default_devnam) == 0)
199 * Initialize system-dependent stuff and magic number package.
205 * Detach ourselves from the terminal, if required,
206 * and identify who is running us.
208 if (!default_device && !nodetach && daemon(0, 0) < 0) {
209 perror("Couldn't detach from controlling terminal");
216 if (pw != NULL && pw->pw_name != NULL)
221 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
222 VERSION, PATCHLEVEL, p, uid);
225 * Compute mask of all interesting signals and install signal handlers
226 * for each. Only one signal handler may be active at a time. Therefore,
227 * all other signals should be masked when any handler is executing.
230 sigaddset(&mask, SIGHUP);
231 sigaddset(&mask, SIGINT);
232 sigaddset(&mask, SIGTERM);
233 sigaddset(&mask, SIGCHLD);
235 #define SIGNAL(s, handler) { \
236 sa.sa_handler = handler; \
237 if (sigaction(s, &sa, NULL) < 0) { \
238 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
245 SIGNAL(SIGHUP, hup); /* Hangup */
246 SIGNAL(SIGINT, term); /* Interrupt */
247 SIGNAL(SIGTERM, term); /* Terminate */
248 SIGNAL(SIGCHLD, chld);
250 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
251 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
254 * Install a handler for other signals which would otherwise
255 * cause pppd to exit without cleaning up.
257 SIGNAL(SIGABRT, bad_signal);
258 SIGNAL(SIGALRM, bad_signal);
259 SIGNAL(SIGFPE, bad_signal);
260 SIGNAL(SIGILL, bad_signal);
261 SIGNAL(SIGPIPE, bad_signal);
262 SIGNAL(SIGQUIT, bad_signal);
263 SIGNAL(SIGSEGV, bad_signal);
265 SIGNAL(SIGBUS, bad_signal);
268 SIGNAL(SIGEMT, bad_signal);
271 SIGNAL(SIGPOLL, bad_signal);
274 SIGNAL(SIGPROF, bad_signal);
277 SIGNAL(SIGSYS, bad_signal);
280 SIGNAL(SIGTRAP, bad_signal);
283 SIGNAL(SIGVTALRM, bad_signal);
286 SIGNAL(SIGXCPU, bad_signal);
289 SIGNAL(SIGXFSZ, bad_signal);
293 * Lock the device if we've been asked to.
295 if (lockflag && !default_device)
296 if (lock(devnam) < 0)
302 * Open the serial device and set it up to be the ppp interface.
303 * If we're dialling out, or we don't want to use the modem lines,
304 * we open it in non-blocking mode, but then we need to clear
305 * the non-blocking I/O bit.
307 nonblock = (connector || !modem)? O_NONBLOCK: 0;
308 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
309 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
313 if ((fdflags = fcntl(fd, F_GETFL)) == -1
314 || fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
316 "Couldn't reset non-blocking mode on device: %m");
321 /* run connection script */
322 if (connector && connector[0]) {
323 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
325 /* set line speed, flow control, etc.; set CLOCAL for now */
328 /* drop dtr to hang up in case modem is off hook */
329 if (!default_device && modem) {
335 if (device_script(connector, fd, fd) < 0) {
336 syslog(LOG_ERR, "Connect script failed");
341 syslog(LOG_INFO, "Serial connection established.");
342 sleep(1); /* give it time to set up its terminal */
345 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
348 /* set up the serial device as a ppp interface */
351 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
352 (void) sprintf(ifname, "ppp%d", ifunit);
354 /* write pid to file */
355 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
356 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
357 fprintf(pidfile, "%d\n", pid);
358 (void) fclose(pidfile);
360 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
365 * Block all signals, start opening the connection, and wait for
366 * incoming events (reply, timeout, etc.).
368 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
370 lcp_open(0); /* Start protocol */
371 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
372 wait_input(timeleft(&timo));
380 if (phase == PHASE_NETWORK) {
381 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
386 reap_kids(); /* Don't leave dead kids lying around */
390 * Run disconnector script, if requested.
391 * XXX we may not be able to do this if the line has hung up!
396 if (device_script(disconnector, fd, fd) < 0) {
397 syslog(LOG_WARNING, "disconnect script failed");
399 syslog(LOG_INFO, "Serial link disconnected.");
404 if (unlink(pidfilename) < 0 && errno != ENOENT)
405 syslog(LOG_WARNING, "unable to delete pid file: %m");
415 * get_input - called when incoming data is available.
424 p = inpacket_buf; /* point to beginning of packet buffer */
426 len = read_packet(inpacket_buf);
431 syslog(LOG_NOTICE, "Modem hangup");
433 lcp_lowerdown(0); /* serial link is no longer available */
438 if (debug /*&& (debugflags & DBG_INPACKET)*/)
439 log_packet(p, len, "rcvd ");
441 if (len < PPP_HDRLEN) {
442 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
446 p += 2; /* Skip address and control */
447 GETSHORT(protocol, p);
451 * Toss all non-LCP packets unless LCP is OPEN.
453 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
455 "io(): Received non-LCP packet when LCP not open."));
460 * Upcall the proper protocol input routine.
462 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++) {
463 if (prottbl[i].protocol == protocol) {
464 (*prottbl[i].input)(0, p, len);
467 if (protocol == (prottbl[i].protocol & ~0x8000)
468 && prottbl[i].datainput != NULL) {
469 (*prottbl[i].datainput)(0, p, len);
475 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
476 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
481 * demuxprotrej - Demultiplex a Protocol-Reject.
484 demuxprotrej(unit, protocol)
491 * Upcall the proper Protocol-Reject routine.
493 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
494 if (prottbl[i].protocol == protocol) {
495 (*prottbl[i].protrej)(unit);
499 syslog(LOG_WARNING, "Unrecognized Protocol-Reject for protocol 0x%x",
505 * quit - Clean up state and exit (with an error indication).
514 * die - like quit, except we can specify an exit status.
521 syslog(LOG_INFO, "Exit.");
526 * cleanup - restore anything which needs to be restored before we exit
537 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
538 syslog(LOG_WARNING, "unable to delete pid file: %m");
541 if (lockflag && !default_device)
546 * close_fd - restore the terminal device and close it.
553 /* drop dtr to hang up */
565 struct timeval c_time; /* time at which to call routine */
566 caddr_t c_arg; /* argument to routine */
567 void (*c_func)(); /* routine */
568 struct callout *c_next;
571 static struct callout *callout = NULL; /* Callout list */
572 static struct timeval timenow; /* Current time */
575 * timeout - Schedule a timeout.
577 * Note that this timeout takes the number of seconds, NOT hz (as in
581 timeout(func, arg, time)
586 struct callout *newp, *p, **pp;
588 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
589 (long) func, (long) arg, time));
594 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
595 syslog(LOG_ERR, "Out of memory in timeout()!");
600 gettimeofday(&timenow, NULL);
601 newp->c_time.tv_sec = timenow.tv_sec + time;
602 newp->c_time.tv_usec = timenow.tv_usec;
605 * Find correct place and link it in.
607 for (pp = &callout; (p = *pp); pp = &p->c_next)
608 if (newp->c_time.tv_sec < p->c_time.tv_sec
609 || (newp->c_time.tv_sec == p->c_time.tv_sec
610 && newp->c_time.tv_usec < p->c_time.tv_sec))
618 * untimeout - Unschedule a timeout.
625 struct itimerval itv;
626 struct callout **copp, *freep;
629 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
632 * Find first matching timeout and remove it from the list.
634 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
635 if (freep->c_func == func && freep->c_arg == arg) {
636 *copp = freep->c_next;
637 (void) free((char *) freep);
644 * calltimeout - Call any timeout routines which are now due.
651 while (callout != NULL) {
654 if (gettimeofday(&timenow, NULL) < 0) {
655 syslog(LOG_ERR, "Failed to get time of day: %m");
658 if (!(p->c_time.tv_sec < timenow.tv_sec
659 || (p->c_time.tv_sec == timenow.tv_sec
660 && p->c_time.tv_usec <= timenow.tv_usec)))
661 break; /* no, it's not time yet */
664 (*p->c_func)(p->c_arg);
672 * timeleft - return the length of time until the next timeout is due.
674 static struct timeval *
681 gettimeofday(&timenow, NULL);
682 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
683 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
684 if (tvp->tv_usec < 0) {
685 tvp->tv_usec += 1000000;
689 tvp->tv_sec = tvp->tv_usec = 0;
696 * hup - Catch SIGHUP signal.
698 * Indicates that the physical layer has been disconnected.
699 * We don't rely on this indication; if the user has sent this
700 * signal, we just take the link down.
706 syslog(LOG_INFO, "Hangup (SIGHUP)");
712 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
714 * Indicates that we should initiate a graceful disconnect and exit.
721 syslog(LOG_INFO, "Terminating on signal %d.", sig);
722 persist = 0; /* don't try to restart */
728 * chld - Catch SIGCHLD signal.
729 * Calls reap_kids to get status for any dead kids.
740 * toggle_debug - Catch SIGUSR1 signal.
755 * open_ccp - Catch SIGUSR2 signal.
757 * Try to (re)negotiate compression.
769 * bad_signal - We've caught a fatal signal. Clean up state and exit.
775 syslog(LOG_ERR, "Fatal signal %d", sig);
781 * device_script - run a program to connect or disconnect the
785 device_script(program, in, out)
796 syslog(LOG_ERR, "Failed to create child process: %m");
803 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
808 execl("/bin/sh", "sh", "-c", program, (char *)0);
809 syslog(LOG_ERR, "could not exec /bin/sh: %m");
814 while (waitpid(pid, &status, 0) < 0) {
817 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
821 return (status == 0 ? 0 : -1);
826 * run-program - execute a program with given arguments,
827 * but don't wait for it.
828 * If the program can't be executed, logs an error unless
829 * must_exist is 0 and the program file doesn't exist.
832 run_program(prog, args, must_exist)
842 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
848 /* Leave the current location */
849 (void) setsid(); /* No controlling tty. */
850 (void) umask (S_IRWXG|S_IRWXO);
851 (void) chdir ("/"); /* no current directory. */
855 /* Ensure that nothing of our device environment is inherited. */
859 close (fd); /* tty interface to the ppp device */
860 /* XXX should call sysdep cleanup procedure here */
862 /* Don't pass handles to the PPP device, even by accident. */
863 new_fd = open (_PATH_DEVNULL, O_RDWR);
866 dup2 (new_fd, 0); /* stdin <- /dev/null */
869 dup2 (0, 1); /* stdout -> /dev/null */
870 dup2 (0, 2); /* stderr -> /dev/null */
874 /* Force the priority back to zero if pppd is running higher. */
875 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
876 syslog (LOG_WARNING, "can't reset priority to 0: %m");
879 /* SysV recommends a second fork at this point. */
881 /* run the program; give it a null environment */
883 execve(prog, args, nullenv);
884 if (must_exist || errno != ENOENT)
885 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
888 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
895 * reap_kids - get status from any dead child processes,
896 * and log a message for abnormal terminations.
905 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
907 syslog(LOG_ERR, "Error waiting for child process: %m");
912 if (WIFSIGNALED(status)) {
913 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
914 pid, WTERMSIG(status));
921 * log_packet - format a packet and log it.
924 char line[256]; /* line to be logged accumulated here */
928 log_packet(p, len, prefix)
933 strcpy(line, prefix);
934 linep = line + strlen(line);
935 format_packet(p, len, pr_log, NULL);
937 syslog(LOG_DEBUG, "%s", line);
941 * format_packet - make a readable representation of a packet,
942 * calling `printer(arg, format, ...)' to output it.
945 format_packet(p, len, printer, arg)
948 void (*printer) __P((void *, char *, ...));
955 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
959 for (i = 0; i < N_PROTO; ++i)
960 if (proto == prottbl[i].protocol)
963 printer(arg, "[%s", prottbl[i].name);
964 n = (*prottbl[i].printpkt)(p, len, printer, arg);
969 printer(arg, "[proto=0x%x]", proto);
973 for (; len > 0; --len) {
975 printer(arg, " %.2x", x);
983 pr_log(void *arg, char *fmt, ...)
990 vsprintf(buf, fmt, pvar);
994 if (linep + n + 1 > line + sizeof(line)) {
995 syslog(LOG_DEBUG, "%s", line);
1002 #else /* __STDC__ */
1003 #include <varargs.h>
1006 pr_log(arg, fmt, va_alist)
1016 vsprintf(buf, fmt, pvar);
1020 if (linep + n + 1 > line + sizeof(line)) {
1021 syslog(LOG_DEBUG, "%s", line);
1030 * print_string - print a readable representation of a string using
1034 print_string(p, len, printer, arg)
1037 void (*printer) __P((void *, char *, ...));
1043 for (; len > 0; --len) {
1045 if (' ' <= c && c <= '~')
1046 printer(arg, "%c", c);
1048 printer(arg, "\\%.3o", c);
1054 * novm - log an error message saying we ran out of memory, and die.
1060 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);