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.27 1995/08/16 01:39:08 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 */
90 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
93 static void hup __P((int));
94 static void term __P((int));
95 static void chld __P((int));
96 static void toggle_debug __P((int));
97 static void open_ccp __P((int));
98 static void bad_signal __P((int));
100 static void get_input __P((void));
101 void establish_ppp __P((void));
102 void calltimeout __P((void));
103 struct timeval *timeleft __P((struct timeval *));
104 void reap_kids __P((void));
105 void cleanup __P((int, caddr_t));
106 void close_fd __P((void));
108 void novm __P((char *));
110 void log_packet __P((u_char *, int, char *));
111 void format_packet __P((u_char *, int,
112 void (*) (void *, char *, ...), void *));
113 void pr_log __P((void *, char *, ...));
115 extern char *ttyname __P((int));
116 extern char *getlogin __P((void));
120 #define O_NONBLOCK O_NDELAY
124 * PPP Data Link Layer "protocol" table.
125 * One entry per supported protocol.
127 static struct protent {
136 { PPP_LCP, lcp_init, lcp_input, lcp_protrej,
137 lcp_printpkt, NULL, "LCP" },
138 { PPP_IPCP, ipcp_init, ipcp_input, ipcp_protrej,
139 ipcp_printpkt, NULL, "IPCP" },
140 { PPP_PAP, upap_init, upap_input, upap_protrej,
141 upap_printpkt, NULL, "PAP" },
142 { PPP_CHAP, ChapInit, ChapInput, ChapProtocolReject,
143 ChapPrintPkt, NULL, "CHAP" },
144 { PPP_CCP, ccp_init, ccp_input, ccp_protrej,
145 ccp_printpkt, ccp_datainput, "CCP" },
148 #define N_PROTO (sizeof(prottbl) / sizeof(prottbl[0]))
166 strcpy(default_devnam, devnam);
168 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
169 perror("couldn't get hostname");
172 hostname[MAXNAMELEN-1] = 0;
176 if (!ppp_available()) {
177 fprintf(stderr, no_ppp_msg);
182 * Initialize to the standard option set, then parse, in order,
183 * the system options file, the user's options file, and the command
186 for (i = 0; i < N_PROTO; i++)
187 (*prottbl[i].init)(0);
191 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
192 !options_from_user() ||
193 !parse_args(argc-1, argv+1) ||
196 check_auth_options();
200 * If the user has specified the default device name explicitly,
201 * pretend they hadn't.
203 if (!default_device && strcmp(devnam, default_devnam) == 0)
207 * Initialize system-dependent stuff and magic number package.
213 * Detach ourselves from the terminal, if required,
214 * and identify who is running us.
216 if (!default_device && !nodetach && daemon(0, 0) < 0) {
217 perror("Couldn't detach from controlling terminal");
224 if (pw != NULL && pw->pw_name != NULL)
229 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
230 VERSION, PATCHLEVEL, p, uid);
233 * Compute mask of all interesting signals and install signal handlers
234 * for each. Only one signal handler may be active at a time. Therefore,
235 * all other signals should be masked when any handler is executing.
238 sigaddset(&mask, SIGHUP);
239 sigaddset(&mask, SIGINT);
240 sigaddset(&mask, SIGTERM);
241 sigaddset(&mask, SIGCHLD);
243 #define SIGNAL(s, handler) { \
244 sa.sa_handler = handler; \
245 if (sigaction(s, &sa, NULL) < 0) { \
246 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
253 SIGNAL(SIGHUP, hup); /* Hangup */
254 SIGNAL(SIGINT, term); /* Interrupt */
255 SIGNAL(SIGTERM, term); /* Terminate */
256 SIGNAL(SIGCHLD, chld);
258 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
259 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
262 * Install a handler for other signals which would otherwise
263 * cause pppd to exit without cleaning up.
265 SIGNAL(SIGABRT, bad_signal);
266 SIGNAL(SIGALRM, bad_signal);
267 SIGNAL(SIGFPE, bad_signal);
268 SIGNAL(SIGILL, bad_signal);
269 SIGNAL(SIGPIPE, bad_signal);
270 SIGNAL(SIGQUIT, bad_signal);
271 SIGNAL(SIGSEGV, bad_signal);
273 SIGNAL(SIGBUS, bad_signal);
276 SIGNAL(SIGEMT, bad_signal);
279 SIGNAL(SIGPOLL, bad_signal);
282 SIGNAL(SIGPROF, bad_signal);
285 SIGNAL(SIGSYS, bad_signal);
288 SIGNAL(SIGTRAP, bad_signal);
291 SIGNAL(SIGVTALRM, bad_signal);
294 SIGNAL(SIGXCPU, bad_signal);
297 SIGNAL(SIGXFSZ, bad_signal);
301 * Lock the device if we've been asked to.
303 if (lockflag && !default_device)
304 if (lock(devnam) < 0)
310 * Open the serial device and set it up to be the ppp interface.
311 * If we're dialling out, or we don't want to use the modem lines,
312 * we open it in non-blocking mode, but then we need to clear
313 * the non-blocking I/O bit.
315 nonblock = (connector || !modem)? O_NONBLOCK: 0;
316 if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
317 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
320 if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
321 syslog(LOG_ERR, "Couldn't get device fd flags: %m");
325 initfdflags &= ~O_NONBLOCK;
326 fcntl(fd, F_SETFL, initfdflags);
331 /* run connection script */
332 if (connector && connector[0]) {
333 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
335 /* set line speed, flow control, etc.; set CLOCAL for now */
338 /* drop dtr to hang up in case modem is off hook */
339 if (!default_device && modem) {
345 if (device_script(connector, fd, fd) < 0) {
346 syslog(LOG_ERR, "Connect script failed");
351 syslog(LOG_INFO, "Serial connection established.");
352 sleep(1); /* give it time to set up its terminal */
355 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
358 /* set up the serial device as a ppp interface */
361 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
362 (void) sprintf(ifname, "ppp%d", ifunit);
364 /* write pid to file */
365 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
366 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
367 fprintf(pidfile, "%d\n", pid);
368 (void) fclose(pidfile);
370 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
375 * Set device for non-blocking reads.
377 if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
378 syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
383 * Block all signals, start opening the connection, and wait for
384 * incoming events (reply, timeout, etc.).
386 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
388 lcp_open(0); /* Start protocol */
389 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
390 wait_input(timeleft(&timo));
398 if (phase == PHASE_NETWORK) {
399 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
404 reap_kids(); /* Don't leave dead kids lying around */
408 * Run disconnector script, if requested.
409 * First we need to reset non-blocking mode.
410 * XXX we may not be able to do this if the line has hung up!
412 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
417 if (device_script(disconnector, fd, fd) < 0) {
418 syslog(LOG_WARNING, "disconnect script failed");
420 syslog(LOG_INFO, "Serial link disconnected.");
425 if (unlink(pidfilename) < 0 && errno != ENOENT)
426 syslog(LOG_WARNING, "unable to delete pid file: %m");
436 * get_input - called when incoming data is available.
445 p = inpacket_buf; /* point to beginning of packet buffer */
447 len = read_packet(inpacket_buf);
452 syslog(LOG_NOTICE, "Modem hangup");
454 lcp_lowerdown(0); /* serial link is no longer available */
459 if (debug /*&& (debugflags & DBG_INPACKET)*/)
460 log_packet(p, len, "rcvd ");
462 if (len < PPP_HDRLEN) {
463 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
467 p += 2; /* Skip address and control */
468 GETSHORT(protocol, p);
472 * Toss all non-LCP packets unless LCP is OPEN.
474 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
476 "io(): Received non-LCP packet when LCP not open."));
481 * Upcall the proper protocol input routine.
483 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++) {
484 if (prottbl[i].protocol == protocol) {
485 (*prottbl[i].input)(0, p, len);
488 if (protocol == (prottbl[i].protocol & ~0x8000)
489 && prottbl[i].datainput != NULL) {
490 (*prottbl[i].datainput)(0, p, len);
496 syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
497 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
502 * demuxprotrej - Demultiplex a Protocol-Reject.
505 demuxprotrej(unit, protocol)
512 * Upcall the proper Protocol-Reject routine.
514 for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
515 if (prottbl[i].protocol == protocol) {
516 (*prottbl[i].protrej)(unit);
521 "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
527 * bad_signal - We've caught a fatal signal. Clean up state and exit.
533 syslog(LOG_ERR, "Fatal signal %d", sig);
538 * quit - Clean up state and exit (with an error indication).
547 * die - like quit, except we can specify an exit status.
554 syslog(LOG_INFO, "Exit.");
559 * cleanup - restore anything which needs to be restored before we exit
570 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
571 syslog(LOG_WARNING, "unable to delete pid file: %m");
574 if (lockflag && !default_device)
579 * close_fd - restore the terminal device and close it.
586 /* drop dtr to hang up */
590 if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
591 syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
602 struct timeval c_time; /* time at which to call routine */
603 caddr_t c_arg; /* argument to routine */
604 void (*c_func)(); /* routine */
605 struct callout *c_next;
608 static struct callout *callout = NULL; /* Callout list */
609 static struct timeval timenow; /* Current time */
612 * timeout - Schedule a timeout.
614 * Note that this timeout takes the number of seconds, NOT hz (as in
618 timeout(func, arg, time)
623 struct callout *newp, *p, **pp;
625 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
626 (long) func, (long) arg, time));
631 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
632 syslog(LOG_ERR, "Out of memory in timeout()!");
637 gettimeofday(&timenow, NULL);
638 newp->c_time.tv_sec = timenow.tv_sec + time;
639 newp->c_time.tv_usec = timenow.tv_usec;
642 * Find correct place and link it in.
644 for (pp = &callout; (p = *pp); pp = &p->c_next)
645 if (newp->c_time.tv_sec < p->c_time.tv_sec
646 || (newp->c_time.tv_sec == p->c_time.tv_sec
647 && newp->c_time.tv_usec < p->c_time.tv_sec))
655 * untimeout - Unschedule a timeout.
662 struct itimerval itv;
663 struct callout **copp, *freep;
666 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
669 * Find first matching timeout and remove it from the list.
671 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
672 if (freep->c_func == func && freep->c_arg == arg) {
673 *copp = freep->c_next;
674 (void) free((char *) freep);
681 * calltimeout - Call any timeout routines which are now due.
688 while (callout != NULL) {
691 if (gettimeofday(&timenow, NULL) < 0) {
692 syslog(LOG_ERR, "Failed to get time of day: %m");
695 if (!(p->c_time.tv_sec < timenow.tv_sec
696 || (p->c_time.tv_sec == timenow.tv_sec
697 && p->c_time.tv_usec <= timenow.tv_usec)))
698 break; /* no, it's not time yet */
701 (*p->c_func)(p->c_arg);
709 * timeleft - return the length of time until the next timeout is due.
718 gettimeofday(&timenow, NULL);
719 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
720 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
721 if (tvp->tv_usec < 0) {
722 tvp->tv_usec += 1000000;
726 tvp->tv_sec = tvp->tv_usec = 0;
733 * hup - Catch SIGHUP signal.
735 * Indicates that the physical layer has been disconnected.
736 * We don't rely on this indication; if the user has sent this
737 * signal, we just take the link down.
743 syslog(LOG_INFO, "Hangup (SIGHUP)");
749 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
751 * Indicates that we should initiate a graceful disconnect and exit.
758 syslog(LOG_INFO, "Terminating on signal %d.", sig);
759 persist = 0; /* don't try to restart */
765 * chld - Catch SIGCHLD signal.
766 * Calls reap_kids to get status for any dead kids.
777 * toggle_debug - Catch SIGUSR1 signal.
792 * open_ccp - Catch SIGUSR2 signal.
794 * Try to (re)negotiate compression.
806 * device_script - run a program to connect or disconnect the
810 device_script(program, in, out)
821 syslog(LOG_ERR, "Failed to create child process: %m");
828 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
833 execl("/bin/sh", "sh", "-c", program, (char *)0);
834 syslog(LOG_ERR, "could not exec /bin/sh: %m");
839 while (waitpid(pid, &status, 0) < 0) {
842 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
846 return (status == 0 ? 0 : -1);
851 * run-program - execute a program with given arguments,
852 * but don't wait for it.
853 * If the program can't be executed, logs an error unless
854 * must_exist is 0 and the program file doesn't exist.
857 run_program(prog, args, must_exist)
867 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
873 /* Leave the current location */
874 (void) setsid(); /* No controlling tty. */
875 (void) umask (S_IRWXG|S_IRWXO);
876 (void) chdir ("/"); /* no current directory. */
880 /* Ensure that nothing of our device environment is inherited. */
884 close (fd); /* tty interface to the ppp device */
885 /* XXX should call sysdep cleanup procedure here */
887 /* Don't pass handles to the PPP device, even by accident. */
888 new_fd = open (_PATH_DEVNULL, O_RDWR);
891 dup2 (new_fd, 0); /* stdin <- /dev/null */
894 dup2 (0, 1); /* stdout -> /dev/null */
895 dup2 (0, 2); /* stderr -> /dev/null */
899 /* Force the priority back to zero if pppd is running higher. */
900 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
901 syslog (LOG_WARNING, "can't reset priority to 0: %m");
904 /* SysV recommends a second fork at this point. */
906 /* run the program; give it a null environment */
908 execve(prog, args, nullenv);
909 if (must_exist || errno != ENOENT)
910 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
913 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
920 * reap_kids - get status from any dead child processes,
921 * and log a message for abnormal terminations.
930 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
932 syslog(LOG_ERR, "Error waiting for child process: %m");
937 if (WIFSIGNALED(status)) {
938 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
939 pid, WTERMSIG(status));
946 * log_packet - format a packet and log it.
949 char line[256]; /* line to be logged accumulated here */
953 log_packet(p, len, prefix)
958 strcpy(line, prefix);
959 linep = line + strlen(line);
960 format_packet(p, len, pr_log, NULL);
962 syslog(LOG_DEBUG, "%s", line);
966 * format_packet - make a readable representation of a packet,
967 * calling `printer(arg, format, ...)' to output it.
970 format_packet(p, len, printer, arg)
973 void (*printer) __P((void *, char *, ...));
980 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
984 for (i = 0; i < N_PROTO; ++i)
985 if (proto == prottbl[i].protocol)
988 printer(arg, "[%s", prottbl[i].name);
989 n = (*prottbl[i].printpkt)(p, len, printer, arg);
994 printer(arg, "[proto=0x%x]", proto);
998 for (; len > 0; --len) {
1000 printer(arg, " %.2x", x);
1008 pr_log(void *arg, char *fmt, ...)
1014 va_start(pvar, fmt);
1015 vsprintf(buf, fmt, pvar);
1019 if (linep + n + 1 > line + sizeof(line)) {
1020 syslog(LOG_DEBUG, "%s", line);
1027 #else /* __STDC__ */
1028 #include <varargs.h>
1031 pr_log(arg, fmt, va_alist)
1041 vsprintf(buf, fmt, pvar);
1045 if (linep + n + 1 > line + sizeof(line)) {
1046 syslog(LOG_DEBUG, "%s", line);
1055 * print_string - print a readable representation of a string using
1059 print_string(p, len, printer, arg)
1062 void (*printer) __P((void *, char *, ...));
1068 for (; len > 0; --len) {
1070 if (' ' <= c && c <= '~')
1071 printer(arg, "%c", c);
1073 printer(arg, "\\%.3o", c);
1079 * novm - log an error message saying we ran out of memory, and die.
1085 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);