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 const char rcsid[] = "$Id: main.c,v 1.81 1999/08/12 04:17:07 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"
63 #endif /* IPX_CHANGE */
69 char ifname[32]; /* Interface name */
70 int ifunit; /* Interface unit number */
72 char *progname; /* Name of this program */
73 char hostname[MAXNAMELEN]; /* Our hostname */
74 static char pidfilename[MAXPATHLEN]; /* name of pid file */
75 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
76 static uid_t uid; /* Our real user-id */
77 static int conn_running; /* we have a [dis]connector running */
79 int ttyfd; /* Serial port file descriptor */
80 mode_t tty_mode = -1; /* Original access permissions to tty */
81 int baud_rate; /* Actual bits/second for serial device */
82 int hungup; /* terminal has been hung up */
83 int privileged; /* we're running as real uid root */
84 int need_holdoff; /* need holdoff period before restarting */
85 int detached; /* have detached from terminal */
86 struct stat devstat; /* result of stat() on devnam */
87 int prepass = 0; /* doing prepass to find device name */
88 int devnam_fixed; /* set while in options.ttyxx file */
89 volatile int status; /* exit status for pppd */
90 int unsuccess; /* # unsuccessful connection attempts */
92 static int fd_ppp = -1; /* fd for talking PPP */
93 static int fd_loop; /* fd for getting demand-dial packets */
94 static int pty_master; /* fd for master side of pty */
95 static int pty_slave; /* fd for slave side of pty */
96 static int real_ttyfd; /* fd for actual serial port (not pty) */
98 int phase; /* where the link is at */
103 static sigjmp_buf sigjmp;
105 char **script_env; /* Env. variable values for scripts */
106 int s_env_nalloc; /* # words avail at script_env */
108 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
109 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
111 static int n_children; /* # child processes still running */
112 static int got_sigchld; /* set if we have received a SIGCHLD */
114 static int locked; /* lock() has succeeded */
115 static int privopen; /* don't lock, open device as root */
117 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
119 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
120 int ngroups; /* How many groups valid in groups */
122 static struct timeval start_time; /* Time when link was started. */
124 struct pppd_stats link_stats;
125 int link_connect_time;
126 int link_stats_valid;
128 static int charshunt_pid; /* Process ID for charshunt */
131 * We maintain a list of child process pids and
132 * functions to call when they exit.
137 void (*done) __P((void *));
139 struct subprocess *next;
142 static struct subprocess *children;
144 /* Prototypes for procedures local to this file. */
146 static void create_pidfile __P((void));
147 static void cleanup __P((void));
148 static void close_tty __P((void));
149 static void get_input __P((void));
150 static void calltimeout __P((void));
151 static struct timeval *timeleft __P((struct timeval *));
152 static void kill_my_pg __P((int));
153 static void hup __P((int));
154 static void term __P((int));
155 static void chld __P((int));
156 static void toggle_debug __P((int));
157 static void open_ccp __P((int));
158 static void bad_signal __P((int));
159 static void holdoff_end __P((void *));
160 static int device_script __P((char *, int, int, int));
161 static void reap_kids __P((int waitfor));
162 static void record_child __P((int, char *, void (*) (void *), void *));
163 static int start_charshunt __P((int, int));
164 static void charshunt_done __P((void *));
165 static void charshunt __P((int, int, char *));
166 static int record_write __P((FILE *, int code, u_char *buf, int nb,
169 extern char *ttyname __P((int));
170 extern char *getlogin __P((void));
171 int main __P((int, char *[]));
175 #define O_NONBLOCK O_NDELAY
179 #define setlogmask(x)
183 * PPP Data Link Layer "protocol" table.
184 * One entry per supported protocol.
185 * The last entry must be NULL.
187 struct protent *protocols[] = {
216 struct protent *protp;
220 phase = PHASE_INITIALIZE;
223 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
224 * This way we can close 0, 1, 2 in detach() without clobbering
225 * a fd that we are using.
227 if ((i = open("/dev/null", O_RDWR)) >= 0) {
228 while (0 <= i && i <= 2)
236 /* Initialize syslog facilities */
239 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
240 option_error("Couldn't get hostname: %m");
243 hostname[MAXNAMELEN-1] = 0;
246 privileged = uid == 0;
247 slprintf(numbuf, sizeof(numbuf), "%d", uid);
248 script_setenv("ORIG_UID", numbuf);
250 ngroups = getgroups(NGROUPS_MAX, groups);
253 * Initialize to the standard option set, then parse, in order,
254 * the system options file, the user's options file,
255 * the tty's options file, and the command line arguments.
257 for (i = 0; (protp = protocols[i]) != NULL; ++i)
263 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
264 || !options_from_user())
265 exit(EXIT_OPTION_ERROR);
267 /* scan command line and options files to find device name */
269 parse_args(argc-1, argv+1);
273 * Work out the device name, if it hasn't already been specified.
275 using_pty = notty || ptycommand != NULL;
276 if (!using_pty && default_device) {
278 if (!isatty(0) || (p = ttyname(0)) == NULL) {
279 option_error("no device specified and stdin is not a tty");
280 exit(EXIT_OPTION_ERROR);
282 strlcpy(devnam, p, sizeof(devnam));
283 if (stat(devnam, &devstat) < 0)
284 fatal("Couldn't stat default device %s: %m", devnam);
288 * Parse the tty options file and the command line.
289 * The per-tty options file should not change
290 * ptycommand, notty or devnam.
294 if (!options_for_tty())
295 exit(EXIT_OPTION_ERROR);
299 if (!parse_args(argc-1, argv+1))
300 exit(EXIT_OPTION_ERROR);
303 * Check that we are running as root.
305 if (geteuid() != 0) {
306 option_error("must be root to run %s, since it is not setuid-root",
311 if (!ppp_available()) {
312 option_error(no_ppp_msg);
313 exit(EXIT_NO_KERNEL_SUPPORT);
317 * Check that the options given are valid and consistent.
319 if (!sys_check_options())
320 exit(EXIT_OPTION_ERROR);
321 auth_check_options();
322 for (i = 0; (protp = protocols[i]) != NULL; ++i)
323 if (protp->check_options != NULL)
324 (*protp->check_options)();
325 if (demand && connector == 0) {
326 option_error("connect script is required for demand-dialling\n");
327 exit(EXIT_OPTION_ERROR);
331 if (!default_device) {
332 option_error("%s option precludes specifying device name",
333 notty? "notty": "pty");
334 exit(EXIT_OPTION_ERROR);
336 if (ptycommand != NULL && notty) {
337 option_error("pty option is incompatible with notty option");
338 exit(EXIT_OPTION_ERROR);
340 default_device = notty;
343 if (notty && log_to_fd <= 1)
347 * If the user has specified a device which is the same as
348 * the one on stdin, pretend they didn't specify any.
349 * If the device is already open read/write on stdin,
350 * we assume we don't need to lock it, and we can open it as root.
352 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
353 && statbuf.st_rdev == devstat.st_rdev) {
355 fdflags = fcntl(0, F_GETFL);
356 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
364 * Don't send log messages to the serial port, it tends to
365 * confuse the peer. :-)
367 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
368 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
371 script_setenv("DEVICE", devnam);
374 * Initialize system-dependent stuff and magic number package.
379 setlogmask(LOG_UPTO(LOG_DEBUG));
382 * Detach ourselves from the terminal, if required,
383 * and identify who is running us.
385 if (!nodetach && !updetach)
390 if (pw != NULL && pw->pw_name != NULL)
395 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
396 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
397 script_setenv("PPPLOGNAME", p);
400 * Compute mask of all interesting signals and install signal handlers
401 * for each. Only one signal handler may be active at a time. Therefore,
402 * all other signals should be masked when any handler is executing.
405 sigaddset(&mask, SIGHUP);
406 sigaddset(&mask, SIGINT);
407 sigaddset(&mask, SIGTERM);
408 sigaddset(&mask, SIGCHLD);
409 sigaddset(&mask, SIGUSR2);
411 #define SIGNAL(s, handler) do { \
412 sa.sa_handler = handler; \
413 if (sigaction(s, &sa, NULL) < 0) \
414 fatal("Couldn't establish signal handler (%d): %m", s); \
419 SIGNAL(SIGHUP, hup); /* Hangup */
420 SIGNAL(SIGINT, term); /* Interrupt */
421 SIGNAL(SIGTERM, term); /* Terminate */
422 SIGNAL(SIGCHLD, chld);
424 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
425 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
428 * Install a handler for other signals which would otherwise
429 * cause pppd to exit without cleaning up.
431 SIGNAL(SIGABRT, bad_signal);
432 SIGNAL(SIGALRM, bad_signal);
433 SIGNAL(SIGFPE, bad_signal);
434 SIGNAL(SIGILL, bad_signal);
435 SIGNAL(SIGPIPE, bad_signal);
436 SIGNAL(SIGQUIT, bad_signal);
437 SIGNAL(SIGSEGV, bad_signal);
439 SIGNAL(SIGBUS, bad_signal);
442 SIGNAL(SIGEMT, bad_signal);
445 SIGNAL(SIGPOLL, bad_signal);
448 SIGNAL(SIGPROF, bad_signal);
451 SIGNAL(SIGSYS, bad_signal);
454 SIGNAL(SIGTRAP, bad_signal);
457 SIGNAL(SIGVTALRM, bad_signal);
460 SIGNAL(SIGXCPU, bad_signal);
463 SIGNAL(SIGXFSZ, bad_signal);
467 * Apparently we can get a SIGPIPE when we call syslog, if
468 * syslogd has died and been restarted. Ignoring it seems
471 signal(SIGPIPE, SIG_IGN);
476 * If we're doing dial-on-demand, set up the interface now.
480 * Open the loopback channel and set it up to be the ppp interface.
482 fd_loop = open_ppp_loopback();
484 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
485 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
486 script_setenv("IFNAME", ifname);
488 create_pidfile(); /* write pid to file */
491 * Configure the interface and mark it up, etc.
506 * Don't do anything until we see some activity.
509 phase = PHASE_DORMANT;
513 if (sigsetjmp(sigjmp, 1) == 0) {
514 sigprocmask(SIG_BLOCK, &mask, NULL);
515 if (kill_link || got_sigchld) {
516 sigprocmask(SIG_UNBLOCK, &mask, NULL);
519 sigprocmask(SIG_UNBLOCK, &mask, NULL);
520 wait_input(timeleft(&timo));
530 if (get_loop_output())
536 if (kill_link && !persist)
540 * Now we want to bring up the link.
543 info("Starting link");
546 phase = PHASE_SERIALCONN;
549 * Get a pty master/slave pair if the pty, notty, or record
550 * options were specified.
552 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
555 if (ptycommand != NULL || notty || record_file != NULL) {
556 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
557 error("Couldn't allocate pseudo-tty");
558 status = EXIT_FATAL_ERROR;
561 set_up_tty(pty_slave, 1);
565 * Lock the device if we've been asked to.
567 status = EXIT_LOCK_FAILED;
568 if (lockflag && !privopen) {
569 if (lock(devnam) < 0)
575 * Open the serial device and set it up to be the ppp interface.
576 * First we open it in non-blocking mode so we can set the
577 * various termios flags appropriately. If we aren't dialling
578 * out and we want to use the modem lines, we reopen it later
579 * in order to wait for the carrier detect signal from the modem.
583 if (devnam[0] != 0) {
585 /* If the user specified the device name, become the
586 user before opening it. */
588 if (!devnam_info.priv && !privopen)
590 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
592 if (!devnam_info.priv && !privopen)
598 error("Failed to open %s: %m", devnam);
599 status = EXIT_OPEN_FAILED;
601 if (!persist || err != EINTR)
604 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
605 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
606 warn("Couldn't reset non-blocking mode on device: %m");
609 * Do the equivalent of `mesg n' to stop broadcast messages.
611 if (fstat(ttyfd, &statbuf) < 0
612 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
613 warn("Couldn't restrict write permissions to %s: %m", devnam);
615 tty_mode = statbuf.st_mode;
618 * Set line speed, flow control, etc.
619 * If we have a non-null connection or initializer script,
620 * on most systems we set CLOCAL for now so that we can talk
621 * to the modem before carrier comes up. But this has the
622 * side effect that we might miss it if CD drops before we
623 * get to clear CLOCAL below. On systems where we can talk
624 * successfully to the modem with CLOCAL clear and CD down,
625 * we could clear CLOCAL at this point.
627 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
628 || initializer != NULL));
633 * If the notty and/or record option was specified,
634 * start up the character shunt now.
636 status = EXIT_PTYCMD_FAILED;
637 if (ptycommand != NULL) {
638 if (record_file != NULL) {
639 int ipipe[2], opipe[2], ok;
641 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
642 fatal("Couldn't create pipes for record option: %m");
643 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
644 && start_charshunt(ipipe[0], opipe[1]);
652 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
659 if (!start_charshunt(0, 1))
661 } else if (record_file != NULL) {
662 if (!start_charshunt(ttyfd, ttyfd))
666 /* run connection script */
667 if ((connector && connector[0]) || initializer) {
668 if (real_ttyfd != -1) {
669 if (!default_device && modem) {
670 setdtr(real_ttyfd, 0); /* in case modem is off hook */
672 setdtr(real_ttyfd, 1);
676 if (initializer && initializer[0]) {
677 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
678 error("Initializer script failed");
679 status = EXIT_INIT_FAILED;
685 info("Serial port initialized.");
688 if (connector && connector[0]) {
689 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
690 error("Connect script failed");
691 status = EXIT_CONNECT_FAILED;
697 info("Serial connection established.");
700 /* set line speed, flow control, etc.;
701 clear CLOCAL if modem option */
702 if (real_ttyfd != -1)
703 set_up_tty(real_ttyfd, 0);
706 /* reopen tty if necessary to wait for carrier */
707 if (connector == NULL && modem && devnam[0] != 0) {
709 if ((i = open(devnam, O_RDWR)) >= 0)
711 if (errno != EINTR) {
712 error("Failed to reopen %s: %m", devnam);
713 status = EXIT_OPEN_FAILED;
715 if (!persist || errno != EINTR || hungup || kill_link)
721 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
722 script_setenv("SPEED", numbuf);
724 /* run welcome script, if any */
725 if (welcomer && welcomer[0]) {
726 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
727 warn("Welcome script failed");
730 /* set up the serial device as a ppp interface */
731 fd_ppp = establish_ppp(ttyfd);
733 status = EXIT_FATAL_ERROR;
739 info("Using interface ppp%d", ifunit);
740 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
741 script_setenv("IFNAME", ifname);
743 create_pidfile(); /* write pid to file */
747 * Start opening the connection and wait for
748 * incoming events (reply, timeout, etc.).
750 notice("Connect: %s <--> %s", ifname, ppp_devnam);
751 gettimeofday(&start_time, NULL);
752 link_stats_valid = 0;
753 script_unsetenv("CONNECT_TIME");
754 script_unsetenv("BYTES_SENT");
755 script_unsetenv("BYTES_RCVD");
759 * If we are initiating this connection, wait for a short
760 * time for something from the peer. This can avoid bouncing
761 * our packets off his tty before he has it set up.
763 if (connector != NULL || ptycommand != NULL) {
770 lcp_open(0); /* Start protocol */
773 status = EXIT_NEGOTIATION_FAILED;
774 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
775 if (sigsetjmp(sigjmp, 1) == 0) {
776 sigprocmask(SIG_BLOCK, &mask, NULL);
777 if (kill_link || open_ccp_flag || got_sigchld) {
778 sigprocmask(SIG_UNBLOCK, &mask, NULL);
781 sigprocmask(SIG_UNBLOCK, &mask, NULL);
782 wait_input(timeleft(&timo));
789 lcp_close(0, "User request");
793 if (phase == PHASE_NETWORK) {
794 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
795 (*ccp_protent.open)(0);
800 reap_kids(0); /* Don't leave dead kids lying around */
804 * Print connect time and statistics.
806 if (link_stats_valid) {
807 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
808 info("Connect time %d.%d minutes.", t/10, t%10);
809 info("Sent %d bytes, received %d bytes.",
810 link_stats.bytes_out, link_stats.bytes_in);
814 * If we may want to bring the link up again, transfer
815 * the ppp unit back to the loopback. Set the
816 * real serial device back to its normal mode of operation.
822 disestablish_ppp(ttyfd);
828 * Run disconnector script, if requested.
829 * XXX we may not be able to do this if the line has hung up!
832 if (disconnector && !hungup) {
834 set_up_tty(real_ttyfd, 1);
835 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
836 warn("disconnect script failed");
838 info("Serial link disconnected.");
855 if (pidfilename[0] != 0
856 && unlink(pidfilename) < 0 && errno != ENOENT)
857 warn("unable to delete pid file: %m");
861 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
867 if (holdoff > 0 && need_holdoff) {
868 phase = PHASE_HOLDOFF;
869 TIMEOUT(holdoff_end, NULL, holdoff);
871 if (sigsetjmp(sigjmp, 1) == 0) {
872 sigprocmask(SIG_BLOCK, &mask, NULL);
873 if (kill_link || got_sigchld) {
874 sigprocmask(SIG_UNBLOCK, &mask, NULL);
877 sigprocmask(SIG_UNBLOCK, &mask, NULL);
878 wait_input(timeleft(&timo));
885 phase = PHASE_DORMANT; /* allow signal to end holdoff */
889 } while (phase == PHASE_HOLDOFF);
895 /* Wait for scripts to finish */
896 /* XXX should have a timeout here */
897 while (n_children > 0) {
899 struct subprocess *chp;
900 dbglog("Waiting for %d child processes...", n_children);
901 for (chp = children; chp != NULL; chp = chp->next)
902 dbglog(" script %s, pid %d", chp->prog, chp->pid);
912 * detach - detach us from the controlling terminal.
921 if ((pid = fork()) < 0) {
922 error("Couldn't detach (fork failed: %m)");
923 die(1); /* or just return? */
929 exit(0); /* parent dies */
938 /* update pid file if it has been written already */
944 * reopen_log - (re)open our connection to syslog.
950 openlog("pppd", LOG_PID);
952 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
953 setlogmask(LOG_UPTO(LOG_INFO));
958 * Create a file containing our process ID.
966 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
967 _PATH_VARRUN, ifname);
968 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
969 fprintf(pidfile, "%d\n", getpid());
970 (void) fclose(pidfile);
972 error("Failed to create pid file %s: %m", pidfilename);
975 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
976 script_setenv("PPPD_PID", numbuf);
980 * holdoff_end - called via a timeout when the holdoff period ends.
986 phase = PHASE_DORMANT;
990 * get_input - called when incoming data is available.
998 struct protent *protp;
1000 p = inpacket_buf; /* point to beginning of packet buffer */
1002 len = read_packet(inpacket_buf);
1007 notice("Modem hangup");
1009 status = EXIT_HANGUP;
1010 lcp_lowerdown(0); /* serial link is no longer available */
1015 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1016 dbglog("rcvd %P", p, len);
1018 if (len < PPP_HDRLEN) {
1019 MAINDEBUG(("io(): Received short packet."));
1023 p += 2; /* Skip address and control */
1024 GETSHORT(protocol, p);
1028 * Toss all non-LCP packets unless LCP is OPEN.
1030 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1031 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1036 * Until we get past the authentication phase, toss all packets
1037 * except LCP, LQR and authentication packets.
1039 if (phase <= PHASE_AUTHENTICATE
1040 && !(protocol == PPP_LCP || protocol == PPP_LQR
1041 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1042 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1048 * Upcall the proper protocol input routine.
1050 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1051 if (protp->protocol == protocol && protp->enabled_flag) {
1052 (*protp->input)(0, p, len);
1055 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1056 && protp->datainput != NULL) {
1057 (*protp->datainput)(0, p, len);
1063 warn("Unsupported protocol (0x%x) received", protocol);
1064 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1069 * die - clean up state and exit with the specified status.
1076 syslog(LOG_INFO, "Exit.");
1081 * cleanup - restore anything which needs to be restored before we exit
1090 disestablish_ppp(ttyfd);
1091 if (real_ttyfd >= 0)
1094 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1095 warn("unable to delete pid file: %m");
1103 * close_tty - restore the terminal device and close it.
1108 /* drop dtr to hang up */
1109 if (!default_device && modem) {
1110 setdtr(real_ttyfd, 0);
1112 * This sleep is in case the serial port has CLOCAL set by default,
1113 * and consequently will reassert DTR when we close the device.
1118 restore_tty(real_ttyfd);
1120 if (tty_mode != (mode_t) -1) {
1121 if (fchmod(real_ttyfd, tty_mode) != 0) {
1122 /* XXX if devnam is a symlink, this will change the link */
1123 chmod(devnam, tty_mode);
1132 * update_link_stats - get stats at link termination.
1135 update_link_stats(u)
1141 if (!get_ppp_stats(u, &link_stats)
1142 || gettimeofday(&now, NULL) < 0)
1144 link_connect_time = now.tv_sec - start_time.tv_sec;
1145 link_stats_valid = 1;
1147 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1148 script_setenv("CONNECT_TIME", numbuf);
1149 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1150 script_setenv("BYTES_SENT", numbuf);
1151 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1152 script_setenv("BYTES_RCVD", numbuf);
1157 struct timeval c_time; /* time at which to call routine */
1158 void *c_arg; /* argument to routine */
1159 void (*c_func) __P((void *)); /* routine */
1160 struct callout *c_next;
1163 static struct callout *callout = NULL; /* Callout list */
1164 static struct timeval timenow; /* Current time */
1167 * timeout - Schedule a timeout.
1169 * Note that this timeout takes the number of seconds, NOT hz (as in
1173 timeout(func, arg, time)
1174 void (*func) __P((void *));
1178 struct callout *newp, *p, **pp;
1180 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1185 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1186 fatal("Out of memory in timeout()!");
1188 newp->c_func = func;
1189 gettimeofday(&timenow, NULL);
1190 newp->c_time.tv_sec = timenow.tv_sec + time;
1191 newp->c_time.tv_usec = timenow.tv_usec;
1194 * Find correct place and link it in.
1196 for (pp = &callout; (p = *pp); pp = &p->c_next)
1197 if (newp->c_time.tv_sec < p->c_time.tv_sec
1198 || (newp->c_time.tv_sec == p->c_time.tv_sec
1199 && newp->c_time.tv_usec < p->c_time.tv_usec))
1207 * untimeout - Unschedule a timeout.
1210 untimeout(func, arg)
1211 void (*func) __P((void *));
1214 struct callout **copp, *freep;
1216 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1219 * Find first matching timeout and remove it from the list.
1221 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1222 if (freep->c_func == func && freep->c_arg == arg) {
1223 *copp = freep->c_next;
1224 (void) free((char *) freep);
1231 * calltimeout - Call any timeout routines which are now due.
1238 while (callout != NULL) {
1241 if (gettimeofday(&timenow, NULL) < 0)
1242 fatal("Failed to get time of day: %m");
1243 if (!(p->c_time.tv_sec < timenow.tv_sec
1244 || (p->c_time.tv_sec == timenow.tv_sec
1245 && p->c_time.tv_usec <= timenow.tv_usec)))
1246 break; /* no, it's not time yet */
1248 callout = p->c_next;
1249 (*p->c_func)(p->c_arg);
1257 * timeleft - return the length of time until the next timeout is due.
1259 static struct timeval *
1261 struct timeval *tvp;
1263 if (callout == NULL)
1266 gettimeofday(&timenow, NULL);
1267 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1268 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1269 if (tvp->tv_usec < 0) {
1270 tvp->tv_usec += 1000000;
1273 if (tvp->tv_sec < 0)
1274 tvp->tv_sec = tvp->tv_usec = 0;
1281 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1287 struct sigaction act, oldact;
1289 act.sa_handler = SIG_IGN;
1292 sigaction(sig, &act, &oldact);
1293 sigaction(sig, &oldact, NULL);
1298 * hup - Catch SIGHUP signal.
1300 * Indicates that the physical layer has been disconnected.
1301 * We don't rely on this indication; if the user has sent this
1302 * signal, we just take the link down.
1308 info("Hangup (SIGHUP)");
1310 if (status != EXIT_HANGUP)
1311 status = EXIT_USER_REQUEST;
1313 /* Send the signal to the [dis]connector process(es) also */
1316 kill(charshunt_pid, sig);
1318 siglongjmp(sigjmp, 1);
1323 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1325 * Indicates that we should initiate a graceful disconnect and exit.
1332 info("Terminating on signal %d.", sig);
1333 persist = 0; /* don't try to restart */
1335 status = EXIT_USER_REQUEST;
1337 /* Send the signal to the [dis]connector process(es) also */
1340 kill(charshunt_pid, sig);
1342 siglongjmp(sigjmp, 1);
1347 * chld - Catch SIGCHLD signal.
1348 * Sets a flag so we will call reap_kids in the mainline.
1356 siglongjmp(sigjmp, 1);
1361 * toggle_debug - Catch SIGUSR1 signal.
1363 * Toggle debug flag.
1372 setlogmask(LOG_UPTO(LOG_DEBUG));
1374 setlogmask(LOG_UPTO(LOG_WARNING));
1380 * open_ccp - Catch SIGUSR2 signal.
1382 * Try to (re)negotiate compression.
1391 siglongjmp(sigjmp, 1);
1396 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1402 static int crashed = 0;
1407 error("Fatal signal %d", sig);
1409 kill_my_pg(SIGTERM);
1411 kill(charshunt_pid, SIGTERM);
1417 * device_script - run a program to talk to the serial device
1418 * (e.g. to run the connector or disconnector script).
1421 device_script(program, in, out, dont_wait)
1435 error("Failed to create child process: %m");
1444 int newin = dup(in);
1448 } else if (out == 2) {
1451 if (log_to_fd >= 0) {
1456 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1457 if (errfd >= 0 && errfd != 2) {
1477 if (getuid() != uid) {
1478 error("setuid failed");
1482 execl("/bin/sh", "sh", "-c", program, (char *)0);
1483 error("could not exec /bin/sh: %m");
1489 record_child(pid, program, NULL, NULL);
1492 while (waitpid(pid, &status, 0) < 0) {
1495 fatal("error waiting for (dis)connection process: %m");
1500 return (status == 0 ? 0 : -1);
1505 * run-program - execute a program with given arguments,
1506 * but don't wait for it.
1507 * If the program can't be executed, logs an error unless
1508 * must_exist is 0 and the program file doesn't exist.
1509 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1510 * or isn't an executable plain file, or the process ID of the child.
1511 * If done != NULL, (*done)(arg) will be called later (within
1512 * reap_kids) iff the return value is > 0.
1515 run_program(prog, args, must_exist, done, arg)
1519 void (*done) __P((void *));
1526 * First check if the file exists and is executable.
1527 * We don't use access() because that would use the
1528 * real user-id, which might not be root, and the script
1529 * might be accessible only to root.
1532 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1533 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1534 if (must_exist || errno != ENOENT)
1535 warn("Can't execute %s: %m", prog);
1541 error("Failed to create child process for %s: %m", prog);
1547 /* Leave the current location */
1548 (void) setsid(); /* No controlling tty. */
1549 (void) umask (S_IRWXG|S_IRWXO);
1550 (void) chdir ("/"); /* no current directory. */
1551 setuid(0); /* set real UID = root */
1554 /* Ensure that nothing of our device environment is inherited. */
1560 close (ttyfd); /* tty interface to the ppp device */
1561 if (real_ttyfd >= 0)
1564 /* Don't pass handles to the PPP device, even by accident. */
1565 new_fd = open (_PATH_DEVNULL, O_RDWR);
1568 dup2 (new_fd, 0); /* stdin <- /dev/null */
1571 dup2 (0, 1); /* stdout -> /dev/null */
1572 dup2 (0, 2); /* stderr -> /dev/null */
1576 /* Force the priority back to zero if pppd is running higher. */
1577 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1578 warn("can't reset priority to 0: %m");
1581 /* SysV recommends a second fork at this point. */
1583 /* run the program */
1584 execve(prog, args, script_env);
1585 if (must_exist || errno != ENOENT) {
1586 /* have to reopen the log, there's nowhere else
1587 for the message to go. */
1589 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1596 dbglog("Script %s started (pid %d)", prog, pid);
1597 record_child(pid, prog, done, arg);
1604 * record_child - add a child process to the list for reap_kids
1608 record_child(pid, prog, done, arg)
1611 void (*done) __P((void *));
1614 struct subprocess *chp;
1618 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1620 warn("losing track of %s process", prog);
1626 chp->next = children;
1633 * reap_kids - get status from any dead child processes,
1634 * and log a message for abnormal terminations.
1641 struct subprocess *chp, **prevp;
1644 if (n_children == 0)
1646 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1649 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1650 if (chp->pid == pid) {
1655 if (WIFSIGNALED(status)) {
1656 warn("Child process %s (pid %d) terminated with signal %d",
1657 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1659 dbglog("Script %s finished (pid %d), status = 0x%x",
1660 (chp? chp->prog: "??"), pid, status);
1661 if (chp && chp->done)
1662 (*chp->done)(chp->arg);
1666 if (pid == -1 && errno != ECHILD && errno != EINTR)
1667 error("Error waiting for child process: %m");
1672 * novm - log an error message saying we ran out of memory, and die.
1678 fatal("Virtual memory exhausted allocating %s\n", msg);
1682 * script_setenv - set an environment variable value to be used
1683 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1686 script_setenv(var, value)
1689 size_t vl = strlen(var) + strlen(value) + 2;
1691 char *p, *newstring;
1693 newstring = (char *) malloc(vl);
1696 slprintf(newstring, vl, "%s=%s", var, value);
1698 /* check if this variable is already set */
1699 if (script_env != 0) {
1700 for (i = 0; (p = script_env[i]) != 0; ++i) {
1701 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1703 script_env[i] = newstring;
1709 script_env = (char **) malloc(16 * sizeof(char *));
1710 if (script_env == 0)
1715 /* reallocate script_env with more space if needed */
1716 if (i + 1 >= s_env_nalloc) {
1718 char **newenv = (char **) realloc((void *)script_env,
1719 new_n * sizeof(char *));
1722 script_env = newenv;
1723 s_env_nalloc = new_n;
1726 script_env[i] = newstring;
1727 script_env[i+1] = 0;
1731 * script_unsetenv - remove a variable from the environment
1735 script_unsetenv(var)
1738 int vl = strlen(var);
1742 if (script_env == 0)
1744 for (i = 0; (p = script_env[i]) != 0; ++i) {
1745 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1747 while ((script_env[i] = script_env[i+1]) != 0)
1755 * start_charshunt - create a child process to run the character shunt.
1758 start_charshunt(ifd, ofd)
1765 error("Can't fork process for character shunt: %m");
1772 if (getuid() != uid)
1773 fatal("setuid failed");
1777 charshunt(ifd, ofd, record_file);
1780 charshunt_pid = cpid;
1784 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1796 * charshunt - the character shunt, which passes characters between
1797 * the pty master side and the serial port (or stdin/stdout).
1798 * This runs as the user (not as root).
1799 * (We assume ofd >= ifd which is true the way this gets called. :-).
1802 charshunt(ifd, ofd, record_file)
1807 fd_set ready, writey;
1808 u_char *ibufp, *obufp;
1811 int pty_readable, stdin_readable;
1812 struct timeval lasttime;
1813 FILE *recordf = NULL;
1816 * Reset signal handlers.
1818 signal(SIGHUP, SIG_IGN); /* Hangup */
1819 signal(SIGINT, SIG_DFL); /* Interrupt */
1820 signal(SIGTERM, SIG_DFL); /* Terminate */
1821 signal(SIGCHLD, SIG_DFL);
1822 signal(SIGUSR1, SIG_DFL);
1823 signal(SIGUSR2, SIG_DFL);
1824 signal(SIGABRT, SIG_DFL);
1825 signal(SIGALRM, SIG_DFL);
1826 signal(SIGFPE, SIG_DFL);
1827 signal(SIGILL, SIG_DFL);
1828 signal(SIGPIPE, SIG_DFL);
1829 signal(SIGQUIT, SIG_DFL);
1830 signal(SIGSEGV, SIG_DFL);
1832 signal(SIGBUS, SIG_DFL);
1835 signal(SIGEMT, SIG_DFL);
1838 signal(SIGPOLL, SIG_DFL);
1841 signal(SIGPROF, SIG_DFL);
1844 signal(SIGSYS, SIG_DFL);
1847 signal(SIGTRAP, SIG_DFL);
1850 signal(SIGVTALRM, SIG_DFL);
1853 signal(SIGXCPU, SIG_DFL);
1856 signal(SIGXFSZ, SIG_DFL);
1860 * Open the record file if required.
1862 if (record_file != NULL) {
1863 recordf = fopen(record_file, "a");
1864 if (recordf == NULL)
1865 error("Couldn't create record file %s: %m", record_file);
1868 /* set all the fds to non-blocking mode */
1869 flags = fcntl(pty_master, F_GETFL);
1871 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1872 warn("couldn't set pty master to nonblock: %m");
1873 flags = fcntl(ifd, F_GETFL);
1875 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1876 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1878 flags = fcntl(ofd, F_GETFL);
1880 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1881 warn("couldn't set stdout to nonblock: %m");
1885 ibufp = obufp = NULL;
1886 pty_readable = stdin_readable = 1;
1887 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1888 if (recordf != NULL) {
1889 gettimeofday(&lasttime, NULL);
1890 putc(7, recordf); /* put start marker */
1891 putc(lasttime.tv_sec >> 24, recordf);
1892 putc(lasttime.tv_sec >> 16, recordf);
1893 putc(lasttime.tv_sec >> 8, recordf);
1894 putc(lasttime.tv_sec, recordf);
1895 lasttime.tv_usec = 0;
1898 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1902 FD_SET(pty_master, &writey);
1903 else if (stdin_readable)
1904 FD_SET(ifd, &ready);
1906 FD_SET(ofd, &writey);
1907 else if (pty_readable)
1908 FD_SET(pty_master, &ready);
1909 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1914 if (FD_ISSET(ifd, &ready)) {
1915 ibufp = inpacket_buf;
1916 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1917 if (nibuf < 0 && errno == EIO)
1920 if (!(errno == EINTR || errno == EAGAIN)) {
1921 error("Error reading standard input: %m");
1925 } else if (nibuf == 0) {
1926 /* end of file from stdin */
1928 /* do a 0-length write, hopefully this will generate
1929 an EOF (hangup) on the slave side. */
1930 write(pty_master, inpacket_buf, 0);
1932 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1935 FD_SET(pty_master, &writey);
1937 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1941 if (FD_ISSET(pty_master, &ready)) {
1942 obufp = outpacket_buf;
1943 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1944 if (nobuf < 0 && errno == EIO)
1947 if (!(errno == EINTR || errno == EAGAIN)) {
1948 error("Error reading pseudo-tty master: %m");
1952 } else if (nobuf == 0) {
1953 /* end of file from the pty - slave side has closed */
1955 stdin_readable = 0; /* pty is not writable now */
1959 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1962 FD_SET(ofd, &writey);
1964 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1968 if (FD_ISSET(ofd, &writey)) {
1969 n = write(ofd, obufp, nobuf);
1972 error("Error writing standard output: %m");
1982 if (FD_ISSET(pty_master, &writey)) {
1983 n = write(pty_master, ibufp, nibuf);
1986 error("Error writing pseudo-tty master: %m");
2001 record_write(f, code, buf, nb, tp)
2011 gettimeofday(&now, NULL);
2012 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2013 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2017 putc(diff >> 24, f);
2018 putc(diff >> 16, f);
2031 fwrite(buf, nb, 1, f);
2035 error("Error writing record file: %m");