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.29 1995/12/18 03:50:17 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"
56 #endif /* IPX_CHANGE */
59 * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
60 * /etc/ppp/options exists.
62 #ifndef REQ_SYSOPTIONS
63 #define REQ_SYSOPTIONS 1
67 char ifname[IFNAMSIZ]; /* Interface name */
68 int ifunit; /* Interface unit number */
70 char *progname; /* Name of this program */
71 char hostname[MAXNAMELEN]; /* Our hostname */
72 static char pidfilename[MAXPATHLEN]; /* name of pid file */
73 static char default_devnam[MAXPATHLEN]; /* name of default device */
74 static pid_t pid; /* Our pid */
75 static pid_t pgrpid; /* Process Group ID */
76 static uid_t uid; /* Our real user-id */
78 int fd = -1; /* Device file descriptor */
80 int phase; /* where the link is at */
84 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
85 static u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
87 int hungup; /* terminal has been hung up */
88 static int n_children; /* # child processes still running */
90 int baud_rate; /* Actual bits/second for serial device */
92 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
94 /* Prototypes for procedures local to this file. */
96 static void cleanup __P((void));
97 static void close_fd __P((void));
98 static void get_input __P((void));
99 static void connect_time_expired __P((caddr_t));
100 static void calltimeout __P((void));
101 static struct timeval *timeleft __P((struct timeval *));
102 static void hup __P((int));
103 static void term __P((int));
104 static void chld __P((int));
105 static void toggle_debug __P((int));
106 static void open_ccp __P((int));
107 static void bad_signal __P((int));
108 static int device_script __P((char *, int, int));
109 static void reap_kids __P((void));
110 static 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.
123 * The last entry must be NULL.
125 struct protent *protocols[] = {
141 int i, nonblock, fdflags;
149 struct protent *protp;
154 strcpy(default_devnam, devnam);
156 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
157 perror("couldn't get hostname");
160 hostname[MAXNAMELEN-1] = 0;
165 * Initialize to the standard option set, then parse, in order,
166 * the system options file, the user's options file, and the command
169 for (i = 0; (protp = protocols[i]) != NULL; ++i)
174 if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
175 !options_from_user() ||
176 !parse_args(argc-1, argv+1) ||
180 if (!ppp_available()) {
181 fprintf(stderr, no_ppp_msg);
186 remove_sys_options();
187 #endif /* IPX_CHANGE */
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 * Set a timeout to close the connection once the maximum
366 * connect time has expired.
369 TIMEOUT(connect_time_expired, 0, maxconnect);
372 * Block all signals, start opening the connection, and wait for
373 * incoming events (reply, timeout, etc.).
375 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
377 lcp_open(0); /* Start protocol */
378 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
379 wait_input(timeleft(&timo));
383 lcp_close(0, "User request");
384 phase = PHASE_TERMINATE;
388 if (phase == PHASE_NETWORK) {
389 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
394 reap_kids(); /* Don't leave dead kids lying around */
398 * Run disconnector script, if requested.
399 * XXX we may not be able to do this if the line has hung up!
404 if (device_script(disconnector, fd, fd) < 0) {
405 syslog(LOG_WARNING, "disconnect script failed");
407 syslog(LOG_INFO, "Serial link disconnected.");
412 if (unlink(pidfilename) < 0 && errno != ENOENT)
413 syslog(LOG_WARNING, "unable to delete pid file: %m");
423 * get_input - called when incoming data is available.
431 struct protent *protp;
433 p = inpacket_buf; /* point to beginning of packet buffer */
435 len = read_packet(inpacket_buf);
440 syslog(LOG_NOTICE, "Modem hangup");
442 lcp_lowerdown(0); /* serial link is no longer available */
447 if (debug /*&& (debugflags & DBG_INPACKET)*/)
448 log_packet(p, len, "rcvd ");
450 if (len < PPP_HDRLEN) {
451 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
455 p += 2; /* Skip address and control */
456 GETSHORT(protocol, p);
460 * Toss all non-LCP packets unless LCP is OPEN.
462 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
464 "io(): Received non-LCP packet when LCP not open."));
469 * Upcall the proper protocol input routine.
471 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
472 if (protp->protocol == protocol && protp->enabled_flag) {
473 (*protp->input)(0, p, len);
476 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
477 && protp->datainput != NULL) {
478 (*protp->datainput)(0, p, len);
484 syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
485 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
490 * quit - Clean up state and exit (with an error indication).
499 * die - like quit, except we can specify an exit status.
506 syslog(LOG_INFO, "Exit.");
511 * connect_time_expired - log a message and close the connection.
514 connect_time_expired(arg)
517 syslog(LOG_INFO, "Connect time expired");
519 phase = PHASE_TERMINATE;
520 lcp_close(0, "Connect time expired"); /* Close connection */
524 * cleanup - restore anything which needs to be restored before we exit
535 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
536 syslog(LOG_WARNING, "unable to delete pid file: %m");
539 if (lockflag && !default_device)
544 * close_fd - restore the terminal device and close it.
551 /* drop dtr to hang up */
563 struct timeval c_time; /* time at which to call routine */
564 caddr_t c_arg; /* argument to routine */
565 void (*c_func)(); /* routine */
566 struct callout *c_next;
569 static struct callout *callout = NULL; /* Callout list */
570 static struct timeval timenow; /* Current time */
573 * timeout - Schedule a timeout.
575 * Note that this timeout takes the number of seconds, NOT hz (as in
579 timeout(func, arg, time)
584 struct callout *newp, *p, **pp;
586 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
587 (long) func, (long) arg, time));
592 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
593 syslog(LOG_ERR, "Out of memory in timeout()!");
598 gettimeofday(&timenow, NULL);
599 newp->c_time.tv_sec = timenow.tv_sec + time;
600 newp->c_time.tv_usec = timenow.tv_usec;
603 * Find correct place and link it in.
605 for (pp = &callout; (p = *pp); pp = &p->c_next)
606 if (newp->c_time.tv_sec < p->c_time.tv_sec
607 || (newp->c_time.tv_sec == p->c_time.tv_sec
608 && newp->c_time.tv_usec < p->c_time.tv_sec))
616 * untimeout - Unschedule a timeout.
623 struct itimerval itv;
624 struct callout **copp, *freep;
627 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
630 * Find first matching timeout and remove it from the list.
632 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
633 if (freep->c_func == func && freep->c_arg == arg) {
634 *copp = freep->c_next;
635 (void) free((char *) freep);
642 * calltimeout - Call any timeout routines which are now due.
649 while (callout != NULL) {
652 if (gettimeofday(&timenow, NULL) < 0) {
653 syslog(LOG_ERR, "Failed to get time of day: %m");
656 if (!(p->c_time.tv_sec < timenow.tv_sec
657 || (p->c_time.tv_sec == timenow.tv_sec
658 && p->c_time.tv_usec <= timenow.tv_usec)))
659 break; /* no, it's not time yet */
662 (*p->c_func)(p->c_arg);
670 * timeleft - return the length of time until the next timeout is due.
672 static struct timeval *
679 gettimeofday(&timenow, NULL);
680 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
681 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
682 if (tvp->tv_usec < 0) {
683 tvp->tv_usec += 1000000;
687 tvp->tv_sec = tvp->tv_usec = 0;
694 * hup - Catch SIGHUP signal.
696 * Indicates that the physical layer has been disconnected.
697 * We don't rely on this indication; if the user has sent this
698 * signal, we just take the link down.
704 syslog(LOG_INFO, "Hangup (SIGHUP)");
710 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
712 * Indicates that we should initiate a graceful disconnect and exit.
719 syslog(LOG_INFO, "Terminating on signal %d.", sig);
720 persist = 0; /* don't try to restart */
726 * chld - Catch SIGCHLD signal.
727 * Calls reap_kids to get status for any dead kids.
738 * toggle_debug - Catch SIGUSR1 signal.
753 * open_ccp - Catch SIGUSR2 signal.
755 * Try to (re)negotiate compression.
767 * bad_signal - We've caught a fatal signal. Clean up state and exit.
773 syslog(LOG_ERR, "Fatal signal %d", sig);
779 * device_script - run a program to connect or disconnect the
783 device_script(program, in, out)
794 syslog(LOG_ERR, "Failed to create child process: %m");
801 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
806 execl("/bin/sh", "sh", "-c", program, (char *)0);
807 syslog(LOG_ERR, "could not exec /bin/sh: %m");
812 while (waitpid(pid, &status, 0) < 0) {
815 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
819 return (status == 0 ? 0 : -1);
824 * run-program - execute a program with given arguments,
825 * but don't wait for it.
826 * If the program can't be executed, logs an error unless
827 * must_exist is 0 and the program file doesn't exist.
830 run_program(prog, args, must_exist)
840 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
846 /* Leave the current location */
847 (void) setsid(); /* No controlling tty. */
848 (void) umask (S_IRWXG|S_IRWXO);
849 (void) chdir ("/"); /* no current directory. */
853 /* Ensure that nothing of our device environment is inherited. */
857 close (fd); /* tty interface to the ppp device */
858 /* XXX should call sysdep cleanup procedure here */
860 /* Don't pass handles to the PPP device, even by accident. */
861 new_fd = open (_PATH_DEVNULL, O_RDWR);
864 dup2 (new_fd, 0); /* stdin <- /dev/null */
867 dup2 (0, 1); /* stdout -> /dev/null */
868 dup2 (0, 2); /* stderr -> /dev/null */
872 /* Force the priority back to zero if pppd is running higher. */
873 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
874 syslog (LOG_WARNING, "can't reset priority to 0: %m");
877 /* SysV recommends a second fork at this point. */
879 /* run the program; give it a null environment */
881 execve(prog, args, nullenv);
882 if (must_exist || errno != ENOENT)
883 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
886 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
893 * reap_kids - get status from any dead child processes,
894 * and log a message for abnormal terminations.
903 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
905 syslog(LOG_ERR, "Error waiting for child process: %m");
910 if (WIFSIGNALED(status)) {
911 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
912 pid, WTERMSIG(status));
919 * log_packet - format a packet and log it.
922 char line[256]; /* line to be logged accumulated here */
926 log_packet(p, len, prefix)
931 strcpy(line, prefix);
932 linep = line + strlen(line);
933 format_packet(p, len, pr_log, NULL);
935 syslog(LOG_DEBUG, "%s", line);
939 * format_packet - make a readable representation of a packet,
940 * calling `printer(arg, format, ...)' to output it.
943 format_packet(p, len, printer, arg)
946 void (*printer) __P((void *, char *, ...));
952 struct protent *protp;
954 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
958 for (i = 0; (protp = protocols[i]) != NULL; ++i)
959 if (proto == protp->protocol)
962 printer(arg, "[%s", protp->name);
963 n = (*protp->printpkt)(p, len, printer, arg);
968 printer(arg, "[proto=0x%x]", proto);
972 for (; len > 0; --len) {
974 printer(arg, " %.2x", x);
982 pr_log(void *arg, char *fmt, ...)
989 vsprintf(buf, fmt, pvar);
993 if (linep + n + 1 > line + sizeof(line)) {
994 syslog(LOG_DEBUG, "%s", line);
1001 #else /* __STDC__ */
1002 #include <varargs.h>
1005 pr_log(arg, fmt, va_alist)
1015 vsprintf(buf, fmt, pvar);
1019 if (linep + n + 1 > line + sizeof(line)) {
1020 syslog(LOG_DEBUG, "%s", line);
1029 * print_string - print a readable representation of a string using
1033 print_string(p, len, printer, arg)
1036 void (*printer) __P((void *, char *, ...));
1042 for (; len > 0; --len) {
1044 if (' ' <= c && c <= '~')
1045 printer(arg, "%c", c);
1047 printer(arg, "\\%.3o", c);
1053 * novm - log an error message saying we ran out of memory, and die.
1059 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);