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.80 1999/07/21 00:24: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"
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 */
91 static int fd_ppp = -1; /* fd for talking PPP */
92 static int fd_loop; /* fd for getting demand-dial packets */
93 static int pty_master; /* fd for master side of pty */
94 static int pty_slave; /* fd for slave side of pty */
95 static int real_ttyfd; /* fd for actual serial port (not pty) */
97 int phase; /* where the link is at */
102 static sigjmp_buf sigjmp;
104 char **script_env; /* Env. variable values for scripts */
105 int s_env_nalloc; /* # words avail at script_env */
107 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
108 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
110 static int n_children; /* # child processes still running */
111 static int got_sigchld; /* set if we have received a SIGCHLD */
113 static int locked; /* lock() has succeeded */
114 static int privopen; /* don't lock, open device as root */
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_connect_time;
125 int link_stats_valid;
127 static int charshunt_pid; /* Process ID for charshunt */
130 * We maintain a list of child process pids and
131 * functions to call when they exit.
136 void (*done) __P((void *));
138 struct subprocess *next;
141 static struct subprocess *children;
143 /* Prototypes for procedures local to this file. */
145 static void create_pidfile __P((void));
146 static void cleanup __P((void));
147 static void close_tty __P((void));
148 static void get_input __P((void));
149 static void calltimeout __P((void));
150 static struct timeval *timeleft __P((struct timeval *));
151 static void kill_my_pg __P((int));
152 static void hup __P((int));
153 static void term __P((int));
154 static void chld __P((int));
155 static void toggle_debug __P((int));
156 static void open_ccp __P((int));
157 static void bad_signal __P((int));
158 static void holdoff_end __P((void *));
159 static int device_script __P((char *, int, int, int));
160 static void reap_kids __P((int waitfor));
161 static void record_child __P((int, char *, void (*) (void *), void *));
162 static int start_charshunt __P((int, int));
163 static void charshunt_done __P((void *));
164 static void charshunt __P((int, int, char *));
165 static int record_write __P((FILE *, int code, u_char *buf, int nb,
168 extern char *ttyname __P((int));
169 extern char *getlogin __P((void));
170 int main __P((int, char *[]));
174 #define O_NONBLOCK O_NDELAY
178 #define setlogmask(x)
182 * PPP Data Link Layer "protocol" table.
183 * One entry per supported protocol.
184 * The last entry must be NULL.
186 struct protent *protocols[] = {
215 struct protent *protp;
219 phase = PHASE_INITIALIZE;
222 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
223 * This way we can close 0, 1, 2 in detach() without clobbering
224 * a fd that we are using.
226 if ((i = open("/dev/null", O_RDWR)) >= 0) {
227 while (0 <= i && i <= 2)
235 /* Initialize syslog facilities */
238 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
239 option_error("Couldn't get hostname: %m");
242 hostname[MAXNAMELEN-1] = 0;
245 privileged = uid == 0;
246 slprintf(numbuf, sizeof(numbuf), "%d", uid);
247 script_setenv("ORIG_UID", numbuf);
249 ngroups = getgroups(NGROUPS_MAX, groups);
252 * Initialize to the standard option set, then parse, in order,
253 * the system options file, the user's options file,
254 * the tty's options file, and the command line arguments.
256 for (i = 0; (protp = protocols[i]) != NULL; ++i)
262 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
263 || !options_from_user())
264 exit(EXIT_OPTION_ERROR);
266 /* scan command line and options files to find device name */
268 parse_args(argc-1, argv+1);
272 * Work out the device name, if it hasn't already been specified.
274 using_pty = notty || ptycommand != NULL;
275 if (!using_pty && default_device) {
277 if (!isatty(0) || (p = ttyname(0)) == NULL) {
278 option_error("no device specified and stdin is not a tty");
279 exit(EXIT_OPTION_ERROR);
281 strlcpy(devnam, p, sizeof(devnam));
282 if (stat(devnam, &devstat) < 0)
283 fatal("Couldn't stat default device %s: %m", devnam);
287 * Parse the tty options file and the command line.
288 * The per-tty options file should not change
289 * ptycommand, notty or devnam.
293 if (!options_for_tty())
294 exit(EXIT_OPTION_ERROR);
298 if (!parse_args(argc-1, argv+1))
299 exit(EXIT_OPTION_ERROR);
302 * Check that we are running as root.
304 if (geteuid() != 0) {
305 option_error("must be root to run %s, since it is not setuid-root",
310 if (!ppp_available()) {
311 option_error(no_ppp_msg);
312 exit(EXIT_NO_KERNEL_SUPPORT);
316 * Check that the options given are valid and consistent.
318 if (!sys_check_options())
319 exit(EXIT_OPTION_ERROR);
320 auth_check_options();
321 for (i = 0; (protp = protocols[i]) != NULL; ++i)
322 if (protp->check_options != NULL)
323 (*protp->check_options)();
324 if (demand && connector == 0) {
325 option_error("connect script is required for demand-dialling\n");
326 exit(EXIT_OPTION_ERROR);
330 if (!default_device) {
331 option_error("%s option precludes specifying device name",
332 notty? "notty": "pty");
333 exit(EXIT_OPTION_ERROR);
335 if (ptycommand != NULL && notty) {
336 option_error("pty option is incompatible with notty option");
337 exit(EXIT_OPTION_ERROR);
339 default_device = notty;
342 if (notty && log_to_fd <= 1)
346 * If the user has specified a device which is the same as
347 * the one on stdin, pretend they didn't specify any.
348 * If the device is already open read/write on stdin,
349 * we assume we don't need to lock it, and we can open it as root.
351 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
352 && statbuf.st_rdev == devstat.st_rdev) {
354 fdflags = fcntl(0, F_GETFL);
355 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
363 * Don't send log messages to the serial port, it tends to
364 * confuse the peer. :-)
366 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
367 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
370 script_setenv("DEVICE", devnam);
373 * Initialize system-dependent stuff and magic number package.
378 setlogmask(LOG_UPTO(LOG_DEBUG));
381 * Detach ourselves from the terminal, if required,
382 * and identify who is running us.
384 if (!nodetach && !updetach)
389 if (pw != NULL && pw->pw_name != NULL)
394 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
395 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
396 script_setenv("PPPLOGNAME", p);
399 * Compute mask of all interesting signals and install signal handlers
400 * for each. Only one signal handler may be active at a time. Therefore,
401 * all other signals should be masked when any handler is executing.
404 sigaddset(&mask, SIGHUP);
405 sigaddset(&mask, SIGINT);
406 sigaddset(&mask, SIGTERM);
407 sigaddset(&mask, SIGCHLD);
408 sigaddset(&mask, SIGUSR2);
410 #define SIGNAL(s, handler) do { \
411 sa.sa_handler = handler; \
412 if (sigaction(s, &sa, NULL) < 0) \
413 fatal("Couldn't establish signal handler (%d): %m", s); \
418 SIGNAL(SIGHUP, hup); /* Hangup */
419 SIGNAL(SIGINT, term); /* Interrupt */
420 SIGNAL(SIGTERM, term); /* Terminate */
421 SIGNAL(SIGCHLD, chld);
423 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
424 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
427 * Install a handler for other signals which would otherwise
428 * cause pppd to exit without cleaning up.
430 SIGNAL(SIGABRT, bad_signal);
431 SIGNAL(SIGALRM, bad_signal);
432 SIGNAL(SIGFPE, bad_signal);
433 SIGNAL(SIGILL, bad_signal);
434 SIGNAL(SIGPIPE, bad_signal);
435 SIGNAL(SIGQUIT, bad_signal);
436 SIGNAL(SIGSEGV, bad_signal);
438 SIGNAL(SIGBUS, bad_signal);
441 SIGNAL(SIGEMT, bad_signal);
444 SIGNAL(SIGPOLL, bad_signal);
447 SIGNAL(SIGPROF, bad_signal);
450 SIGNAL(SIGSYS, bad_signal);
453 SIGNAL(SIGTRAP, bad_signal);
456 SIGNAL(SIGVTALRM, bad_signal);
459 SIGNAL(SIGXCPU, bad_signal);
462 SIGNAL(SIGXFSZ, bad_signal);
466 * Apparently we can get a SIGPIPE when we call syslog, if
467 * syslogd has died and been restarted. Ignoring it seems
470 signal(SIGPIPE, SIG_IGN);
475 * If we're doing dial-on-demand, set up the interface now.
479 * Open the loopback channel and set it up to be the ppp interface.
481 fd_loop = open_ppp_loopback();
483 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
484 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
485 script_setenv("IFNAME", ifname);
487 create_pidfile(); /* write pid to file */
490 * Configure the interface and mark it up, etc.
504 * Don't do anything until we see some activity.
507 phase = PHASE_DORMANT;
511 if (sigsetjmp(sigjmp, 1) == 0) {
512 sigprocmask(SIG_BLOCK, &mask, NULL);
513 if (kill_link || got_sigchld) {
514 sigprocmask(SIG_UNBLOCK, &mask, NULL);
517 sigprocmask(SIG_UNBLOCK, &mask, NULL);
518 wait_input(timeleft(&timo));
528 if (get_loop_output())
534 if (kill_link && !persist)
538 * Now we want to bring up the link.
541 info("Starting link");
544 phase = PHASE_SERIALCONN;
547 * Get a pty master/slave pair if the pty, notty, or record
548 * options were specified.
550 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
553 if (ptycommand != NULL || notty || record_file != NULL) {
554 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
555 error("Couldn't allocate pseudo-tty");
556 status = EXIT_FATAL_ERROR;
559 set_up_tty(pty_slave, 1);
563 * Lock the device if we've been asked to.
565 status = EXIT_LOCK_FAILED;
566 if (lockflag && !privopen) {
567 if (lock(devnam) < 0)
573 * Open the serial device and set it up to be the ppp interface.
574 * First we open it in non-blocking mode so we can set the
575 * various termios flags appropriately. If we aren't dialling
576 * out and we want to use the modem lines, we reopen it later
577 * in order to wait for the carrier detect signal from the modem.
581 if (devnam[0] != 0) {
583 /* If the user specified the device name, become the
584 user before opening it. */
586 if (!devnam_info.priv && !privopen)
588 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
590 if (!devnam_info.priv && !privopen)
596 error("Failed to open %s: %m", devnam);
597 status = EXIT_OPEN_FAILED;
599 if (!persist || err != EINTR)
602 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
603 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
604 warn("Couldn't reset non-blocking mode on device: %m");
607 * Do the equivalent of `mesg n' to stop broadcast messages.
609 if (fstat(ttyfd, &statbuf) < 0
610 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
611 warn("Couldn't restrict write permissions to %s: %m", devnam);
613 tty_mode = statbuf.st_mode;
616 * Set line speed, flow control, etc.
617 * If we have a non-null connection or initializer script,
618 * on most systems we set CLOCAL for now so that we can talk
619 * to the modem before carrier comes up. But this has the
620 * side effect that we might miss it if CD drops before we
621 * get to clear CLOCAL below. On systems where we can talk
622 * successfully to the modem with CLOCAL clear and CD down,
623 * we could clear CLOCAL at this point.
625 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
626 || initializer != NULL));
631 * If the notty and/or record option was specified,
632 * start up the character shunt now.
634 status = EXIT_PTYCMD_FAILED;
635 if (ptycommand != NULL) {
636 if (record_file != NULL) {
637 int ipipe[2], opipe[2], ok;
639 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
640 fatal("Couldn't create pipes for record option: %m");
641 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
642 && start_charshunt(ipipe[0], opipe[1]);
650 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
657 if (!start_charshunt(0, 1))
659 } else if (record_file != NULL) {
660 if (!start_charshunt(ttyfd, ttyfd))
664 /* run connection script */
665 if ((connector && connector[0]) || initializer) {
666 if (real_ttyfd != -1) {
667 if (!default_device && modem) {
668 setdtr(real_ttyfd, 0); /* in case modem is off hook */
670 setdtr(real_ttyfd, 1);
674 if (initializer && initializer[0]) {
675 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
676 error("Initializer script failed");
677 status = EXIT_INIT_FAILED;
683 info("Serial port initialized.");
686 if (connector && connector[0]) {
687 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
688 error("Connect script failed");
689 status = EXIT_CONNECT_FAILED;
695 info("Serial connection established.");
698 /* set line speed, flow control, etc.;
699 clear CLOCAL if modem option */
700 if (real_ttyfd != -1)
701 set_up_tty(real_ttyfd, 0);
704 /* reopen tty if necessary to wait for carrier */
705 if (connector == NULL && modem && devnam[0] != 0) {
707 if ((i = open(devnam, O_RDWR)) >= 0)
709 if (errno != EINTR) {
710 error("Failed to reopen %s: %m", devnam);
711 status = EXIT_OPEN_FAILED;
713 if (!persist || errno != EINTR || hungup || kill_link)
719 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
720 script_setenv("SPEED", numbuf);
722 /* run welcome script, if any */
723 if (welcomer && welcomer[0]) {
724 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
725 warn("Welcome script failed");
728 /* set up the serial device as a ppp interface */
729 fd_ppp = establish_ppp(ttyfd);
731 status = EXIT_FATAL_ERROR;
737 info("Using interface ppp%d", ifunit);
738 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
739 script_setenv("IFNAME", ifname);
741 create_pidfile(); /* write pid to file */
745 * Start opening the connection and wait for
746 * incoming events (reply, timeout, etc.).
748 notice("Connect: %s <--> %s", ifname, ppp_devnam);
749 gettimeofday(&start_time, NULL);
750 link_stats_valid = 0;
751 script_unsetenv("CONNECT_TIME");
752 script_unsetenv("BYTES_SENT");
753 script_unsetenv("BYTES_RCVD");
757 * If we are initiating this connection, wait for a short
758 * time for something from the peer. This can avoid bouncing
759 * our packets off his tty before he has it set up.
761 if (connector != NULL || ptycommand != NULL) {
768 lcp_open(0); /* Start protocol */
771 status = EXIT_NEGOTIATION_FAILED;
772 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
773 if (sigsetjmp(sigjmp, 1) == 0) {
774 sigprocmask(SIG_BLOCK, &mask, NULL);
775 if (kill_link || open_ccp_flag || got_sigchld) {
776 sigprocmask(SIG_UNBLOCK, &mask, NULL);
779 sigprocmask(SIG_UNBLOCK, &mask, NULL);
780 wait_input(timeleft(&timo));
787 lcp_close(0, "User request");
791 if (phase == PHASE_NETWORK) {
792 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
793 (*ccp_protent.open)(0);
798 reap_kids(0); /* Don't leave dead kids lying around */
802 * Print connect time and statistics.
804 if (link_stats_valid) {
805 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
806 info("Connect time %d.%d minutes.", t/10, t%10);
807 info("Sent %d bytes, received %d bytes.",
808 link_stats.bytes_out, link_stats.bytes_in);
812 * If we may want to bring the link up again, transfer
813 * the ppp unit back to the loopback. Set the
814 * real serial device back to its normal mode of operation.
820 disestablish_ppp(ttyfd);
826 * Run disconnector script, if requested.
827 * XXX we may not be able to do this if the line has hung up!
830 if (disconnector && !hungup) {
832 set_up_tty(real_ttyfd, 1);
833 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
834 warn("disconnect script failed");
836 info("Serial link disconnected.");
853 if (pidfilename[0] != 0
854 && unlink(pidfilename) < 0 && errno != ENOENT)
855 warn("unable to delete pid file: %m");
865 if (holdoff > 0 && need_holdoff) {
866 phase = PHASE_HOLDOFF;
867 TIMEOUT(holdoff_end, NULL, holdoff);
869 if (sigsetjmp(sigjmp, 1) == 0) {
870 sigprocmask(SIG_BLOCK, &mask, NULL);
871 if (kill_link || got_sigchld) {
872 sigprocmask(SIG_UNBLOCK, &mask, NULL);
875 sigprocmask(SIG_UNBLOCK, &mask, NULL);
876 wait_input(timeleft(&timo));
883 phase = PHASE_DORMANT; /* allow signal to end holdoff */
887 } while (phase == PHASE_HOLDOFF);
893 /* Wait for scripts to finish */
894 /* XXX should have a timeout here */
895 while (n_children > 0) {
897 struct subprocess *chp;
898 dbglog("Waiting for %d child processes...", n_children);
899 for (chp = children; chp != NULL; chp = chp->next)
900 dbglog(" script %s, pid %d", chp->prog, chp->pid);
910 * detach - detach us from the controlling terminal.
919 if ((pid = fork()) < 0) {
920 error("Couldn't detach (fork failed: %m)");
921 die(1); /* or just return? */
927 exit(0); /* parent dies */
936 /* update pid file if it has been written already */
942 * reopen_log - (re)open our connection to syslog.
948 openlog("pppd", LOG_PID);
950 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
951 setlogmask(LOG_UPTO(LOG_INFO));
956 * Create a file containing our process ID.
964 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
965 _PATH_VARRUN, ifname);
966 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
967 fprintf(pidfile, "%d\n", getpid());
968 (void) fclose(pidfile);
970 error("Failed to create pid file %s: %m", pidfilename);
973 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
974 script_setenv("PPPD_PID", numbuf);
978 * holdoff_end - called via a timeout when the holdoff period ends.
984 phase = PHASE_DORMANT;
988 * get_input - called when incoming data is available.
996 struct protent *protp;
998 p = inpacket_buf; /* point to beginning of packet buffer */
1000 len = read_packet(inpacket_buf);
1005 notice("Modem hangup");
1007 status = EXIT_HANGUP;
1008 lcp_lowerdown(0); /* serial link is no longer available */
1013 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1014 dbglog("rcvd %P", p, len);
1016 if (len < PPP_HDRLEN) {
1017 MAINDEBUG(("io(): Received short packet."));
1021 p += 2; /* Skip address and control */
1022 GETSHORT(protocol, p);
1026 * Toss all non-LCP packets unless LCP is OPEN.
1028 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1029 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1034 * Until we get past the authentication phase, toss all packets
1035 * except LCP, LQR and authentication packets.
1037 if (phase <= PHASE_AUTHENTICATE
1038 && !(protocol == PPP_LCP || protocol == PPP_LQR
1039 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1040 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1046 * Upcall the proper protocol input routine.
1048 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1049 if (protp->protocol == protocol && protp->enabled_flag) {
1050 (*protp->input)(0, p, len);
1053 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1054 && protp->datainput != NULL) {
1055 (*protp->datainput)(0, p, len);
1061 warn("Unsupported protocol (0x%x) received", protocol);
1062 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1067 * die - clean up state and exit with the specified status.
1074 syslog(LOG_INFO, "Exit.");
1079 * cleanup - restore anything which needs to be restored before we exit
1088 disestablish_ppp(ttyfd);
1089 if (real_ttyfd >= 0)
1092 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1093 warn("unable to delete pid file: %m");
1101 * close_tty - restore the terminal device and close it.
1106 /* drop dtr to hang up */
1107 if (!default_device && modem) {
1108 setdtr(real_ttyfd, 0);
1110 * This sleep is in case the serial port has CLOCAL set by default,
1111 * and consequently will reassert DTR when we close the device.
1116 restore_tty(real_ttyfd);
1118 if (tty_mode != (mode_t) -1) {
1119 if (fchmod(real_ttyfd, tty_mode) != 0) {
1120 /* XXX if devnam is a symlink, this will change the link */
1121 chmod(devnam, tty_mode);
1130 * update_link_stats - get stats at link termination.
1133 update_link_stats(u)
1139 if (!get_ppp_stats(u, &link_stats)
1140 || gettimeofday(&now, NULL) < 0)
1142 link_connect_time = now.tv_sec - start_time.tv_sec;
1143 link_stats_valid = 1;
1145 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1146 script_setenv("CONNECT_TIME", numbuf);
1147 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1148 script_setenv("BYTES_SENT", numbuf);
1149 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1150 script_setenv("BYTES_RCVD", numbuf);
1155 struct timeval c_time; /* time at which to call routine */
1156 void *c_arg; /* argument to routine */
1157 void (*c_func) __P((void *)); /* routine */
1158 struct callout *c_next;
1161 static struct callout *callout = NULL; /* Callout list */
1162 static struct timeval timenow; /* Current time */
1165 * timeout - Schedule a timeout.
1167 * Note that this timeout takes the number of seconds, NOT hz (as in
1171 timeout(func, arg, time)
1172 void (*func) __P((void *));
1176 struct callout *newp, *p, **pp;
1178 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1183 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1184 fatal("Out of memory in timeout()!");
1186 newp->c_func = func;
1187 gettimeofday(&timenow, NULL);
1188 newp->c_time.tv_sec = timenow.tv_sec + time;
1189 newp->c_time.tv_usec = timenow.tv_usec;
1192 * Find correct place and link it in.
1194 for (pp = &callout; (p = *pp); pp = &p->c_next)
1195 if (newp->c_time.tv_sec < p->c_time.tv_sec
1196 || (newp->c_time.tv_sec == p->c_time.tv_sec
1197 && newp->c_time.tv_usec < p->c_time.tv_usec))
1205 * untimeout - Unschedule a timeout.
1208 untimeout(func, arg)
1209 void (*func) __P((void *));
1212 struct callout **copp, *freep;
1214 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1217 * Find first matching timeout and remove it from the list.
1219 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1220 if (freep->c_func == func && freep->c_arg == arg) {
1221 *copp = freep->c_next;
1222 (void) free((char *) freep);
1229 * calltimeout - Call any timeout routines which are now due.
1236 while (callout != NULL) {
1239 if (gettimeofday(&timenow, NULL) < 0)
1240 fatal("Failed to get time of day: %m");
1241 if (!(p->c_time.tv_sec < timenow.tv_sec
1242 || (p->c_time.tv_sec == timenow.tv_sec
1243 && p->c_time.tv_usec <= timenow.tv_usec)))
1244 break; /* no, it's not time yet */
1246 callout = p->c_next;
1247 (*p->c_func)(p->c_arg);
1255 * timeleft - return the length of time until the next timeout is due.
1257 static struct timeval *
1259 struct timeval *tvp;
1261 if (callout == NULL)
1264 gettimeofday(&timenow, NULL);
1265 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1266 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1267 if (tvp->tv_usec < 0) {
1268 tvp->tv_usec += 1000000;
1271 if (tvp->tv_sec < 0)
1272 tvp->tv_sec = tvp->tv_usec = 0;
1279 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1285 struct sigaction act, oldact;
1287 act.sa_handler = SIG_IGN;
1290 sigaction(sig, &act, &oldact);
1291 sigaction(sig, &oldact, NULL);
1296 * hup - Catch SIGHUP signal.
1298 * Indicates that the physical layer has been disconnected.
1299 * We don't rely on this indication; if the user has sent this
1300 * signal, we just take the link down.
1306 info("Hangup (SIGHUP)");
1308 if (status != EXIT_HANGUP)
1309 status = EXIT_USER_REQUEST;
1311 /* Send the signal to the [dis]connector process(es) also */
1314 kill(charshunt_pid, sig);
1316 siglongjmp(sigjmp, 1);
1321 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1323 * Indicates that we should initiate a graceful disconnect and exit.
1330 info("Terminating on signal %d.", sig);
1331 persist = 0; /* don't try to restart */
1333 status = EXIT_USER_REQUEST;
1335 /* Send the signal to the [dis]connector process(es) also */
1338 kill(charshunt_pid, sig);
1340 siglongjmp(sigjmp, 1);
1345 * chld - Catch SIGCHLD signal.
1346 * Sets a flag so we will call reap_kids in the mainline.
1354 siglongjmp(sigjmp, 1);
1359 * toggle_debug - Catch SIGUSR1 signal.
1361 * Toggle debug flag.
1370 setlogmask(LOG_UPTO(LOG_DEBUG));
1372 setlogmask(LOG_UPTO(LOG_WARNING));
1378 * open_ccp - Catch SIGUSR2 signal.
1380 * Try to (re)negotiate compression.
1389 siglongjmp(sigjmp, 1);
1394 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1400 static int crashed = 0;
1405 error("Fatal signal %d", sig);
1407 kill_my_pg(SIGTERM);
1409 kill(charshunt_pid, SIGTERM);
1415 * device_script - run a program to talk to the serial device
1416 * (e.g. to run the connector or disconnector script).
1419 device_script(program, in, out, dont_wait)
1433 error("Failed to create child process: %m");
1442 int newin = dup(in);
1446 } else if (out == 2) {
1449 if (log_to_fd >= 0) {
1454 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1455 if (errfd >= 0 && errfd != 2) {
1475 if (getuid() != uid) {
1476 error("setuid failed");
1480 execl("/bin/sh", "sh", "-c", program, (char *)0);
1481 error("could not exec /bin/sh: %m");
1487 record_child(pid, program, NULL, NULL);
1490 while (waitpid(pid, &status, 0) < 0) {
1493 fatal("error waiting for (dis)connection process: %m");
1498 return (status == 0 ? 0 : -1);
1503 * run-program - execute a program with given arguments,
1504 * but don't wait for it.
1505 * If the program can't be executed, logs an error unless
1506 * must_exist is 0 and the program file doesn't exist.
1507 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1508 * or isn't an executable plain file, or the process ID of the child.
1509 * If done != NULL, (*done)(arg) will be called later (within
1510 * reap_kids) iff the return value is > 0.
1513 run_program(prog, args, must_exist, done, arg)
1517 void (*done) __P((void *));
1524 * First check if the file exists and is executable.
1525 * We don't use access() because that would use the
1526 * real user-id, which might not be root, and the script
1527 * might be accessible only to root.
1530 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1531 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1532 if (must_exist || errno != ENOENT)
1533 warn("Can't execute %s: %m", prog);
1539 error("Failed to create child process for %s: %m", prog);
1545 /* Leave the current location */
1546 (void) setsid(); /* No controlling tty. */
1547 (void) umask (S_IRWXG|S_IRWXO);
1548 (void) chdir ("/"); /* no current directory. */
1549 setuid(0); /* set real UID = root */
1552 /* Ensure that nothing of our device environment is inherited. */
1558 close (ttyfd); /* tty interface to the ppp device */
1559 if (real_ttyfd >= 0)
1562 /* Don't pass handles to the PPP device, even by accident. */
1563 new_fd = open (_PATH_DEVNULL, O_RDWR);
1566 dup2 (new_fd, 0); /* stdin <- /dev/null */
1569 dup2 (0, 1); /* stdout -> /dev/null */
1570 dup2 (0, 2); /* stderr -> /dev/null */
1574 /* Force the priority back to zero if pppd is running higher. */
1575 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1576 warn("can't reset priority to 0: %m");
1579 /* SysV recommends a second fork at this point. */
1581 /* run the program */
1582 execve(prog, args, script_env);
1583 if (must_exist || errno != ENOENT) {
1584 /* have to reopen the log, there's nowhere else
1585 for the message to go. */
1587 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1594 dbglog("Script %s started (pid %d)", prog, pid);
1595 record_child(pid, prog, done, arg);
1602 * record_child - add a child process to the list for reap_kids
1606 record_child(pid, prog, done, arg)
1609 void (*done) __P((void *));
1612 struct subprocess *chp;
1616 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1618 warn("losing track of %s process", prog);
1624 chp->next = children;
1631 * reap_kids - get status from any dead child processes,
1632 * and log a message for abnormal terminations.
1639 struct subprocess *chp, **prevp;
1642 if (n_children == 0)
1644 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1647 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1648 if (chp->pid == pid) {
1653 if (WIFSIGNALED(status)) {
1654 warn("Child process %s (pid %d) terminated with signal %d",
1655 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1657 dbglog("Script %s finished (pid %d), status = 0x%x",
1658 (chp? chp->prog: "??"), pid, status);
1659 if (chp && chp->done)
1660 (*chp->done)(chp->arg);
1664 if (pid == -1 && errno != ECHILD && errno != EINTR)
1665 error("Error waiting for child process: %m");
1670 * novm - log an error message saying we ran out of memory, and die.
1676 fatal("Virtual memory exhausted allocating %s\n", msg);
1680 * script_setenv - set an environment variable value to be used
1681 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1684 script_setenv(var, value)
1687 size_t vl = strlen(var) + strlen(value) + 2;
1689 char *p, *newstring;
1691 newstring = (char *) malloc(vl);
1694 slprintf(newstring, vl, "%s=%s", var, value);
1696 /* check if this variable is already set */
1697 if (script_env != 0) {
1698 for (i = 0; (p = script_env[i]) != 0; ++i) {
1699 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1701 script_env[i] = newstring;
1707 script_env = (char **) malloc(16 * sizeof(char *));
1708 if (script_env == 0)
1713 /* reallocate script_env with more space if needed */
1714 if (i + 1 >= s_env_nalloc) {
1716 char **newenv = (char **) realloc((void *)script_env,
1717 new_n * sizeof(char *));
1720 script_env = newenv;
1721 s_env_nalloc = new_n;
1724 script_env[i] = newstring;
1725 script_env[i+1] = 0;
1729 * script_unsetenv - remove a variable from the environment
1733 script_unsetenv(var)
1736 int vl = strlen(var);
1740 if (script_env == 0)
1742 for (i = 0; (p = script_env[i]) != 0; ++i) {
1743 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1745 while ((script_env[i] = script_env[i+1]) != 0)
1753 * start_charshunt - create a child process to run the character shunt.
1756 start_charshunt(ifd, ofd)
1763 error("Can't fork process for character shunt: %m");
1770 if (getuid() != uid)
1771 fatal("setuid failed");
1775 charshunt(ifd, ofd, record_file);
1778 charshunt_pid = cpid;
1782 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1794 * charshunt - the character shunt, which passes characters between
1795 * the pty master side and the serial port (or stdin/stdout).
1796 * This runs as the user (not as root).
1797 * (We assume ofd >= ifd which is true the way this gets called. :-).
1800 charshunt(ifd, ofd, record_file)
1805 fd_set ready, writey;
1806 u_char *ibufp, *obufp;
1809 int pty_readable, stdin_readable;
1810 struct timeval lasttime;
1811 FILE *recordf = NULL;
1814 * Reset signal handlers.
1816 signal(SIGHUP, SIG_IGN); /* Hangup */
1817 signal(SIGINT, SIG_DFL); /* Interrupt */
1818 signal(SIGTERM, SIG_DFL); /* Terminate */
1819 signal(SIGCHLD, SIG_DFL);
1820 signal(SIGUSR1, SIG_DFL);
1821 signal(SIGUSR2, SIG_DFL);
1822 signal(SIGABRT, SIG_DFL);
1823 signal(SIGALRM, SIG_DFL);
1824 signal(SIGFPE, SIG_DFL);
1825 signal(SIGILL, SIG_DFL);
1826 signal(SIGPIPE, SIG_DFL);
1827 signal(SIGQUIT, SIG_DFL);
1828 signal(SIGSEGV, SIG_DFL);
1830 signal(SIGBUS, SIG_DFL);
1833 signal(SIGEMT, SIG_DFL);
1836 signal(SIGPOLL, SIG_DFL);
1839 signal(SIGPROF, SIG_DFL);
1842 signal(SIGSYS, SIG_DFL);
1845 signal(SIGTRAP, SIG_DFL);
1848 signal(SIGVTALRM, SIG_DFL);
1851 signal(SIGXCPU, SIG_DFL);
1854 signal(SIGXFSZ, SIG_DFL);
1858 * Open the record file if required.
1860 if (record_file != NULL) {
1861 recordf = fopen(record_file, "a");
1862 if (recordf == NULL)
1863 error("Couldn't create record file %s: %m", record_file);
1866 /* set all the fds to non-blocking mode */
1867 flags = fcntl(pty_master, F_GETFL);
1869 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1870 warn("couldn't set pty master to nonblock: %m");
1871 flags = fcntl(ifd, F_GETFL);
1873 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1874 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1876 flags = fcntl(ofd, F_GETFL);
1878 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1879 warn("couldn't set stdout to nonblock: %m");
1883 ibufp = obufp = NULL;
1884 pty_readable = stdin_readable = 1;
1885 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1886 if (recordf != NULL) {
1887 gettimeofday(&lasttime, NULL);
1888 putc(7, recordf); /* put start marker */
1889 putc(lasttime.tv_sec >> 24, recordf);
1890 putc(lasttime.tv_sec >> 16, recordf);
1891 putc(lasttime.tv_sec >> 8, recordf);
1892 putc(lasttime.tv_sec, recordf);
1893 lasttime.tv_usec = 0;
1896 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1900 FD_SET(pty_master, &writey);
1901 else if (stdin_readable)
1902 FD_SET(ifd, &ready);
1904 FD_SET(ofd, &writey);
1905 else if (pty_readable)
1906 FD_SET(pty_master, &ready);
1907 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1912 if (FD_ISSET(ifd, &ready)) {
1913 ibufp = inpacket_buf;
1914 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1915 if (nibuf < 0 && errno == EIO)
1918 if (!(errno == EINTR || errno == EAGAIN)) {
1919 error("Error reading standard input: %m");
1923 } else if (nibuf == 0) {
1924 /* end of file from stdin */
1926 /* do a 0-length write, hopefully this will generate
1927 an EOF (hangup) on the slave side. */
1928 write(pty_master, inpacket_buf, 0);
1930 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1933 FD_SET(pty_master, &writey);
1935 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1939 if (FD_ISSET(pty_master, &ready)) {
1940 obufp = outpacket_buf;
1941 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1942 if (nobuf < 0 && errno == EIO)
1945 if (!(errno == EINTR || errno == EAGAIN)) {
1946 error("Error reading pseudo-tty master: %m");
1950 } else if (nobuf == 0) {
1951 /* end of file from the pty - slave side has closed */
1953 stdin_readable = 0; /* pty is not writable now */
1957 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1960 FD_SET(ofd, &writey);
1962 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1966 if (FD_ISSET(ofd, &writey)) {
1967 n = write(ofd, obufp, nobuf);
1970 error("Error writing standard output: %m");
1980 if (FD_ISSET(pty_master, &writey)) {
1981 n = write(pty_master, ibufp, nibuf);
1984 error("Error writing pseudo-tty master: %m");
1999 record_write(f, code, buf, nb, tp)
2009 gettimeofday(&now, NULL);
2010 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2011 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2015 putc(diff >> 24, f);
2016 putc(diff >> 16, f);
2029 fwrite(buf, nb, 1, f);
2033 error("Error writing record file: %m");