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.25 1995/07/11 06:40:58 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, "Serial connection established.");
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));
356 if (phase == PHASE_NETWORK) {
357 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.
368 * XXX we may not be able to do this if the line has hung up!
370 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
375 if (device_script(disconnector, fd, fd) < 0) {
376 syslog(LOG_WARNING, "disconnect script failed");
378 syslog(LOG_INFO, "Serial link disconnected.");
383 if (unlink(pidfilename) < 0 && errno != ENOENT)
384 syslog(LOG_WARNING, "unable to delete pid file: %m");
394 * get_input - called when incoming data is available.
403 p = inpacket_buf; /* point to beginning of packet buffer */
405 len = read_packet(inpacket_buf);
410 syslog(LOG_NOTICE, "Modem hangup");
412 lcp_lowerdown(0); /* serial link is no longer available */
417 if (debug /*&& (debugflags & DBG_INPACKET)*/)
418 log_packet(p, len, "rcvd ");
420 if (len < PPP_HDRLEN) {
421 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
425 p += 2; /* Skip address and control */
426 GETSHORT(protocol, p);
430 * Toss all non-LCP packets unless LCP is OPEN.
432 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
434 "io(): Received non-LCP packet when LCP not open."));
439 * Upcall the proper protocol input routine.
441 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++) {
442 if (prottbl[i].protocol == protocol) {
443 (*prottbl[i].input)(0, p, len);
446 if (protocol == (prottbl[i].protocol & ~0x8000)
447 && prottbl[i].datainput != NULL) {
448 (*prottbl[i].datainput)(0, p, len);
454 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
455 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
460 * demuxprotrej - Demultiplex a Protocol-Reject.
463 demuxprotrej(unit, protocol)
470 * Upcall the proper Protocol-Reject routine.
472 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
473 if (prottbl[i].protocol == protocol) {
474 (*prottbl[i].protrej)(unit);
479 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
485 * quit - Clean up state and exit.
494 * die - like quit, except we can specify an exit status.
501 syslog(LOG_INFO, "Exit.");
506 * cleanup - restore anything which needs to be restored before we exit
517 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
518 syslog(LOG_WARNING, "unable to delete pid file: %m");
521 if (lockflag && !default_device)
526 * close_fd - restore the terminal device and close it.
533 /* drop dtr to hang up */
537 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
538 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
549 struct timeval c_time; /* time at which to call routine */
550 caddr_t c_arg; /* argument to routine */
551 void (*c_func)(); /* routine */
552 struct callout *c_next;
555 static struct callout *callout = NULL; /* Callout list */
556 static struct timeval timenow; /* Current time */
559 * timeout - Schedule a timeout.
561 * Note that this timeout takes the number of seconds, NOT hz (as in
565 timeout(func, arg, time)
570 struct callout *newp, *p, **pp;
572 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
573 (long) func, (long) arg, time));
578 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
579 syslog(LOG_ERR, "Out of memory in timeout()!");
584 gettimeofday(&timenow, NULL);
585 newp->c_time.tv_sec = timenow.tv_sec + time;
586 newp->c_time.tv_usec = timenow.tv_usec;
589 * Find correct place and link it in.
591 for (pp = &callout; (p = *pp); pp = &p->c_next)
592 if (newp->c_time.tv_sec < p->c_time.tv_sec
593 || (newp->c_time.tv_sec == p->c_time.tv_sec
594 && newp->c_time.tv_usec < p->c_time.tv_sec))
602 * untimeout - Unschedule a timeout.
609 struct itimerval itv;
610 struct callout **copp, *freep;
613 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
616 * Find first matching timeout and remove it from the list.
618 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
619 if (freep->c_func == func && freep->c_arg == arg) {
620 *copp = freep->c_next;
621 (void) free((char *) freep);
628 * calltimeout - Call any timeout routines which are now due.
635 while (callout != NULL) {
638 if (gettimeofday(&timenow, NULL) < 0) {
639 syslog(LOG_ERR, "Failed to get time of day: %m");
642 if (!(p->c_time.tv_sec < timenow.tv_sec
643 || (p->c_time.tv_sec == timenow.tv_sec
644 && p->c_time.tv_usec <= timenow.tv_usec)))
645 break; /* no, it's not time yet */
648 (*p->c_func)(p->c_arg);
656 * timeleft - return the length of time until the next timeout is due.
665 gettimeofday(&timenow, NULL);
666 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
667 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
668 if (tvp->tv_usec < 0) {
669 tvp->tv_usec += 1000000;
673 tvp->tv_sec = tvp->tv_usec = 0;
680 * hup - Catch SIGHUP signal.
682 * Indicates that the physical layer has been disconnected.
683 * We don't rely on this indication; if the user has sent this
684 * signal, we just take the link down.
690 syslog(LOG_INFO, "Hangup (SIGHUP)");
696 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
698 * Indicates that we should initiate a graceful disconnect and exit.
705 syslog(LOG_INFO, "Terminating on signal %d.", sig);
706 persist = 0; /* don't try to restart */
712 * chld - Catch SIGCHLD signal.
713 * Calls reap_kids to get status for any dead kids.
724 * toggle_debug - Catch SIGUSR1 signal.
739 * open_ccp - Catch SIGUSR2 signal.
741 * Try to (re)negotiate compression.
753 * device_script - run a program to connect or disconnect the
757 device_script(program, in, out)
768 syslog(LOG_ERR, "Failed to create child process: %m");
775 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
780 execl("/bin/sh", "sh", "-c", program, (char *)0);
781 syslog(LOG_ERR, "could not exec /bin/sh: %m");
786 while (waitpid(pid, &status, 0) < 0) {
789 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
793 return (status == 0 ? 0 : -1);
798 * run-program - execute a program with given arguments,
799 * but don't wait for it.
800 * If the program can't be executed, logs an error unless
801 * must_exist is 0 and the program file doesn't exist.
804 run_program(prog, args, must_exist)
814 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
820 /* Leave the current location */
821 (void) setsid(); /* No controlling tty. */
822 (void) umask (S_IRWXG|S_IRWXO);
823 (void) chdir ("/"); /* no current directory. */
827 /* Ensure that nothing of our device environment is inherited. */
831 close (fd); /* tty interface to the ppp device */
832 /* XXX should call sysdep cleanup procedure here */
834 /* Don't pass handles to the PPP device, even by accident. */
835 new_fd = open (_PATH_DEVNULL, O_RDWR);
838 dup2 (new_fd, 0); /* stdin <- /dev/null */
841 dup2 (0, 1); /* stdout -> /dev/null */
842 dup2 (0, 2); /* stderr -> /dev/null */
846 /* Force the priority back to zero if pppd is running higher. */
847 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
848 syslog (LOG_WARNING, "can't reset priority to 0: %m");
851 /* SysV recommends a second fork at this point. */
853 /* run the program; give it a null environment */
855 execve(prog, args, nullenv);
856 if (must_exist || errno != ENOENT)
857 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
860 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
867 * reap_kids - get status from any dead child processes,
868 * and log a message for abnormal terminations.
877 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
879 syslog(LOG_ERR, "Error waiting for child process: %m");
884 if (WIFSIGNALED(status)) {
885 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
886 pid, WTERMSIG(status));
893 * log_packet - format a packet and log it.
896 char line[256]; /* line to be logged accumulated here */
900 log_packet(p, len, prefix)
905 strcpy(line, prefix);
906 linep = line + strlen(line);
907 format_packet(p, len, pr_log, NULL);
909 syslog(LOG_DEBUG, "%s", line);
913 * format_packet - make a readable representation of a packet,
914 * calling `printer(arg, format, ...)' to output it.
917 format_packet(p, len, printer, arg)
920 void (*printer) __P((void *, char *, ...));
927 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
931 for (i = 0; i < N_PROTO; ++i)
932 if (proto == prottbl[i].protocol)
935 printer(arg, "[%s", prottbl[i].name);
936 n = (*prottbl[i].printpkt)(p, len, printer, arg);
941 printer(arg, "[proto=0x%x]", proto);
945 for (; len > 0; --len) {
947 printer(arg, " %.2x", x);
955 pr_log(void *arg, char *fmt, ...)
962 vsprintf(buf, fmt, pvar);
966 if (linep + n + 1 > line + sizeof(line)) {
967 syslog(LOG_DEBUG, "%s", line);
978 pr_log(arg, fmt, va_alist)
988 vsprintf(buf, fmt, pvar);
992 if (linep + n + 1 > line + sizeof(line)) {
993 syslog(LOG_DEBUG, "%s", line);
1002 * print_string - print a readable representation of a string using
1006 print_string(p, len, printer, arg)
1009 void (*printer) __P((void *, char *, ...));
1015 for (; len > 0; --len) {
1017 if (' ' <= c && c <= '~')
1018 printer(arg, "%c", c);
1020 printer(arg, "\\%.3o", c);
1026 * novm - log an error message saying we ran out of memory, and die.
1032 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);