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.22 1995/05/01 01:44:30 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 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));
117 #define O_NONBLOCK O_NDELAY
121 * PPP Data Link Layer "protocol" table.
122 * One entry per supported protocol.
124 static struct protent {
133 { PPP_LCP, lcp_init, lcp_input, lcp_protrej,
134 lcp_printpkt, NULL, "LCP" },
135 { PPP_IPCP, ipcp_init, ipcp_input, ipcp_protrej,
136 ipcp_printpkt, NULL, "IPCP" },
137 { PPP_PAP, upap_init, upap_input, upap_protrej,
138 upap_printpkt, NULL, "PAP" },
139 { PPP_CHAP, ChapInit, ChapInput, ChapProtocolReject,
140 ChapPrintPkt, NULL, "CHAP" },
141 { PPP_CCP, ccp_init, ccp_input, ccp_protrej,
142 ccp_printpkt, ccp_datainput, "CCP" },
145 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
163 strcpy(default_devnam, devnam);
165 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
166 perror("couldn't get hostname");
169 hostname[MAXNAMELEN-1] = 0;
173 if (!ppp_available()) {
174 fprintf(stderr, "Sorry - PPP is not available on this system\n");
179 * Initialize to the standard option set, then parse, in order,
180 * the system options file, the user's options file, and the command
183 for (i = 0; i < N_PROTO; i++)
184 (*prottbl[i].init)(0);
188 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
189 !options_from_user() ||
190 !parse_args(argc-1, argv+1) ||
193 check_auth_options();
197 * If the user has specified the default device name explicitly,
198 * pretend they hadn't.
200 if (!default_device && strcmp(devnam, default_devnam) == 0)
204 * Initialize system-dependent stuff and magic number package.
210 * Detach ourselves from the terminal, if required,
211 * and identify who is running us.
213 if (!default_device && !nodetach && daemon(0, 0) < 0) {
214 perror("Couldn't detach from controlling terminal");
221 if (pw != NULL && pw->pw_name != NULL)
226 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
227 VERSION, PATCHLEVEL, p, uid);
230 * Compute mask of all interesting signals and install signal handlers
231 * for each. Only one signal handler may be active at a time. Therefore,
232 * all other signals should be masked when any handler is executing.
235 sigaddset(&mask, SIGHUP);
236 sigaddset(&mask, SIGINT);
237 sigaddset(&mask, SIGTERM);
238 sigaddset(&mask, SIGCHLD);
240 #define SIGNAL(s, handler) { \
241 sa.sa_handler = handler; \
242 if (sigaction(s, &sa, NULL) < 0) { \
243 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
250 SIGNAL(SIGHUP, hup); /* Hangup */
251 SIGNAL(SIGINT, term); /* Interrupt */
252 SIGNAL(SIGTERM, term); /* Terminate */
253 SIGNAL(SIGCHLD, chld);
255 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
256 signal(SIGUSR2, open_ccp); /* Reopen CCP */
259 * Lock the device if we've been asked to.
261 if (lockflag && !default_device)
262 if (lock(devnam) < 0)
268 * Open the serial device and set it up to be the ppp interface.
269 * If we're dialling out, or we don't want to use the modem lines,
270 * we open it in non-blocking mode, but then we need to clear
271 * the non-blocking I/O bit.
273 nonblock = (connector || !modem)? O_NONBLOCK: 0;
274 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
275 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
278 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
279 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
283 initfdflags &= ~O_NONBLOCK;
284 fcntl(fd, F_SETFL, initfdflags);
289 /* run connection script */
290 if (connector && connector[0]) {
291 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
293 /* set line speed, flow control, etc.; set CLOCAL for now */
296 /* drop dtr to hang up in case modem is off hook */
297 if (!default_device && modem) {
303 if (device_script(connector, fd, fd) < 0) {
304 syslog(LOG_ERR, "Connect script failed");
309 syslog(LOG_INFO, "Connected...");
310 sleep(1); /* give it time to set up its terminal */
313 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
316 /* set up the serial device as a ppp interface */
319 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
320 (void) sprintf(ifname, "ppp%d", ifunit);
322 /* write pid to file */
323 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
324 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
325 fprintf(pidfile, "%d\n", pid);
326 (void) fclose(pidfile);
328 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
333 * Set device for non-blocking reads.
335 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
336 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
341 * Block all signals, start opening the connection, and wait for
342 * incoming events (reply, timeout, etc.).
344 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
346 lcp_open(0); /* Start protocol */
347 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
348 wait_input(timeleft(&timo));
355 if (phase == PHASE_NETWORK) {
356 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
362 reap_kids(); /* Don't leave dead kids lying around */
366 * Run disconnector script, if requested.
367 * First we need to reset non-blocking mode.
369 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
374 if (device_script(disconnector, fd, fd) < 0) {
375 syslog(LOG_WARNING, "disconnect script failed");
379 syslog(LOG_INFO, "Disconnected...");
383 if (unlink(pidfilename) < 0 && errno != ENOENT)
384 syslog(LOG_WARNING, "unable to delete pid file: %m");
389 if (lockflag && !default_device)
397 * get_input - called when incoming data is available.
406 p = inpacket_buf; /* point to beginning of packet buffer */
408 len = read_packet(inpacket_buf);
413 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
415 lcp_lowerdown(0); /* serial link is no longer available */
420 if (debug /*&& (debugflags & DBG_INPACKET)*/)
421 log_packet(p, len, "rcvd ");
423 if (len < PPP_HDRLEN) {
424 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
428 p += 2; /* Skip address and control */
429 GETSHORT(protocol, p);
433 * Toss all non-LCP packets unless LCP is OPEN.
435 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
437 "io(): Received non-LCP packet when LCP not open."));
442 * Upcall the proper protocol input routine.
444 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
445 if (prottbl[i].protocol == protocol) {
446 (*prottbl[i].input)(0, p, len);
448 } else if (protocol == (prottbl[i].protocol & ~0x8000)
449 && prottbl[i].datainput != NULL) {
450 (*prottbl[i].datainput)(0, p, len);
454 if (i == sizeof (prottbl) / sizeof (struct protent)) {
456 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
457 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
463 * demuxprotrej - Demultiplex a Protocol-Reject.
466 demuxprotrej(unit, protocol)
473 * Upcall the proper Protocol-Reject routine.
475 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
476 if (prottbl[i].protocol == protocol) {
477 (*prottbl[i].protrej)(unit);
482 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
488 * quit - Clean up state and exit.
497 * die - like quit, except we can specify an exit status.
504 syslog(LOG_INFO, "Exit.");
509 * cleanup - restore anything which needs to be restored before we exit
520 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
521 syslog(LOG_WARNING, "unable to delete pid file: %m");
524 if (lockflag && !default_device)
529 * close_fd - restore the terminal device and close it.
534 /* drop dtr to hang up */
538 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
539 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
552 struct timeval c_time; /* time at which to call routine */
553 caddr_t c_arg; /* argument to routine */
554 void (*c_func)(); /* routine */
555 struct callout *c_next;
558 static struct callout *callout = NULL; /* Callout list */
559 static struct timeval timenow; /* Current time */
562 * timeout - Schedule a timeout.
564 * Note that this timeout takes the number of seconds, NOT hz (as in
568 timeout(func, arg, time)
573 struct callout *newp, *p, **pp;
575 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
576 (long) func, (long) arg, time));
581 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
582 syslog(LOG_ERR, "Out of memory in timeout()!");
587 gettimeofday(&timenow, NULL);
588 newp->c_time.tv_sec = timenow.tv_sec + time;
589 newp->c_time.tv_usec = timenow.tv_usec;
592 * Find correct place and link it in.
594 for (pp = &callout; (p = *pp); pp = &p->c_next)
595 if (newp->c_time.tv_sec < p->c_time.tv_sec
596 || (newp->c_time.tv_sec == p->c_time.tv_sec
597 && newp->c_time.tv_usec < p->c_time.tv_sec))
605 * untimeout - Unschedule a timeout.
612 struct itimerval itv;
613 struct callout **copp, *freep;
616 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
619 * Find first matching timeout and remove it from the list.
621 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
622 if (freep->c_func == func && freep->c_arg == arg) {
623 *copp = freep->c_next;
624 (void) free((char *) freep);
631 * calltimeout - Call any timeout routines which are now due.
638 while (callout != NULL) {
641 if (gettimeofday(&timenow, NULL) < 0) {
642 syslog(LOG_ERR, "Failed to get time of day: %m");
645 if (!(p->c_time.tv_sec < timenow.tv_sec
646 || (p->c_time.tv_sec == timenow.tv_sec
647 && p->c_time.tv_usec <= timenow.tv_usec)))
648 break; /* no, it's not time yet */
651 (*p->c_func)(p->c_arg);
659 * timeleft - return the length of time until the next timeout is due.
668 gettimeofday(&timenow, NULL);
669 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
670 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
671 if (tvp->tv_usec < 0) {
672 tvp->tv_usec += 1000000;
676 tvp->tv_sec = tvp->tv_usec = 0;
683 * hup - Catch SIGHUP signal.
685 * Indicates that the physical layer has been disconnected.
686 * We don't rely on this indication; if the user has sent this
687 * signal, we just take the link down.
693 syslog(LOG_INFO, "Hangup (SIGHUP)");
699 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
701 * Indicates that we should initiate a graceful disconnect and exit.
708 syslog(LOG_INFO, "Terminating on signal %d.", sig);
709 persist = 0; /* don't try to restart */
715 * chld - Catch SIGCHLD signal.
716 * Calls reap_kids to get status for any dead kids.
727 * toggle_debug - Catch SIGUSR1 signal.
742 * open_ccp - Catch SIGUSR2 signal.
744 * Try to (re)negotiate compression.
756 * device_script - run a program to connect or disconnect the
760 device_script(program, in, out)
770 syslog(LOG_ERR, "Failed to create child process: %m");
779 execl("/bin/sh", "sh", "-c", program, (char *)0);
780 syslog(LOG_ERR, "could not exec /bin/sh: %m");
785 while (waitpid(pid, &status, 0) < 0) {
788 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
792 return (status == 0 ? 0 : -1);
797 * run-program - execute a program with given arguments,
798 * but don't wait for it.
799 * If the program can't be executed, logs an error unless
800 * must_exist is 0 and the program file doesn't exist.
803 run_program(prog, args, must_exist)
813 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
819 /* Leave the current location */
820 (void) setsid(); /* No controlling tty. */
821 (void) umask (S_IRWXG|S_IRWXO);
822 (void) chdir ("/"); /* no current directory. */
826 /* Ensure that nothing of our device environment is inherited. */
830 close (fd); /* tty interface to the ppp device */
831 /* XXX should call sysdep cleanup procedure here */
833 /* Don't pass handles to the PPP device, even by accident. */
834 new_fd = open (_PATH_DEVNULL, O_RDWR);
837 dup2 (new_fd, 0); /* stdin <- /dev/null */
840 dup2 (0, 1); /* stdout -> /dev/null */
841 dup2 (0, 2); /* stderr -> /dev/null */
845 /* Force the priority back to zero if pppd is running higher. */
846 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
847 syslog (LOG_WARNING, "can't reset priority to 0: %m");
850 /* SysV recommends a second fork at this point. */
852 /* run the program; give it a null environment */
854 execve(prog, args, nullenv);
855 if (must_exist || errno != ENOENT)
856 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
859 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
866 * reap_kids - get status from any dead child processes,
867 * and log a message for abnormal terminations.
876 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
878 syslog(LOG_ERR, "Error waiting for child process: %m");
883 if (WIFSIGNALED(status)) {
884 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
885 pid, WTERMSIG(status));
892 * log_packet - format a packet and log it.
895 char line[256]; /* line to be logged accumulated here */
899 log_packet(p, len, prefix)
904 strcpy(line, prefix);
905 linep = line + strlen(line);
906 format_packet(p, len, pr_log, NULL);
908 syslog(LOG_DEBUG, "%s", line);
912 * format_packet - make a readable representation of a packet,
913 * calling `printer(arg, format, ...)' to output it.
916 format_packet(p, len, printer, arg)
919 void (*printer) __P((void *, char *, ...));
926 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
930 for (i = 0; i < N_PROTO; ++i)
931 if (proto == prottbl[i].protocol)
934 printer(arg, "[%s", prottbl[i].name);
935 n = (*prottbl[i].printpkt)(p, len, printer, arg);
940 printer(arg, "[proto=0x%x]", proto);
944 for (; len > 0; --len) {
946 printer(arg, " %.2x", x);
954 pr_log(void *arg, char *fmt, ...)
961 vsprintf(buf, fmt, pvar);
965 if (linep + n + 1 > line + sizeof(line)) {
966 syslog(LOG_DEBUG, "%s", line);
977 pr_log(arg, fmt, va_alist)
987 vsprintf(buf, fmt, pvar);
991 if (linep + n + 1 > line + sizeof(line)) {
992 syslog(LOG_DEBUG, "%s", line);
1001 * print_string - print a readable representation of a string using
1005 print_string(p, len, printer, arg)
1008 void (*printer) __P((void *, char *, ...));
1014 for (; len > 0; --len) {
1016 if (' ' <= c && c <= '~')
1017 printer(arg, "%c", c);
1019 printer(arg, "\\%.3o", c);
1025 * novm - log an error message saying we ran out of memory, and die.
1031 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);