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.21 1995/04/24 05:56:13 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];
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]))
164 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
165 perror("couldn't get hostname");
168 hostname[MAXNAMELEN-1] = 0;
172 if (!ppp_available()) {
173 fprintf(stderr, "Sorry - PPP is not available on this system\n");
178 * Initialize to the standard option set, then parse, in order,
179 * the system options file, the user's options file, and the command
182 for (i = 0; i < N_PROTO; i++)
183 (*prottbl[i].init)(0);
187 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
188 !options_from_user() ||
189 !parse_args(argc-1, argv+1) ||
192 check_auth_options();
196 * Initialize system-dependent stuff and magic number package.
202 * Detach ourselves from the terminal, if required,
203 * and identify who is running us.
205 if (!default_device && !nodetach && daemon(0, 0) < 0) {
206 perror("Couldn't detach from controlling terminal");
213 if (pw != NULL && pw->pw_name != NULL)
218 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
219 VERSION, PATCHLEVEL, p, uid);
222 * Compute mask of all interesting signals and install signal handlers
223 * for each. Only one signal handler may be active at a time. Therefore,
224 * all other signals should be masked when any handler is executing.
227 sigaddset(&mask, SIGHUP);
228 sigaddset(&mask, SIGINT);
229 sigaddset(&mask, SIGTERM);
230 sigaddset(&mask, SIGCHLD);
232 #define SIGNAL(s, handler) { \
233 sa.sa_handler = handler; \
234 if (sigaction(s, &sa, NULL) < 0) { \
235 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
242 SIGNAL(SIGHUP, hup); /* Hangup */
243 SIGNAL(SIGINT, term); /* Interrupt */
244 SIGNAL(SIGTERM, term); /* Terminate */
245 SIGNAL(SIGCHLD, chld);
247 signal(SIGUSR1, toggle_debug); /* Toggle debug flag */
248 signal(SIGUSR2, open_ccp); /* Reopen CCP */
251 * Lock the device if we've been asked to.
253 if (lockflag && !default_device)
254 if (lock(devnam) < 0)
260 * Open the serial device and set it up to be the ppp interface.
261 * If we're dialling out, or we don't want to use the modem lines,
262 * we open it in non-blocking mode, but then we need to clear
263 * the non-blocking I/O bit.
265 nonblock = (connector || !modem)? O_NONBLOCK: 0;
266 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
267 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
270 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
271 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
275 initfdflags &= ~O_NONBLOCK;
276 fcntl(fd, F_SETFL, initfdflags);
281 /* run connection script */
282 if (connector && connector[0]) {
283 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
285 /* set line speed, flow control, etc.; set CLOCAL for now */
288 /* drop dtr to hang up in case modem is off hook */
289 if (!default_device && modem) {
295 if (device_script(connector, fd, fd) < 0) {
296 syslog(LOG_ERR, "Connect script failed");
301 syslog(LOG_INFO, "Connected...");
302 sleep(1); /* give it time to set up its terminal */
305 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
308 /* set up the serial device as a ppp interface */
311 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
312 (void) sprintf(ifname, "ppp%d", ifunit);
314 /* write pid to file */
315 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
316 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
317 fprintf(pidfile, "%d\n", pid);
318 (void) fclose(pidfile);
320 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
325 * Set device for non-blocking reads.
327 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
328 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
333 * Block all signals, start opening the connection, and wait for
334 * incoming events (reply, timeout, etc.).
336 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
338 lcp_open(0); /* Start protocol */
339 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
340 wait_input(timeleft(&timo));
347 if (phase == PHASE_NETWORK) {
348 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
354 reap_kids(); /* Don't leave dead kids lying around */
358 * Run disconnector script, if requested.
359 * First we need to reset non-blocking mode.
361 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
366 if (device_script(disconnector, fd, fd) < 0) {
367 syslog(LOG_WARNING, "disconnect script failed");
371 syslog(LOG_INFO, "Disconnected...");
375 if (unlink(pidfilename) < 0 && errno != ENOENT)
376 syslog(LOG_WARNING, "unable to delete pid file: %m");
381 if (lockflag && !default_device)
389 * get_input - called when incoming data is available.
398 p = inpacket_buf; /* point to beginning of packet buffer */
400 len = read_packet(inpacket_buf);
405 MAINDEBUG((LOG_DEBUG, "End of file on fd!"));
407 lcp_lowerdown(0); /* serial link is no longer available */
412 if (debug /*&& (debugflags & DBG_INPACKET)*/)
413 log_packet(p, len, "rcvd ");
415 if (len < PPP_HDRLEN) {
416 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
420 p += 2; /* Skip address and control */
421 GETSHORT(protocol, p);
425 * Toss all non-LCP packets unless LCP is OPEN.
427 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
429 "io(): Received non-LCP packet when LCP not open."));
434 * Upcall the proper protocol input routine.
436 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
437 if (prottbl[i].protocol == protocol) {
438 (*prottbl[i].input)(0, p, len);
440 } else if (protocol == (prottbl[i].protocol & ~0x8000)
441 && prottbl[i].datainput != NULL) {
442 (*prottbl[i].datainput)(0, p, len);
446 if (i == sizeof (prottbl) / sizeof (struct protent)) {
448 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
449 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
455 * demuxprotrej - Demultiplex a Protocol-Reject.
458 demuxprotrej(unit, protocol)
465 * Upcall the proper Protocol-Reject routine.
467 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
468 if (prottbl[i].protocol == protocol) {
469 (*prottbl[i].protrej)(unit);
474 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
480 * quit - Clean up state and exit.
489 * die - like quit, except we can specify an exit status.
496 syslog(LOG_INFO, "Exit.");
501 * cleanup - restore anything which needs to be restored before we exit
512 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
513 syslog(LOG_WARNING, "unable to delete pid file: %m");
516 if (lockflag && !default_device)
521 * close_fd - restore the terminal device and close it.
526 /* drop dtr to hang up */
530 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
531 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
544 struct timeval c_time; /* time at which to call routine */
545 caddr_t c_arg; /* argument to routine */
546 void (*c_func)(); /* routine */
547 struct callout *c_next;
550 static struct callout *callout = NULL; /* Callout list */
551 static struct timeval timenow; /* Current time */
554 * timeout - Schedule a timeout.
556 * Note that this timeout takes the number of seconds, NOT hz (as in
560 timeout(func, arg, time)
565 struct callout *newp, *p, **pp;
567 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
568 (long) func, (long) arg, time));
573 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
574 syslog(LOG_ERR, "Out of memory in timeout()!");
579 gettimeofday(&timenow, NULL);
580 newp->c_time.tv_sec = timenow.tv_sec + time;
581 newp->c_time.tv_usec = timenow.tv_usec;
584 * Find correct place and link it in.
586 for (pp = &callout; (p = *pp); pp = &p->c_next)
587 if (newp->c_time.tv_sec < p->c_time.tv_sec
588 || (newp->c_time.tv_sec == p->c_time.tv_sec
589 && newp->c_time.tv_usec < p->c_time.tv_sec))
597 * untimeout - Unschedule a timeout.
604 struct itimerval itv;
605 struct callout **copp, *freep;
608 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
611 * Find first matching timeout and remove it from the list.
613 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
614 if (freep->c_func == func && freep->c_arg == arg) {
615 *copp = freep->c_next;
616 (void) free((char *) freep);
623 * calltimeout - Call any timeout routines which are now due.
630 while (callout != NULL) {
633 if (gettimeofday(&timenow, NULL) < 0) {
634 syslog(LOG_ERR, "Failed to get time of day: %m");
637 if (!(p->c_time.tv_sec < timenow.tv_sec
638 || (p->c_time.tv_sec == timenow.tv_sec
639 && p->c_time.tv_usec <= timenow.tv_usec)))
640 break; /* no, it's not time yet */
643 (*p->c_func)(p->c_arg);
651 * timeleft - return the length of time until the next timeout is due.
660 gettimeofday(&timenow, NULL);
661 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
662 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
663 if (tvp->tv_usec < 0) {
664 tvp->tv_usec += 1000000;
668 tvp->tv_sec = tvp->tv_usec = 0;
675 * hup - Catch SIGHUP signal.
677 * Indicates that the physical layer has been disconnected.
678 * We don't rely on this indication; if the user has sent this
679 * signal, we just take the link down.
685 syslog(LOG_INFO, "Hangup (SIGHUP)");
691 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
693 * Indicates that we should initiate a graceful disconnect and exit.
700 syslog(LOG_INFO, "Terminating on signal %d.", sig);
701 persist = 0; /* don't try to restart */
707 * chld - Catch SIGCHLD signal.
708 * Calls reap_kids to get status for any dead kids.
719 * toggle_debug - Catch SIGUSR1 signal.
734 * open_ccp - Catch SIGUSR2 signal.
736 * Try to (re)negotiate compression.
748 * device_script - run a program to connect or disconnect the
752 device_script(program, in, out)
762 syslog(LOG_ERR, "Failed to create child process: %m");
771 execl("/bin/sh", "sh", "-c", program, (char *)0);
772 syslog(LOG_ERR, "could not exec /bin/sh: %m");
777 while (waitpid(pid, &status, 0) < 0) {
780 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
784 return (status == 0 ? 0 : -1);
789 * run-program - execute a program with given arguments,
790 * but don't wait for it.
791 * If the program can't be executed, logs an error unless
792 * must_exist is 0 and the program file doesn't exist.
795 run_program(prog, args, must_exist)
805 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
811 /* Leave the current location */
812 (void) setsid(); /* No controlling tty. */
813 (void) umask (S_IRWXG|S_IRWXO);
814 (void) chdir ("/"); /* no current directory. */
818 /* Ensure that nothing of our device environment is inherited. */
822 close (fd); /* tty interface to the ppp device */
823 /* XXX should call sysdep cleanup procedure here */
825 /* Don't pass handles to the PPP device, even by accident. */
826 new_fd = open (_PATH_DEVNULL, O_RDWR);
829 dup2 (new_fd, 0); /* stdin <- /dev/null */
832 dup2 (0, 1); /* stdout -> /dev/null */
833 dup2 (0, 2); /* stderr -> /dev/null */
837 /* Force the priority back to zero if pppd is running higher. */
838 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
839 syslog (LOG_WARNING, "can't reset priority to 0: %m");
842 /* SysV recommends a second fork at this point. */
844 /* run the program; give it a null environment */
846 execve(prog, args, nullenv);
847 if (must_exist || errno != ENOENT)
848 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
851 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
858 * reap_kids - get status from any dead child processes,
859 * and log a message for abnormal terminations.
868 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
870 syslog(LOG_ERR, "Error waiting for child process: %m");
875 if (WIFSIGNALED(status)) {
876 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
877 pid, WTERMSIG(status));
884 * log_packet - format a packet and log it.
887 char line[256]; /* line to be logged accumulated here */
891 log_packet(p, len, prefix)
896 strcpy(line, prefix);
897 linep = line + strlen(line);
898 format_packet(p, len, pr_log, NULL);
900 syslog(LOG_DEBUG, "%s", line);
904 * format_packet - make a readable representation of a packet,
905 * calling `printer(arg, format, ...)' to output it.
908 format_packet(p, len, printer, arg)
911 void (*printer) __P((void *, char *, ...));
918 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
922 for (i = 0; i < N_PROTO; ++i)
923 if (proto == prottbl[i].protocol)
926 printer(arg, "[%s", prottbl[i].name);
927 n = (*prottbl[i].printpkt)(p, len, printer, arg);
932 printer(arg, "[proto=0x%x]", proto);
936 for (; len > 0; --len) {
938 printer(arg, " %.2x", x);
946 pr_log(void *arg, char *fmt, ...)
953 vsprintf(buf, fmt, pvar);
957 if (linep + n + 1 > line + sizeof(line)) {
958 syslog(LOG_DEBUG, "%s", line);
969 pr_log(arg, fmt, va_alist)
979 vsprintf(buf, fmt, pvar);
983 if (linep + n + 1 > line + sizeof(line)) {
984 syslog(LOG_DEBUG, "%s", line);
993 * print_string - print a readable representation of a string using
997 print_string(p, len, printer, arg)
1000 void (*printer) __P((void *, char *, ...));
1006 for (; len > 0; --len) {
1008 if (' ' <= c && c <= '~')
1009 printer(arg, "%c", c);
1011 printer(arg, "\\%.3o", c);
1017 * novm - log an error message saying we ran out of memory, and die.
1023 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);