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.64 1999/03/22 05:55:31 paulus Exp $";
37 #include <sys/param.h>
38 #include <sys/types.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
54 #include "pathnames.h"
55 #include "patchlevel.h"
62 extern char *strerror();
67 #endif /* IPX_CHANGE */
73 char ifname[32]; /* Interface name */
74 int ifunit; /* Interface unit number */
76 char *progname; /* Name of this program */
77 char hostname[MAXNAMELEN]; /* Our hostname */
78 static char pidfilename[MAXPATHLEN]; /* name of pid file */
79 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
80 static pid_t pid; /* Our pid */
81 static uid_t uid; /* Our real user-id */
82 static int conn_running; /* we have a [dis]connector running */
84 int ttyfd; /* Serial port file descriptor */
85 mode_t tty_mode = -1; /* Original access permissions to tty */
86 int baud_rate; /* Actual bits/second for serial device */
87 int hungup; /* terminal has been hung up */
88 int privileged; /* we're running as real uid root */
89 int need_holdoff; /* need holdoff period before restarting */
90 int detached; /* have detached from terminal */
91 int log_to_fd; /* send log messages to this fd too */
93 static int fd_ppp; /* fd for talking PPP */
94 static int fd_loop; /* fd for getting demand-dial packets */
95 static int pty_master; /* fd for master side of pty */
96 static int pty_slave; /* fd for slave side of pty */
97 static int real_ttyfd; /* fd for actual serial port (not pty) */
99 int phase; /* where the link is at */
104 static sigjmp_buf sigjmp;
106 char **script_env; /* Env. variable values for scripts */
107 int s_env_nalloc; /* # words avail at script_env */
109 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
110 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
112 static int n_children; /* # child processes still running */
114 static int locked; /* lock() has succeeded */
116 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
118 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
119 int ngroups; /* How many groups valid in groups */
121 static struct timeval start_time; /* Time when link was started. */
123 struct pppd_stats link_stats;
124 int link_stats_valid;
126 static int charshunt_pid; /* Process ID for charshunt */
127 static FILE *recordf; /* File for recording chars sent/rcvd */
129 /* Prototypes for procedures local to this file. */
131 static void create_pidfile __P((void));
132 static void cleanup __P((void));
133 static void close_tty __P((void));
134 static void get_input __P((void));
135 static void calltimeout __P((void));
136 static struct timeval *timeleft __P((struct timeval *));
137 static void kill_my_pg __P((int));
138 static void hup __P((int));
139 static void term __P((int));
140 static void chld __P((int));
141 static void toggle_debug __P((int));
142 static void open_ccp __P((int));
143 static void bad_signal __P((int));
144 static void holdoff_end __P((void *));
145 static int device_script __P((char *, int, int));
146 static void reap_kids __P((int waitfor));
147 static void pr_log __P((void *, char *, ...));
148 static void logit __P((int, char *, va_list));
149 static void vslp_printer __P((void *, char *, ...));
150 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
152 static void record_child __P((int, char *, void (*) (void *), void *));
153 static void charshunt __P((int));
154 static int record_write(FILE *, int code, u_char *buf, int nb,
157 extern char *ttyname __P((int));
158 extern char *getlogin __P((void));
159 int main __P((int, char *[]));
163 #define O_NONBLOCK O_NDELAY
167 #define setlogmask(x)
171 * PPP Data Link Layer "protocol" table.
172 * One entry per supported protocol.
173 * The last entry must be NULL.
175 struct protent *protocols[] = {
204 struct protent *protp;
209 phase = PHASE_INITIALIZE;
214 /* Initialize syslog facilities */
216 openlog("pppd", LOG_PID);
218 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
219 setlogmask(LOG_UPTO(LOG_INFO));
222 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
223 option_error("Couldn't get hostname: %m");
226 hostname[MAXNAMELEN-1] = 0;
229 privileged = uid == 0;
230 slprintf(numbuf, sizeof(numbuf), "%d", uid);
231 script_setenv("ORIG_UID", numbuf);
233 ngroups = getgroups(NGROUPS_MAX, groups);
236 * Initialize to the standard option set, then parse, in order,
237 * the system options file, the user's options file,
238 * the tty's options file, and the command line arguments.
240 for (i = 0; (protp = protocols[i]) != NULL; ++i)
245 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
246 || !options_from_user())
248 scan_args(argc-1, argv+1); /* look for tty name on command line */
249 if (!options_for_tty()
250 || !parse_args(argc-1, argv+1))
254 * Check that we are running as root.
256 if (geteuid() != 0) {
257 option_error("must be root to run %s, since it is not setuid-root",
262 if (!ppp_available()) {
263 option_error(no_ppp_msg);
268 * Check that the options given are valid and consistent.
270 if (!sys_check_options())
272 auth_check_options();
273 for (i = 0; (protp = protocols[i]) != NULL; ++i)
274 if (protp->check_options != NULL)
275 (*protp->check_options)();
276 if (demand && connector == 0) {
277 option_error("connect script is required for demand-dialling\n");
281 if (ptycommand != NULL || notty) {
282 if (!default_device) {
283 option_error("%s option precludes specifying device name",
284 notty? "notty": "pty");
287 if (ptycommand != NULL && (notty || record_file != NULL)) {
288 option_error("pty option is incompatible with %s option",
289 notty? "notty": "record");
292 default_device = notty;
297 * If the user has specified the default device name explicitly,
298 * pretend they hadn't.
300 p = isatty(0)? ttyname(0): NULL;
302 if (default_device) {
303 option_error("no device specified and stdin is not a tty");
308 strlcpy(devnam, p, sizeof(devnam));
309 else if (strcmp(devnam, p) == 0)
316 log_to_fd = 1; /* default to stdout */
318 script_setenv("DEVICE", devnam);
319 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
320 script_setenv("SPEED", numbuf);
323 * Open the record file (as the user) if required.
325 if (record_file != NULL) {
328 recordf = fopen(record_file, "a");
332 option_error("Couldn't create record file %s: %m", record_file);
336 * Initialize system-dependent stuff and magic number package.
341 setlogmask(LOG_UPTO(LOG_DEBUG));
344 * Detach ourselves from the terminal, if required,
345 * and identify who is running us.
347 if (!nodetach && !updetach)
353 if (pw != NULL && pw->pw_name != NULL)
358 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
359 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
362 * Compute mask of all interesting signals and install signal handlers
363 * for each. Only one signal handler may be active at a time. Therefore,
364 * all other signals should be masked when any handler is executing.
367 sigaddset(&mask, SIGHUP);
368 sigaddset(&mask, SIGINT);
369 sigaddset(&mask, SIGTERM);
370 sigaddset(&mask, SIGCHLD);
371 sigaddset(&mask, SIGUSR2);
373 #define SIGNAL(s, handler) do { \
374 sa.sa_handler = handler; \
375 if (sigaction(s, &sa, NULL) < 0) \
376 fatal("Couldn't establish signal handler (%d): %m", s); \
381 SIGNAL(SIGHUP, hup); /* Hangup */
382 SIGNAL(SIGINT, term); /* Interrupt */
383 SIGNAL(SIGTERM, term); /* Terminate */
384 SIGNAL(SIGCHLD, chld);
386 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
387 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
390 * Install a handler for other signals which would otherwise
391 * cause pppd to exit without cleaning up.
393 SIGNAL(SIGABRT, bad_signal);
394 SIGNAL(SIGALRM, bad_signal);
395 SIGNAL(SIGFPE, bad_signal);
396 SIGNAL(SIGILL, bad_signal);
397 SIGNAL(SIGPIPE, bad_signal);
398 SIGNAL(SIGQUIT, bad_signal);
399 SIGNAL(SIGSEGV, bad_signal);
401 SIGNAL(SIGBUS, bad_signal);
404 SIGNAL(SIGEMT, bad_signal);
407 SIGNAL(SIGPOLL, bad_signal);
410 SIGNAL(SIGPROF, bad_signal);
413 SIGNAL(SIGSYS, bad_signal);
416 SIGNAL(SIGTRAP, bad_signal);
419 SIGNAL(SIGVTALRM, bad_signal);
422 SIGNAL(SIGXCPU, bad_signal);
425 SIGNAL(SIGXFSZ, bad_signal);
429 * Apparently we can get a SIGPIPE when we call syslog, if
430 * syslogd has died and been restarted. Ignoring it seems
433 signal(SIGPIPE, SIG_IGN);
438 * If we're doing dial-on-demand, set up the interface now.
442 * Open the loopback channel and set it up to be the ppp interface.
444 fd_loop = open_ppp_loopback();
446 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
447 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
448 script_setenv("IFNAME", ifname);
450 create_pidfile(); /* write pid to file */
453 * Configure the interface and mark it up, etc.
466 * Don't do anything until we see some activity.
469 phase = PHASE_DORMANT;
473 if (sigsetjmp(sigjmp, 1) == 0) {
474 sigprocmask(SIG_BLOCK, &mask, NULL);
476 sigprocmask(SIG_UNBLOCK, &mask, NULL);
479 sigprocmask(SIG_UNBLOCK, &mask, NULL);
480 wait_input(timeleft(&timo));
490 if (get_loop_output())
495 if (kill_link && !persist)
499 * Now we want to bring up the link.
502 info("Starting link");
506 * Get a pty master/slave pair if the pty, notty, or record
507 * options were specified.
509 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
512 if (ptycommand != NULL || notty || record_file != NULL) {
513 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
514 error("Couldn't allocate pseudo-tty");
517 set_up_tty(pty_slave, 1);
518 if (ptycommand != NULL) {
519 if (device_script(ptycommand, pty_master, 1) < 0)
528 * Lock the device if we've been asked to.
530 if (lockflag && !default_device) {
531 if (lock(devnam) < 0)
537 * Open the serial device and set it up to be the ppp interface.
538 * First we open it in non-blocking mode so we can set the
539 * various termios flags appropriately. If we aren't dialling
540 * out and we want to use the modem lines, we reopen it later
541 * in order to wait for the carrier detect signal from the modem.
545 if (devnam[0] != 0) {
547 /* If the user specified the device name, become the
548 user before opening it. */
549 if (!devnam_info.priv)
551 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
552 if (!devnam_info.priv)
557 error("Failed to open %s: %m", devnam);
558 if (!persist || errno != EINTR)
561 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
562 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
563 warn("Couldn't reset non-blocking mode on device: %m");
566 * Do the equivalent of `mesg n' to stop broadcast messages.
568 if (fstat(ttyfd, &statbuf) < 0
569 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
570 warn("Couldn't restrict write permissions to %s: %m", devnam);
572 tty_mode = statbuf.st_mode;
575 * Set line speed, flow control, etc.
576 * If we have a non-null connection script,
577 * on most systems we set CLOCAL for now so that we can talk
578 * to the modem before carrier comes up. But this has the
579 * side effect that we might miss it if CD drops before we
580 * get to clear CLOCAL below. On systems where we can talk
581 * successfully to the modem with CLOCAL clear and CD down,
582 * we could clear CLOCAL at this point.
584 set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
589 * If the notty and/or record option was specified,
590 * start up the character shunt now.
592 if (notty || record_file != NULL) {
597 error("Can't fork process for character shunt: %m");
604 fatal("setuid failed");
609 charshunt_pid = cpid;
615 record_child(cpid, "pppd (charshunt)", NULL, NULL);
618 /* run connection script */
619 if (connector && connector[0]) {
620 MAINDEBUG(("Connecting with <%s>", connector));
622 if (real_ttyfd != -1) {
623 if (!default_device && modem) {
624 setdtr(real_ttyfd, 0); /* in case modem is off hook */
626 setdtr(real_ttyfd, 1);
630 if (device_script(connector, ttyfd, 0) < 0) {
631 error("Connect script failed");
635 info("Serial connection established.");
637 /* set line speed, flow control, etc.;
638 clear CLOCAL if modem option */
639 if (real_ttyfd != -1)
640 set_up_tty(real_ttyfd, 0);
643 /* reopen tty if necessary to wait for carrier */
644 if (connector == NULL && modem && devnam[0] != 0) {
646 if ((i = open(devnam, O_RDWR)) >= 0)
649 error("Failed to reopen %s: %m", devnam);
650 if (!persist || errno != EINTR || hungup || kill_link)
656 /* run welcome script, if any */
657 if (welcomer && welcomer[0]) {
658 if (device_script(welcomer, ttyfd, 0) < 0)
659 warn("Welcome script failed");
662 /* set up the serial device as a ppp interface */
663 fd_ppp = establish_ppp(ttyfd);
669 info("Using interface ppp%d", ifunit);
670 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
671 script_setenv("IFNAME", ifname);
673 create_pidfile(); /* write pid to file */
677 * Start opening the connection and wait for
678 * incoming events (reply, timeout, etc.).
680 notice("Connect: %s <--> %s", ifname, ppp_devnam);
681 gettimeofday(&start_time, NULL);
685 * If we are initiating this connection, wait for a short
686 * time for something from the peer. This can avoid bouncing
687 * our packets off his tty before he has it set up.
689 if (connector != NULL || ptycommand != NULL) {
696 lcp_open(0); /* Start protocol */
699 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
700 if (sigsetjmp(sigjmp, 1) == 0) {
701 sigprocmask(SIG_BLOCK, &mask, NULL);
702 if (kill_link || open_ccp_flag) {
703 sigprocmask(SIG_UNBLOCK, &mask, NULL);
706 sigprocmask(SIG_UNBLOCK, &mask, NULL);
707 wait_input(timeleft(&timo));
714 lcp_close(0, "User request");
718 if (phase == PHASE_NETWORK) {
719 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
720 (*ccp_protent.open)(0);
724 reap_kids(0); /* Don't leave dead kids lying around */
728 * Print connect time and statistics.
730 if (gettimeofday(&now, NULL) >= 0) {
731 int t = now.tv_sec - start_time.tv_sec;
732 t = (t + 5) / 6; /* now in 1/10ths of minutes */
733 info("Connect time %d.%d minutes.", t/10, t%10);
735 if (link_stats_valid) {
736 info("Sent %d bytes, received %d bytes.",
737 link_stats.bytes_out, link_stats.bytes_in);
741 * If we may want to bring the link up again, transfer
742 * the ppp unit back to the loopback. Set the
743 * real serial device back to its normal mode of operation.
749 disestablish_ppp(ttyfd);
752 * Run disconnector script, if requested.
753 * XXX we may not be able to do this if the line has hung up!
755 if (disconnector && !hungup) {
756 set_up_tty(ttyfd, 1);
757 if (device_script(disconnector, ttyfd, 0) < 0) {
758 warn("disconnect script failed");
760 info("Serial link disconnected.");
769 if (pty_slave >= 0 && pty_slave != ttyfd)
779 if (pidfilename[0] != 0
780 && unlink(pidfilename) < 0 && errno != ENOENT)
781 warn("unable to delete pid file: %m");
791 if (holdoff > 0 && need_holdoff) {
792 phase = PHASE_HOLDOFF;
793 TIMEOUT(holdoff_end, NULL, holdoff);
795 if (sigsetjmp(sigjmp, 1) == 0) {
796 sigprocmask(SIG_BLOCK, &mask, NULL);
798 sigprocmask(SIG_UNBLOCK, &mask, NULL);
801 sigprocmask(SIG_UNBLOCK, &mask, NULL);
802 wait_input(timeleft(&timo));
809 phase = PHASE_DORMANT; /* allow signal to end holdoff */
812 } while (phase == PHASE_HOLDOFF);
818 /* Wait for scripts to finish */
819 while (n_children > 0)
827 * detach - detach us from the controlling terminal.
834 if (daemon(0, 0) < 0) {
835 perror("Couldn't detach from controlling terminal");
841 /* update pid file if it has been written already */
847 * Create a file containing our process ID.
855 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
856 _PATH_VARRUN, ifname);
857 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
858 fprintf(pidfile, "%d\n", pid);
859 (void) fclose(pidfile);
861 error("Failed to create pid file %s: %m", pidfilename);
864 slprintf(numbuf, sizeof(numbuf), "%d", pid);
865 script_setenv("PPPD_PID", numbuf);
869 * holdoff_end - called via a timeout when the holdoff period ends.
875 phase = PHASE_DORMANT;
879 * get_input - called when incoming data is available.
887 struct protent *protp;
889 p = inpacket_buf; /* point to beginning of packet buffer */
891 len = read_packet(inpacket_buf);
896 notice("Modem hangup");
898 lcp_lowerdown(0); /* serial link is no longer available */
903 if (debug /*&& (debugflags & DBG_INPACKET)*/)
904 dbglog("rcvd %P", p, len);
906 if (len < PPP_HDRLEN) {
907 MAINDEBUG(("io(): Received short packet."));
911 p += 2; /* Skip address and control */
912 GETSHORT(protocol, p);
916 * Toss all non-LCP packets unless LCP is OPEN.
918 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
919 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
924 * Until we get past the authentication phase, toss all packets
925 * except LCP, LQR and authentication packets.
927 if (phase <= PHASE_AUTHENTICATE
928 && !(protocol == PPP_LCP || protocol == PPP_LQR
929 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
930 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
936 * Upcall the proper protocol input routine.
938 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
939 if (protp->protocol == protocol && protp->enabled_flag) {
940 (*protp->input)(0, p, len);
943 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
944 && protp->datainput != NULL) {
945 (*protp->datainput)(0, p, len);
951 warn("Unsupported protocol (0x%x) received", protocol);
952 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
957 * die - clean up state and exit with the specified status.
964 syslog(LOG_INFO, "Exit.");
969 * cleanup - restore anything which needs to be restored before we exit
980 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
981 warn("unable to delete pid file: %m");
989 * close_tty - restore the terminal device and close it.
994 disestablish_ppp(ttyfd);
996 /* drop dtr to hang up */
997 if (!default_device && modem) {
1000 * This sleep is in case the serial port has CLOCAL set by default,
1001 * and consequently will reassert DTR when we close the device.
1008 if (tty_mode != (mode_t) -1) {
1009 if (fchmod(ttyfd, tty_mode) != 0) {
1010 /* XXX if devnam is a symlink, this will change the link */
1011 chmod(devnam, tty_mode);
1021 struct timeval c_time; /* time at which to call routine */
1022 void *c_arg; /* argument to routine */
1023 void (*c_func) __P((void *)); /* routine */
1024 struct callout *c_next;
1027 static struct callout *callout = NULL; /* Callout list */
1028 static struct timeval timenow; /* Current time */
1031 * timeout - Schedule a timeout.
1033 * Note that this timeout takes the number of seconds, NOT hz (as in
1037 timeout(func, arg, time)
1038 void (*func) __P((void *));
1042 struct callout *newp, *p, **pp;
1044 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1049 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1050 fatal("Out of memory in timeout()!");
1052 newp->c_func = func;
1053 gettimeofday(&timenow, NULL);
1054 newp->c_time.tv_sec = timenow.tv_sec + time;
1055 newp->c_time.tv_usec = timenow.tv_usec;
1058 * Find correct place and link it in.
1060 for (pp = &callout; (p = *pp); pp = &p->c_next)
1061 if (newp->c_time.tv_sec < p->c_time.tv_sec
1062 || (newp->c_time.tv_sec == p->c_time.tv_sec
1063 && newp->c_time.tv_usec < p->c_time.tv_usec))
1071 * untimeout - Unschedule a timeout.
1074 untimeout(func, arg)
1075 void (*func) __P((void *));
1078 struct callout **copp, *freep;
1080 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1083 * Find first matching timeout and remove it from the list.
1085 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1086 if (freep->c_func == func && freep->c_arg == arg) {
1087 *copp = freep->c_next;
1088 (void) free((char *) freep);
1095 * calltimeout - Call any timeout routines which are now due.
1102 while (callout != NULL) {
1105 if (gettimeofday(&timenow, NULL) < 0)
1106 fatal("Failed to get time of day: %m");
1107 if (!(p->c_time.tv_sec < timenow.tv_sec
1108 || (p->c_time.tv_sec == timenow.tv_sec
1109 && p->c_time.tv_usec <= timenow.tv_usec)))
1110 break; /* no, it's not time yet */
1112 callout = p->c_next;
1113 (*p->c_func)(p->c_arg);
1121 * timeleft - return the length of time until the next timeout is due.
1123 static struct timeval *
1125 struct timeval *tvp;
1127 if (callout == NULL)
1130 gettimeofday(&timenow, NULL);
1131 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1132 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1133 if (tvp->tv_usec < 0) {
1134 tvp->tv_usec += 1000000;
1137 if (tvp->tv_sec < 0)
1138 tvp->tv_sec = tvp->tv_usec = 0;
1145 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1151 struct sigaction act, oldact;
1153 act.sa_handler = SIG_IGN;
1156 sigaction(sig, &act, &oldact);
1157 sigaction(sig, &oldact, NULL);
1162 * hup - Catch SIGHUP signal.
1164 * Indicates that the physical layer has been disconnected.
1165 * We don't rely on this indication; if the user has sent this
1166 * signal, we just take the link down.
1172 info("Hangup (SIGHUP)");
1175 /* Send the signal to the [dis]connector process(es) also */
1178 kill(charshunt_pid, sig);
1180 siglongjmp(sigjmp, 1);
1185 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1187 * Indicates that we should initiate a graceful disconnect and exit.
1194 info("Terminating on signal %d.", sig);
1195 persist = 0; /* don't try to restart */
1198 /* Send the signal to the [dis]connector process(es) also */
1201 kill(charshunt_pid, sig);
1203 siglongjmp(sigjmp, 1);
1208 * chld - Catch SIGCHLD signal.
1209 * Calls reap_kids to get status for any dead kids.
1216 siglongjmp(sigjmp, 1);
1221 * toggle_debug - Catch SIGUSR1 signal.
1223 * Toggle debug flag.
1232 setlogmask(LOG_UPTO(LOG_DEBUG));
1234 setlogmask(LOG_UPTO(LOG_WARNING));
1240 * open_ccp - Catch SIGUSR2 signal.
1242 * Try to (re)negotiate compression.
1251 siglongjmp(sigjmp, 1);
1256 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1262 static int crashed = 0;
1267 error("Fatal signal %d", sig);
1269 kill_my_pg(SIGTERM);
1271 kill(charshunt_pid, SIGTERM);
1277 * device_script - run a program to connect or disconnect the
1281 device_script(program, inout, dont_wait)
1295 error("Failed to create child process: %m");
1304 int newio = dup(inout);
1308 if (log_to_fd >= 0) {
1313 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1314 if (errfd >= 0 && errfd != 2) {
1325 if (getuid() != uid) {
1326 error("setuid failed");
1329 if (ttyfd > 2 && ttyfd != inout)
1332 execl("/bin/sh", "sh", "-c", program, (char *)0);
1333 error("could not exec /bin/sh: %m");
1339 record_child(pid, program, NULL, NULL);
1341 while (waitpid(pid, &status, 0) < 0) {
1344 fatal("error waiting for (dis)connection process: %m");
1349 return (status == 0 ? 0 : -1);
1354 * We maintain a list of child process pids and
1355 * functions to call when they exit.
1360 void (*done) __P((void *));
1362 struct subprocess *next;
1365 struct subprocess *children;
1368 * run-program - execute a program with given arguments,
1369 * but don't wait for it.
1370 * If the program can't be executed, logs an error unless
1371 * must_exist is 0 and the program file doesn't exist.
1372 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1373 * or isn't an executable plain file, or the process ID of the child.
1374 * If done != NULL, (*done)(arg) will be called later (within
1375 * reap_kids) iff the return value is > 0.
1378 run_program(prog, args, must_exist, done, arg)
1382 void (*done) __P((void *));
1389 * First check if the file exists and is executable.
1390 * We don't use access() because that would use the
1391 * real user-id, which might not be root, and the script
1392 * might be accessible only to root.
1395 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1396 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1397 if (must_exist || errno != ENOENT)
1398 warn("Can't execute %s: %m", prog);
1404 error("Failed to create child process for %s: %m", prog);
1410 /* Leave the current location */
1411 (void) setsid(); /* No controlling tty. */
1412 (void) umask (S_IRWXG|S_IRWXO);
1413 (void) chdir ("/"); /* no current directory. */
1414 setuid(0); /* set real UID = root */
1417 /* Ensure that nothing of our device environment is inherited. */
1423 close (ttyfd); /* tty interface to the ppp device */
1425 /* Don't pass handles to the PPP device, even by accident. */
1426 new_fd = open (_PATH_DEVNULL, O_RDWR);
1429 dup2 (new_fd, 0); /* stdin <- /dev/null */
1432 dup2 (0, 1); /* stdout -> /dev/null */
1433 dup2 (0, 2); /* stderr -> /dev/null */
1437 /* Force the priority back to zero if pppd is running higher. */
1438 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1439 warn("can't reset priority to 0: %m");
1442 /* SysV recommends a second fork at this point. */
1444 /* run the program */
1445 execve(prog, args, script_env);
1446 if (must_exist || errno != ENOENT) {
1447 /* have to reopen the log, there's nowhere else
1448 for the message to go. */
1450 openlog("pppd", LOG_PID);
1452 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1453 setlogmask(LOG_UPTO(LOG_INFO));
1455 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1462 dbglog("Script %s started; pid = %d", prog, pid);
1463 record_child(pid, prog, done, arg);
1470 * record_child - add a child process to the list for reap_kids
1474 record_child(pid, prog, done, arg)
1477 void (*done) __P((void *));
1480 struct subprocess *chp;
1484 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1486 warn("losing track of %s process", prog);
1492 chp->next = children;
1499 * reap_kids - get status from any dead child processes,
1500 * and log a message for abnormal terminations.
1507 struct subprocess *chp, **prevp;
1509 if (n_children == 0)
1511 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1514 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1515 if (chp->pid == pid)
1517 if (WIFSIGNALED(status)) {
1518 warn("Child process %s (pid %d) terminated with signal %d",
1519 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1521 dbglog("process %d (%s) finished, status = 0x%x",
1522 pid, (chp? chp->prog: "??"), status);
1523 if (chp && chp->done)
1524 (*chp->done)(chp->arg);
1526 if (pid == -1 && errno != ECHILD && errno != EINTR)
1527 error("Error waiting for child process: %m");
1532 * log_packet - format a packet and log it.
1535 char line[256]; /* line to be logged accumulated here */
1539 log_packet(p, len, prefix, level)
1545 strlcpy(line, prefix, sizeof(line));
1546 linep = line + strlen(line);
1547 format_packet(p, len, pr_log, NULL);
1549 syslog(level, "%s", line);
1553 * format_packet - make a readable representation of a packet,
1554 * calling `printer(arg, format, ...)' to output it.
1557 format_packet(p, len, printer, arg)
1560 void (*printer) __P((void *, char *, ...));
1565 struct protent *protp;
1567 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1571 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1572 if (proto == protp->protocol)
1574 if (protp != NULL) {
1575 printer(arg, "[%s", protp->name);
1576 n = (*protp->printpkt)(p, len, printer, arg);
1581 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1582 if (proto == (protp->protocol & ~0x8000))
1584 if (protp != 0 && protp->data_name != 0) {
1585 printer(arg, "[%s data]", protp->data_name);
1587 printer(arg, "%.8B ...", p);
1589 printer(arg, "%.*B", len, p);
1592 printer(arg, "[proto=0x%x]", proto);
1597 printer(arg, "%.32B ...", p);
1599 printer(arg, "%.*B", len, p);
1603 pr_log __V((void *arg, char *fmt, ...))
1610 va_start(pvar, fmt);
1615 arg = va_arg(pvar, void *);
1616 fmt = va_arg(pvar, char *);
1619 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1622 if (linep + n + 1 > line + sizeof(line)) {
1623 syslog(LOG_DEBUG, "%s", line);
1626 strlcpy(linep, buf, line + sizeof(line) - linep);
1631 * vslp_printer - used in processing a %P format
1633 struct buffer_info {
1639 vslp_printer __V((void *arg, char *fmt, ...))
1643 struct buffer_info *bi;
1646 va_start(pvar, fmt);
1651 arg = va_arg(pvar, void *);
1652 fmt = va_arg(pvar, char *);
1655 bi = (struct buffer_info *) arg;
1656 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1664 * print_string - print a readable representation of a string using
1668 print_string(p, len, printer, arg)
1671 void (*printer) __P((void *, char *, ...));
1677 for (; len > 0; --len) {
1679 if (' ' <= c && c <= '~') {
1680 if (c == '\\' || c == '"')
1682 printer(arg, "%c", c);
1686 printer(arg, "\\n");
1689 printer(arg, "\\r");
1692 printer(arg, "\\t");
1695 printer(arg, "\\%.3o", c);
1703 * novm - log an error message saying we ran out of memory, and die.
1709 fatal("Virtual memory exhausted allocating %s\n", msg);
1713 * slprintf - format a message into a buffer. Like sprintf except we
1714 * also specify the length of the output buffer, and we handle
1715 * %r (recursive format), %m (error message), %v (visible string),
1716 * %q (quoted string), %t (current time) and %I (IP address) formats.
1717 * Doesn't do floating-point formats.
1718 * Returns the number of chars put into buf.
1721 slprintf __V((char *buf, int buflen, char *fmt, ...))
1727 va_start(args, fmt);
1733 buf = va_arg(args, char *);
1734 buflen = va_arg(args, int);
1735 fmt = va_arg(args, char *);
1737 n = vslprintf(buf, buflen, fmt, args);
1743 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1745 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1748 vslprintf(buf, buflen, fmt, args)
1755 int width, prec, fillch;
1756 int base, len, neg, quoted;
1757 unsigned long val = 0;
1758 char *str, *f, *buf0;
1763 static char hexchars[] = "0123456789abcdef";
1764 struct buffer_info bufinfo;
1768 while (buflen > 0) {
1769 for (f = fmt; *f != '%' && *f != 0; ++f)
1775 memcpy(buf, fmt, len);
1790 width = va_arg(args, int);
1793 while (isdigit(c)) {
1794 width = width * 10 + c - '0';
1801 prec = va_arg(args, int);
1804 while (isdigit(c)) {
1805 prec = prec * 10 + c - '0';
1816 i = va_arg(args, int);
1825 val = va_arg(args, unsigned int);
1830 val = va_arg(args, unsigned int);
1834 val = (unsigned long) va_arg(args, void *);
1839 str = va_arg(args, char *);
1842 num[0] = va_arg(args, int);
1847 str = strerror(errno);
1850 ip = va_arg(args, u_int32_t);
1852 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1853 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1857 f = va_arg(args, char *);
1859 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1861 /* On the powerpc, a va_list is an array of 1 structure */
1862 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1870 str += 4; /* chop off the day name */
1871 str[15] = 0; /* chop off year and newline */
1873 case 'v': /* "visible" string */
1874 case 'q': /* quoted string */
1876 p = va_arg(args, unsigned char *);
1877 if (fillch == '0' && prec > 0) {
1880 n = strlen((char *)p);
1881 if (prec > 0 && prec < n)
1884 while (n > 0 && buflen > 0) {
1887 if (!quoted && c >= 0x80) {
1892 if (quoted && (c == '"' || c == '\\'))
1894 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1898 case '\t': OUTCHAR('t'); break;
1899 case '\n': OUTCHAR('n'); break;
1900 case '\b': OUTCHAR('b'); break;
1901 case '\f': OUTCHAR('f'); break;
1904 OUTCHAR(hexchars[c >> 4]);
1905 OUTCHAR(hexchars[c & 0xf]);
1919 case 'P': /* print PPP packet */
1921 bufinfo.len = buflen + 1;
1922 p = va_arg(args, unsigned char *);
1923 n = va_arg(args, int);
1924 format_packet(p, n, vslp_printer, &bufinfo);
1926 buflen = bufinfo.len - 1;
1929 p = va_arg(args, unsigned char *);
1930 for (n = prec; n > 0; --n) {
1934 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1935 OUTCHAR(hexchars[c & 0xf]);
1941 --fmt; /* so %z outputs %z etc. */
1946 str = num + sizeof(num);
1948 while (str > num + neg) {
1949 *--str = hexchars[val % base];
1951 if (--prec <= 0 && val == 0)
1963 len = num + sizeof(num) - 1 - str;
1966 if (prec > 0 && len > prec)
1972 if ((n = width - len) > 0) {
1980 memcpy(buf, str, len);
1989 * script_setenv - set an environment variable value to be used
1990 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1993 script_setenv(var, value)
1996 size_t vl = strlen(var) + strlen(value) + 2;
1998 char *p, *newstring;
2000 newstring = (char *) malloc(vl);
2003 slprintf(newstring, vl, "%s=%s", var, value);
2005 /* check if this variable is already set */
2006 if (script_env != 0) {
2007 for (i = 0; (p = script_env[i]) != 0; ++i) {
2008 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2010 script_env[i] = newstring;
2016 script_env = (char **) malloc(16 * sizeof(char *));
2017 if (script_env == 0)
2022 /* reallocate script_env with more space if needed */
2023 if (i + 1 >= s_env_nalloc) {
2025 char **newenv = (char **) realloc((void *)script_env,
2026 new_n * sizeof(char *));
2029 script_env = newenv;
2030 s_env_nalloc = new_n;
2033 script_env[i] = newstring;
2034 script_env[i+1] = 0;
2038 * script_unsetenv - remove a variable from the environment
2042 script_unsetenv(var)
2045 int vl = strlen(var);
2049 if (script_env == 0)
2051 for (i = 0; (p = script_env[i]) != 0; ++i) {
2052 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2054 while ((script_env[i] = script_env[i+1]) != 0)
2062 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
2063 * always leaves destination null-terminated (for len > 0).
2066 strlcpy(dest, src, len)
2071 size_t ret = strlen(src);
2077 strncpy(dest, src, len - 1);
2085 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
2086 * always leaves destination null-terminated (for len > 0).
2089 strlcat(dest, src, len)
2094 size_t dlen = strlen(dest);
2096 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
2100 * logit - does the hard work for fatal et al.
2103 logit(level, fmt, args)
2111 n = vslprintf(buf, sizeof(buf), fmt, args);
2112 syslog(level, "%s", buf);
2113 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
2114 if (buf[n-1] != '\n')
2116 if (write(log_to_fd, buf, n) != n)
2122 * fatal - log an error message and die horribly.
2125 fatal __V((char *fmt, ...))
2130 va_start(pvar, fmt);
2134 fmt = va_arg(pvar, char *);
2137 logit(LOG_ERR, fmt, pvar);
2140 die(1); /* as promised */
2144 * error - log an error message.
2147 error __V((char *fmt, ...))
2152 va_start(pvar, fmt);
2156 fmt = va_arg(pvar, char *);
2159 logit(LOG_ERR, fmt, pvar);
2164 * warn - log a warning message.
2167 warn __V((char *fmt, ...))
2172 va_start(pvar, fmt);
2176 fmt = va_arg(pvar, char *);
2179 logit(LOG_WARNING, fmt, pvar);
2184 * notice - log a notice-level message.
2187 notice __V((char *fmt, ...))
2192 va_start(pvar, fmt);
2196 fmt = va_arg(pvar, char *);
2199 logit(LOG_NOTICE, fmt, pvar);
2204 * info - log an informational message.
2207 info __V((char *fmt, ...))
2212 va_start(pvar, fmt);
2216 fmt = va_arg(pvar, char *);
2219 logit(LOG_INFO, fmt, pvar);
2224 * dbglog - log a debug message.
2227 dbglog __V((char *fmt, ...))
2232 va_start(pvar, fmt);
2236 fmt = va_arg(pvar, char *);
2239 logit(LOG_DEBUG, fmt, pvar);
2244 * charshunt - the character shunt, which passes characters between
2245 * the pty master side and the serial port (or stdin/stdout).
2246 * This runs as the user (not as root).
2254 fd_set ready, writey;
2255 u_char *ibufp, *obufp;
2258 int pty_readable, stdin_readable;
2259 struct timeval lasttime;
2262 * Reset signal handlers.
2264 signal(SIGHUP, SIG_DFL); /* Hangup */
2265 signal(SIGINT, SIG_DFL); /* Interrupt */
2266 signal(SIGTERM, SIG_DFL); /* Terminate */
2267 signal(SIGCHLD, SIG_DFL);
2268 signal(SIGUSR1, SIG_DFL);
2269 signal(SIGUSR2, SIG_DFL);
2270 signal(SIGABRT, SIG_DFL);
2271 signal(SIGALRM, SIG_DFL);
2272 signal(SIGFPE, SIG_DFL);
2273 signal(SIGILL, SIG_DFL);
2274 signal(SIGPIPE, SIG_DFL);
2275 signal(SIGQUIT, SIG_DFL);
2276 signal(SIGSEGV, SIG_DFL);
2278 signal(SIGBUS, SIG_DFL);
2281 signal(SIGEMT, SIG_DFL);
2284 signal(SIGPOLL, SIG_DFL);
2287 signal(SIGPROF, SIG_DFL);
2290 signal(SIGSYS, SIG_DFL);
2293 signal(SIGTRAP, SIG_DFL);
2296 signal(SIGVTALRM, SIG_DFL);
2299 signal(SIGXCPU, SIG_DFL);
2302 signal(SIGXFSZ, SIG_DFL);
2305 /* work out which fds we're using. */
2312 nfds = (ofd > pty_master? ifd: pty_master) + 1;
2314 /* set all the fds to non-blocking mode */
2315 flags = fcntl(pty_master, F_GETFL);
2317 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2318 warn("couldn't set pty master to nonblock: %m");
2319 flags = fcntl(ifd, F_GETFL);
2321 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2322 warn("couldn't set %s to nonblock: %m", (notty? "stdin": "tty"));
2324 flags = fcntl(ofd, F_GETFL);
2326 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2327 warn("couldn't set stdout to nonblock: %m");
2331 ibufp = obufp = NULL;
2332 pty_readable = stdin_readable = 1;
2333 gettimeofday(&lasttime, NULL);
2334 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2338 FD_SET(pty_master, &writey);
2339 else if (stdin_readable)
2340 FD_SET(ifd, &ready);
2342 FD_SET(ofd, &writey);
2343 else if (pty_readable)
2344 FD_SET(pty_master, &ready);
2345 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
2350 if (FD_ISSET(ifd, &ready)) {
2351 ibufp = inpacket_buf;
2352 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2353 if (nibuf < 0 && errno == EIO)
2356 if (!(errno == EINTR || errno == EAGAIN)) {
2357 error("Error reading standard input: %m");
2361 } else if (nibuf == 0) {
2362 /* end of file from stdin */
2364 /* do a 0-length write, hopefully this will generate
2365 an EOF (hangup) on the slave side. */
2366 write(pty_master, inpacket_buf, 0);
2368 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2371 FD_SET(pty_master, &writey);
2373 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2377 if (FD_ISSET(pty_master, &ready)) {
2378 obufp = outpacket_buf;
2379 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2380 if (nobuf < 0 && errno == EIO)
2383 if (!(errno == EINTR || errno == EAGAIN)) {
2384 error("Error reading pseudo-tty master: %m");
2388 } else if (nobuf == 0) {
2389 /* end of file from the pty - slave side has closed */
2391 stdin_readable = 0; /* pty is not writable now */
2395 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2398 FD_SET(ofd, &writey);
2400 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2404 if (FD_ISSET(ofd, &writey)) {
2405 n = write(ofd, obufp, nobuf);
2408 error("Error writing standard output: %m");
2418 if (FD_ISSET(pty_master, &writey)) {
2419 n = write(pty_master, ibufp, nibuf);
2422 error("Error writing pseudo-tty master: %m");
2437 record_write(f, code, buf, nb, tp)
2447 gettimeofday(&now, NULL);
2448 diff = (now.tv_sec - tp->tv_sec) * 10
2449 + (now.tv_usec - tp->tv_usec) / 100000;
2453 putc(diff >> 24, f);
2454 putc(diff >> 16, f);
2467 fwrite(buf, nb, 1, f);
2471 error("Error writing record file: %m");