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.
20 #define RCSID "$Id: main.c,v 1.97 2000/04/24 02:54:16 masputra Exp $"
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
56 #include "pathnames.h"
57 #include "patchlevel.h"
66 #endif /* IPX_CHANGE */
71 static const char rcsid[] = RCSID;
74 char ifname[32]; /* Interface name */
75 int ifunit; /* Interface unit number */
77 char *progname; /* Name of this program */
78 char hostname[MAXNAMELEN]; /* Our hostname */
79 static char pidfilename[MAXPATHLEN]; /* name of pid file */
80 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
81 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
82 static uid_t uid; /* Our real user-id */
83 static int conn_running; /* we have a [dis]connector running */
85 int ttyfd; /* Serial port file descriptor */
86 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
87 int baud_rate; /* Actual bits/second for serial device */
88 int hungup; /* terminal has been hung up */
89 int privileged; /* we're running as real uid root */
90 int need_holdoff; /* need holdoff period before restarting */
91 int detached; /* have detached from terminal */
92 struct stat devstat; /* result of stat() on devnam */
93 int prepass = 0; /* doing prepass to find device name */
94 int devnam_fixed; /* set while in options.ttyxx file */
95 volatile int status; /* exit status for pppd */
96 int unsuccess; /* # unsuccessful connection attempts */
97 int do_callback; /* != 0 if we should do callback next */
98 int doing_callback; /* != 0 if we are doing callback */
99 char *callback_script; /* script for doing callback */
100 TDB_CONTEXT *pppdb; /* database for storing status etc. */
103 int (*holdoff_hook) __P((void)) = NULL;
104 int (*new_phase_hook) __P((int)) = NULL;
106 static int fd_ppp = -1; /* fd for talking PPP */
107 static int fd_loop; /* fd for getting demand-dial packets */
108 static int pty_master; /* fd for master side of pty */
109 static int pty_slave; /* fd for slave side of pty */
110 static int real_ttyfd; /* fd for actual serial port (not pty) */
112 int phase; /* where the link is at */
117 static sigjmp_buf sigjmp;
119 char **script_env; /* Env. variable values for scripts */
120 int s_env_nalloc; /* # words avail at script_env */
122 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
123 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
125 static int n_children; /* # child processes still running */
126 static int got_sigchld; /* set if we have received a SIGCHLD */
128 static int locked; /* lock() has succeeded */
129 static int privopen; /* don't lock, open device as root */
131 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
133 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
134 int ngroups; /* How many groups valid in groups */
136 static struct timeval start_time; /* Time when link was started. */
138 struct pppd_stats link_stats;
139 int link_connect_time;
140 int link_stats_valid;
142 static int charshunt_pid; /* Process ID for charshunt */
145 * We maintain a list of child process pids and
146 * functions to call when they exit.
151 void (*done) __P((void *));
153 struct subprocess *next;
156 static struct subprocess *children;
158 /* Prototypes for procedures local to this file. */
160 static void setup_signals __P((void));
161 static void create_pidfile __P((void));
162 static void create_linkpidfile __P((void));
163 static void cleanup __P((void));
164 static void close_tty __P((void));
165 static void get_input __P((void));
166 static void calltimeout __P((void));
167 static struct timeval *timeleft __P((struct timeval *));
168 static void kill_my_pg __P((int));
169 static void hup __P((int));
170 static void term __P((int));
171 static void chld __P((int));
172 static void toggle_debug __P((int));
173 static void open_ccp __P((int));
174 static void bad_signal __P((int));
175 static void holdoff_end __P((void *));
176 static int device_script __P((char *, int, int, int));
177 static int reap_kids __P((int waitfor));
178 static void record_child __P((int, char *, void (*) (void *), void *));
179 static void update_db_entry __P((void));
180 static void add_db_key __P((const char *));
181 static void delete_db_key __P((const char *));
182 static void cleanup_db __P((void));
183 static int open_socket __P((char *));
184 static int start_charshunt __P((int, int));
185 static void charshunt_done __P((void *));
186 static void charshunt __P((int, int, char *));
187 static int record_write __P((FILE *, int code, u_char *buf, int nb,
190 extern char *ttyname __P((int));
191 extern char *getlogin __P((void));
192 int main __P((int, char *[]));
196 #define O_NONBLOCK O_NDELAY
200 #define setlogmask(x)
204 * PPP Data Link Layer "protocol" table.
205 * One entry per supported protocol.
206 * The last entry must be NULL.
208 struct protent *protocols[] = {
230 * If PPP_DRV_NAME is not defined, use the legacy "ppp" as the
233 #if !defined(PPP_DRV_NAME)
234 #define PPP_DRV_NAME "ppp"
235 #endif /* !defined(PPP_DRV_NAME) */
247 struct protent *protp;
251 new_phase(PHASE_INITIALIZE);
254 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
255 * This way we can close 0, 1, 2 in detach() without clobbering
256 * a fd that we are using.
258 if ((i = open("/dev/null", O_RDWR)) >= 0) {
259 while (0 <= i && i <= 2)
267 /* Initialize syslog facilities */
270 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
271 option_error("Couldn't get hostname: %m");
274 hostname[MAXNAMELEN-1] = 0;
276 /* make sure we don't create world or group writable files. */
277 umask(umask(0777) | 022);
280 privileged = uid == 0;
281 slprintf(numbuf, sizeof(numbuf), "%d", uid);
282 script_setenv("ORIG_UID", numbuf, 0);
284 ngroups = getgroups(NGROUPS_MAX, groups);
287 * Initialize magic number generator now so that protocols may
288 * use magic numbers in initialization.
293 * Initialize to the standard option set, then parse, in order,
294 * the system options file, the user's options file,
295 * the tty's options file, and the command line arguments.
297 for (i = 0; (protp = protocols[i]) != NULL; ++i)
303 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
304 || !options_from_user())
305 exit(EXIT_OPTION_ERROR);
307 /* scan command line and options files to find device name */
309 parse_args(argc-1, argv+1);
313 * Work out the device name, if it hasn't already been specified.
315 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
316 if (!using_pty && default_device) {
318 if (!isatty(0) || (p = ttyname(0)) == NULL) {
319 option_error("no device specified and stdin is not a tty");
320 exit(EXIT_OPTION_ERROR);
322 strlcpy(devnam, p, sizeof(devnam));
323 if (stat(devnam, &devstat) < 0)
324 fatal("Couldn't stat default device %s: %m", devnam);
328 * Parse the tty options file and the command line.
329 * The per-tty options file should not change
330 * ptycommand, pty_socket, notty or devnam.
334 if (!options_for_tty())
335 exit(EXIT_OPTION_ERROR);
339 if (!parse_args(argc-1, argv+1))
340 exit(EXIT_OPTION_ERROR);
343 * Check that we are running as root.
345 if (geteuid() != 0) {
346 option_error("must be root to run %s, since it is not setuid-root",
351 if (!ppp_available()) {
352 option_error(no_ppp_msg);
353 exit(EXIT_NO_KERNEL_SUPPORT);
357 * Check that the options given are valid and consistent.
359 if (!sys_check_options())
360 exit(EXIT_OPTION_ERROR);
361 auth_check_options();
362 #ifdef HAVE_MULTILINK
365 for (i = 0; (protp = protocols[i]) != NULL; ++i)
366 if (protp->check_options != NULL)
367 (*protp->check_options)();
368 if (demand && connect_script == 0) {
369 option_error("connect script is required for demand-dialling\n");
370 exit(EXIT_OPTION_ERROR);
372 /* default holdoff to 0 if no connect script has been given */
373 if (connect_script == 0 && !holdoff_specified)
377 if (!default_device) {
378 option_error("%s option precludes specifying device name",
379 notty? "notty": "pty");
380 exit(EXIT_OPTION_ERROR);
382 if (ptycommand != NULL && notty) {
383 option_error("pty option is incompatible with notty option");
384 exit(EXIT_OPTION_ERROR);
386 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
387 option_error("socket option is incompatible with pty and notty");
388 exit(EXIT_OPTION_ERROR);
390 default_device = notty;
393 if (notty && log_to_fd <= 1)
397 * If the user has specified a device which is the same as
398 * the one on stdin, pretend they didn't specify any.
399 * If the device is already open read/write on stdin,
400 * we assume we don't need to lock it, and we can open it as root.
402 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
403 && statbuf.st_rdev == devstat.st_rdev) {
405 fdflags = fcntl(0, F_GETFL);
406 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
414 * Don't send log messages to the serial port, it tends to
415 * confuse the peer. :-)
417 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
418 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
422 * Initialize system-dependent stuff.
426 setlogmask(LOG_UPTO(LOG_DEBUG));
428 pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
430 slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
433 warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
435 warn("Warning: disabling multilink");
441 * Detach ourselves from the terminal, if required,
442 * and identify who is running us.
444 if (!nodetach && !updetach)
449 if (pw != NULL && pw->pw_name != NULL)
454 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
455 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
456 script_setenv("PPPLOGNAME", p, 0);
459 script_setenv("DEVICE", devnam, 1);
460 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
461 script_setenv("PPPD_PID", numbuf, 1);
467 create_linkpidfile();
470 * If we're doing dial-on-demand, set up the interface now.
474 * Open the loopback channel and set it up to be the ppp interface.
476 tdb_writelock(pppdb);
477 fd_loop = open_ppp_loopback();
479 tdb_writeunlock(pppdb);
482 * Configure the interface and mark it up, etc.
495 doing_callback = do_callback;
498 if (demand && !doing_callback) {
500 * Don't do anything until we see some activity.
503 new_phase(PHASE_DORMANT);
507 if (sigsetjmp(sigjmp, 1) == 0) {
508 sigprocmask(SIG_BLOCK, &mask, NULL);
509 if (kill_link || got_sigchld) {
510 sigprocmask(SIG_UNBLOCK, &mask, NULL);
513 sigprocmask(SIG_UNBLOCK, &mask, NULL);
514 wait_input(timeleft(&timo));
524 if (get_loop_output())
530 if (kill_link && !persist)
534 * Now we want to bring up the link.
537 info("Starting link");
540 new_phase(PHASE_SERIALCONN);
543 * Get a pty master/slave pair if the pty, notty, socket,
544 * or record options were specified.
546 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
549 if (using_pty || record_file != NULL) {
550 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
551 error("Couldn't allocate pseudo-tty");
552 status = EXIT_FATAL_ERROR;
555 set_up_tty(pty_slave, 1);
559 * Lock the device if we've been asked to.
561 status = EXIT_LOCK_FAILED;
562 if (lockflag && !privopen) {
563 if (lock(devnam) < 0)
569 * Open the serial device and set it up to be the ppp interface.
570 * First we open it in non-blocking mode so we can set the
571 * various termios flags appropriately. If we aren't dialling
572 * out and we want to use the modem lines, we reopen it later
573 * in order to wait for the carrier detect signal from the modem.
577 connector = doing_callback? callback_script: connect_script;
578 if (devnam[0] != 0) {
580 /* If the user specified the device name, become the
581 user before opening it. */
583 if (!devnam_info.priv && !privopen)
585 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
587 if (!devnam_info.priv && !privopen)
593 error("Failed to open %s: %m", devnam);
594 status = EXIT_OPEN_FAILED;
596 if (!persist || err != EINTR)
599 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
600 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
601 warn("Couldn't reset non-blocking mode on device: %m");
604 * Do the equivalent of `mesg n' to stop broadcast messages.
606 if (fstat(ttyfd, &statbuf) < 0
607 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
608 warn("Couldn't restrict write permissions to %s: %m", devnam);
610 tty_mode = statbuf.st_mode;
613 * Set line speed, flow control, etc.
614 * If we have a non-null connection or initializer script,
615 * on most systems we set CLOCAL for now so that we can talk
616 * to the modem before carrier comes up. But this has the
617 * side effect that we might miss it if CD drops before we
618 * get to clear CLOCAL below. On systems where we can talk
619 * successfully to the modem with CLOCAL clear and CD down,
620 * we could clear CLOCAL at this point.
622 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
623 || initializer != NULL));
628 * If the pty, socket, notty and/or record option was specified,
629 * start up the character shunt now.
631 status = EXIT_PTYCMD_FAILED;
632 if (ptycommand != NULL) {
633 if (record_file != NULL) {
634 int ipipe[2], opipe[2], ok;
636 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
637 fatal("Couldn't create pipes for record option: %m");
638 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
639 && start_charshunt(ipipe[0], opipe[1]);
647 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
653 } else if (pty_socket != NULL) {
654 int fd = open_socket(pty_socket);
657 if (!start_charshunt(fd, fd))
660 if (!start_charshunt(0, 1))
662 } else if (record_file != NULL) {
663 if (!start_charshunt(ttyfd, ttyfd))
667 /* run connection script */
668 if ((connector && connector[0]) || initializer) {
669 if (real_ttyfd != -1) {
670 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
671 if (!default_device && modem) {
672 setdtr(real_ttyfd, 0); /* in case modem is off hook */
674 setdtr(real_ttyfd, 1);
678 if (initializer && initializer[0]) {
679 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
680 error("Initializer script failed");
681 status = EXIT_INIT_FAILED;
687 info("Serial port initialized.");
690 if (connector && connector[0]) {
691 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
692 error("Connect script failed");
693 status = EXIT_CONNECT_FAILED;
699 info("Serial connection established.");
702 /* set line speed, flow control, etc.;
703 clear CLOCAL if modem option */
704 if (real_ttyfd != -1)
705 set_up_tty(real_ttyfd, 0);
707 if (doing_callback == CALLBACK_DIALIN)
711 /* reopen tty if necessary to wait for carrier */
712 if (connector == NULL && modem && devnam[0] != 0) {
714 if ((i = open(devnam, O_RDWR)) >= 0)
716 if (errno != EINTR) {
717 error("Failed to reopen %s: %m", devnam);
718 status = EXIT_OPEN_FAILED;
720 if (!persist || errno != EINTR || hungup || kill_link)
726 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
727 script_setenv("SPEED", numbuf, 0);
729 /* run welcome script, if any */
730 if (welcomer && welcomer[0]) {
731 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
732 warn("Welcome script failed");
735 /* set up the serial device as a ppp interface */
736 tdb_writelock(pppdb);
737 fd_ppp = establish_ppp(ttyfd);
739 tdb_writeunlock(pppdb);
740 status = EXIT_FATAL_ERROR;
744 if (!demand && ifunit >= 0)
746 tdb_writeunlock(pppdb);
749 * Start opening the connection and wait for
750 * incoming events (reply, timeout, etc.).
752 notice("Connect: %s <--> %s", ifname, ppp_devnam);
753 gettimeofday(&start_time, NULL);
754 link_stats_valid = 0;
755 script_unsetenv("CONNECT_TIME");
756 script_unsetenv("BYTES_SENT");
757 script_unsetenv("BYTES_RCVD");
761 * If we are initiating this connection, wait for a short
762 * time for something from the peer. This can avoid bouncing
763 * our packets off his tty before he has it set up.
766 if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
768 t.tv_sec = connect_delay / 1000;
769 t.tv_usec = connect_delay % 1000;
773 lcp_open(0); /* Start protocol */
775 status = EXIT_NEGOTIATION_FAILED;
776 new_phase(PHASE_ESTABLISH);
777 while (phase != PHASE_DEAD) {
778 if (sigsetjmp(sigjmp, 1) == 0) {
779 sigprocmask(SIG_BLOCK, &mask, NULL);
780 if (kill_link || open_ccp_flag || got_sigchld) {
781 sigprocmask(SIG_UNBLOCK, &mask, NULL);
784 sigprocmask(SIG_UNBLOCK, &mask, NULL);
785 wait_input(timeleft(&timo));
792 lcp_close(0, "User request");
796 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
797 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
798 (*ccp_protent.open)(0);
803 reap_kids(0); /* Don't leave dead kids lying around */
807 * Print connect time and statistics.
809 if (link_stats_valid) {
810 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
811 info("Connect time %d.%d minutes.", t/10, t%10);
812 info("Sent %d bytes, received %d bytes.",
813 link_stats.bytes_out, link_stats.bytes_in);
817 * Delete pid file before disestablishing ppp. Otherwise it
818 * can happen that another pppd gets the same unit and then
819 * we delete its pid file.
822 if (pidfilename[0] != 0
823 && unlink(pidfilename) < 0 && errno != ENOENT)
824 warn("unable to delete pid file %s: %m", pidfilename);
829 * If we may want to bring the link up again, transfer
830 * the ppp unit back to the loopback. Set the
831 * real serial device back to its normal mode of operation.
837 disestablish_ppp(ttyfd);
842 script_unsetenv("IFNAME");
845 * Run disconnector script, if requested.
846 * XXX we may not be able to do this if the line has hung up!
849 if (disconnect_script && !hungup) {
850 new_phase(PHASE_DISCONNECT);
852 set_up_tty(real_ttyfd, 1);
853 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
854 warn("disconnect script failed");
856 info("Serial link disconnected.");
873 if (pidfilename[0] != 0
874 && unlink(pidfilename) < 0 && errno != ENOENT)
875 warn("unable to delete pid file %s: %m", pidfilename);
879 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
885 t = need_holdoff? holdoff: 0;
887 t = (*holdoff_hook)();
889 new_phase(PHASE_HOLDOFF);
890 TIMEOUT(holdoff_end, NULL, t);
892 if (sigsetjmp(sigjmp, 1) == 0) {
893 sigprocmask(SIG_BLOCK, &mask, NULL);
894 if (kill_link || got_sigchld) {
895 sigprocmask(SIG_UNBLOCK, &mask, NULL);
898 sigprocmask(SIG_UNBLOCK, &mask, NULL);
899 wait_input(timeleft(&timo));
906 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
910 } while (phase == PHASE_HOLDOFF);
916 /* Wait for scripts to finish */
917 /* XXX should have a timeout here */
918 while (n_children > 0) {
920 struct subprocess *chp;
921 dbglog("Waiting for %d child processes...", n_children);
922 for (chp = children; chp != NULL; chp = chp->next)
923 dbglog(" script %s, pid %d", chp->prog, chp->pid);
925 if (reap_kids(1) < 0)
934 * setup_signals - initialize signal handling.
943 * Compute mask of all interesting signals and install signal handlers
944 * for each. Only one signal handler may be active at a time. Therefore,
945 * all other signals should be masked when any handler is executing.
948 sigaddset(&mask, SIGHUP);
949 sigaddset(&mask, SIGINT);
950 sigaddset(&mask, SIGTERM);
951 sigaddset(&mask, SIGCHLD);
952 sigaddset(&mask, SIGUSR2);
954 #define SIGNAL(s, handler) do { \
955 sa.sa_handler = handler; \
956 if (sigaction(s, &sa, NULL) < 0) \
957 fatal("Couldn't establish signal handler (%d): %m", s); \
962 SIGNAL(SIGHUP, hup); /* Hangup */
963 SIGNAL(SIGINT, term); /* Interrupt */
964 SIGNAL(SIGTERM, term); /* Terminate */
965 SIGNAL(SIGCHLD, chld);
967 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
968 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
971 * Install a handler for other signals which would otherwise
972 * cause pppd to exit without cleaning up.
974 SIGNAL(SIGABRT, bad_signal);
975 SIGNAL(SIGALRM, bad_signal);
976 SIGNAL(SIGFPE, bad_signal);
977 SIGNAL(SIGILL, bad_signal);
978 SIGNAL(SIGPIPE, bad_signal);
979 SIGNAL(SIGQUIT, bad_signal);
980 SIGNAL(SIGSEGV, bad_signal);
982 SIGNAL(SIGBUS, bad_signal);
985 SIGNAL(SIGEMT, bad_signal);
988 SIGNAL(SIGPOLL, bad_signal);
991 SIGNAL(SIGPROF, bad_signal);
994 SIGNAL(SIGSYS, bad_signal);
997 SIGNAL(SIGTRAP, bad_signal);
1000 SIGNAL(SIGVTALRM, bad_signal);
1003 SIGNAL(SIGXCPU, bad_signal);
1006 SIGNAL(SIGXFSZ, bad_signal);
1010 * Apparently we can get a SIGPIPE when we call syslog, if
1011 * syslogd has died and been restarted. Ignoring it seems
1014 signal(SIGPIPE, SIG_IGN);
1018 * set_ifunit - do things we need to do once we know which ppp
1019 * unit we are using.
1025 info("Using interface %s%d", PPP_DRV_NAME, ifunit);
1026 slprintf(ifname, sizeof(ifname), PPP_DRV_NAME "%d", ifunit);
1027 script_setenv("IFNAME", ifname, iskey);
1029 create_pidfile(); /* write pid to file */
1030 create_linkpidfile();
1035 * detach - detach us from the controlling terminal.
1045 if ((pid = fork()) < 0) {
1046 error("Couldn't detach (fork failed: %m)");
1047 die(1); /* or just return? */
1053 exit(0); /* parent dies */
1061 if (!log_to_file && !log_to_specific_fd)
1063 /* update pid files if they have been written already */
1067 create_linkpidfile();
1068 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1069 script_setenv("PPPD_PID", numbuf, 1);
1073 * reopen_log - (re)open our connection to syslog.
1079 openlog("pppd", LOG_PID);
1081 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1082 setlogmask(LOG_UPTO(LOG_INFO));
1087 * Create a file containing our process ID.
1094 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1095 _PATH_VARRUN, ifname);
1096 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1097 fprintf(pidfile, "%d\n", getpid());
1098 (void) fclose(pidfile);
1100 error("Failed to create pid file %s: %m", pidfilename);
1106 create_linkpidfile()
1110 if (linkname[0] == 0)
1112 script_setenv("LINKNAME", linkname, 1);
1113 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1114 _PATH_VARRUN, linkname);
1115 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1116 fprintf(pidfile, "%d\n", getpid());
1118 fprintf(pidfile, "%s\n", ifname);
1119 (void) fclose(pidfile);
1121 error("Failed to create pid file %s: %m", linkpidfile);
1127 * holdoff_end - called via a timeout when the holdoff period ends.
1133 new_phase(PHASE_DORMANT);
1136 /* List of protocol names, to make our messages a little more informative. */
1137 struct protocol_list {
1140 } protocol_list[] = {
1142 { 0x23, "OSI Network Layer" },
1143 { 0x25, "Xerox NS IDP" },
1144 { 0x27, "DECnet Phase IV" },
1145 { 0x29, "Appletalk" },
1146 { 0x2b, "Novell IPX" },
1147 { 0x2d, "VJ compressed TCP/IP" },
1148 { 0x2f, "VJ uncompressed TCP/IP" },
1149 { 0x31, "Bridging PDU" },
1150 { 0x33, "Stream Protocol ST-II" },
1151 { 0x35, "Banyan Vines" },
1152 { 0x39, "AppleTalk EDDP" },
1153 { 0x3b, "AppleTalk SmartBuffered" },
1154 { 0x3d, "Multi-Link" },
1155 { 0x3f, "NETBIOS Framing" },
1156 { 0x41, "Cisco Systems" },
1157 { 0x43, "Ascom Timeplex" },
1158 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
1159 { 0x47, "DCA Remote Lan" },
1160 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
1161 { 0x4b, "SNA over 802.2" },
1163 { 0x4f, "IP6 Header Compression" },
1164 { 0x6f, "Stampede Bridging" },
1165 { 0xfb, "single-link compression" },
1166 { 0xfd, "1st choice compression" },
1167 { 0x0201, "802.1d Hello Packets" },
1168 { 0x0203, "IBM Source Routing BPDU" },
1169 { 0x0205, "DEC LANBridge100 Spanning Tree" },
1170 { 0x0231, "Luxcom" },
1171 { 0x0233, "Sigma Network Systems" },
1172 { 0x8021, "Internet Protocol Control Protocol" },
1173 { 0x8023, "OSI Network Layer Control Protocol" },
1174 { 0x8025, "Xerox NS IDP Control Protocol" },
1175 { 0x8027, "DECnet Phase IV Control Protocol" },
1176 { 0x8029, "Appletalk Control Protocol" },
1177 { 0x802b, "Novell IPX Control Protocol" },
1178 { 0x8031, "Bridging NCP" },
1179 { 0x8033, "Stream Protocol Control Protocol" },
1180 { 0x8035, "Banyan Vines Control Protocol" },
1181 { 0x803d, "Multi-Link Control Protocol" },
1182 { 0x803f, "NETBIOS Framing Control Protocol" },
1183 { 0x8041, "Cisco Systems Control Protocol" },
1184 { 0x8043, "Ascom Timeplex" },
1185 { 0x8045, "Fujitsu LBLB Control Protocol" },
1186 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
1187 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
1188 { 0x804b, "SNA over 802.2 Control Protocol" },
1189 { 0x804d, "SNA Control Protocol" },
1190 { 0x804f, "IP6 Header Compression Control Protocol" },
1191 { 0x006f, "Stampede Bridging Control Protocol" },
1192 { 0x80fb, "Single Link Compression Control Protocol" },
1193 { 0x80fd, "Compression Control Protocol" },
1194 { 0xc021, "Link Control Protocol" },
1195 { 0xc023, "Password Authentication Protocol" },
1196 { 0xc025, "Link Quality Report" },
1197 { 0xc027, "Shiva Password Authentication Protocol" },
1198 { 0xc029, "CallBack Control Protocol (CBCP)" },
1199 { 0xc081, "Container Control Protocol" },
1200 { 0xc223, "Challenge Handshake Authentication Protocol" },
1201 { 0xc281, "Proprietary Authentication Protocol" },
1206 * protocol_name - find a name for a PPP protocol.
1209 protocol_name(proto)
1212 struct protocol_list *lp;
1214 for (lp = protocol_list; lp->proto != 0; ++lp)
1215 if (proto == lp->proto)
1221 * get_input - called when incoming data is available.
1229 struct protent *protp;
1231 p = inpacket_buf; /* point to beginning of packet buffer */
1233 len = read_packet(inpacket_buf);
1238 notice("Modem hangup");
1240 status = EXIT_HANGUP;
1241 lcp_lowerdown(0); /* serial link is no longer available */
1246 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1247 dbglog("rcvd %P", p, len);
1249 if (len < PPP_HDRLEN) {
1250 MAINDEBUG(("io(): Received short packet."));
1254 p += 2; /* Skip address and control */
1255 GETSHORT(protocol, p);
1259 * Toss all non-LCP packets unless LCP is OPEN.
1261 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1262 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1267 * Until we get past the authentication phase, toss all packets
1268 * except LCP, LQR and authentication packets.
1270 if (phase <= PHASE_AUTHENTICATE
1271 && !(protocol == PPP_LCP || protocol == PPP_LQR
1272 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1273 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1279 * Upcall the proper protocol input routine.
1281 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1282 if (protp->protocol == protocol && protp->enabled_flag) {
1283 (*protp->input)(0, p, len);
1286 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1287 && protp->datainput != NULL) {
1288 (*protp->datainput)(0, p, len);
1294 const char *pname = protocol_name(protocol);
1296 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1298 warn("Unsupported protocol 0x%x received", protocol);
1300 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1304 * new_phase - signal the start of a new phase of pppd's operation.
1312 (*new_phase_hook)(p);
1316 * die - clean up state and exit with the specified status.
1323 syslog(LOG_INFO, "Exit.");
1328 * cleanup - restore anything which needs to be restored before we exit
1337 disestablish_ppp(ttyfd);
1338 if (real_ttyfd >= 0)
1341 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1342 warn("unable to delete pid file %s: %m", pidfilename);
1344 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1345 warn("unable to delete pid file %s: %m", linkpidfile);
1356 * close_tty - restore the terminal device and close it.
1361 /* drop dtr to hang up */
1362 if (!default_device && modem) {
1363 setdtr(real_ttyfd, 0);
1365 * This sleep is in case the serial port has CLOCAL set by default,
1366 * and consequently will reassert DTR when we close the device.
1371 restore_tty(real_ttyfd);
1373 if (tty_mode != (mode_t) -1) {
1374 if (fchmod(real_ttyfd, tty_mode) != 0) {
1375 /* XXX if devnam is a symlink, this will change the link */
1376 chmod(devnam, tty_mode);
1385 * update_link_stats - get stats at link termination.
1388 update_link_stats(u)
1394 if (!get_ppp_stats(u, &link_stats)
1395 || gettimeofday(&now, NULL) < 0)
1397 link_connect_time = now.tv_sec - start_time.tv_sec;
1398 link_stats_valid = 1;
1400 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1401 script_setenv("CONNECT_TIME", numbuf, 0);
1402 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1403 script_setenv("BYTES_SENT", numbuf, 0);
1404 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1405 script_setenv("BYTES_RCVD", numbuf, 0);
1410 struct timeval c_time; /* time at which to call routine */
1411 void *c_arg; /* argument to routine */
1412 void (*c_func) __P((void *)); /* routine */
1413 struct callout *c_next;
1416 static struct callout *callout = NULL; /* Callout list */
1417 static struct timeval timenow; /* Current time */
1420 * timeout - Schedule a timeout.
1422 * Note that this timeout takes the number of seconds, NOT hz (as in
1426 timeout(func, arg, time)
1427 void (*func) __P((void *));
1431 struct callout *newp, *p, **pp;
1433 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1438 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1439 fatal("Out of memory in timeout()!");
1441 newp->c_func = func;
1442 gettimeofday(&timenow, NULL);
1443 newp->c_time.tv_sec = timenow.tv_sec + time;
1444 newp->c_time.tv_usec = timenow.tv_usec;
1447 * Find correct place and link it in.
1449 for (pp = &callout; (p = *pp); pp = &p->c_next)
1450 if (newp->c_time.tv_sec < p->c_time.tv_sec
1451 || (newp->c_time.tv_sec == p->c_time.tv_sec
1452 && newp->c_time.tv_usec < p->c_time.tv_usec))
1460 * untimeout - Unschedule a timeout.
1463 untimeout(func, arg)
1464 void (*func) __P((void *));
1467 struct callout **copp, *freep;
1469 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1472 * Find first matching timeout and remove it from the list.
1474 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1475 if (freep->c_func == func && freep->c_arg == arg) {
1476 *copp = freep->c_next;
1477 free((char *) freep);
1484 * calltimeout - Call any timeout routines which are now due.
1491 while (callout != NULL) {
1494 if (gettimeofday(&timenow, NULL) < 0)
1495 fatal("Failed to get time of day: %m");
1496 if (!(p->c_time.tv_sec < timenow.tv_sec
1497 || (p->c_time.tv_sec == timenow.tv_sec
1498 && p->c_time.tv_usec <= timenow.tv_usec)))
1499 break; /* no, it's not time yet */
1501 callout = p->c_next;
1502 (*p->c_func)(p->c_arg);
1510 * timeleft - return the length of time until the next timeout is due.
1512 static struct timeval *
1514 struct timeval *tvp;
1516 if (callout == NULL)
1519 gettimeofday(&timenow, NULL);
1520 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1521 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1522 if (tvp->tv_usec < 0) {
1523 tvp->tv_usec += 1000000;
1526 if (tvp->tv_sec < 0)
1527 tvp->tv_sec = tvp->tv_usec = 0;
1534 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1540 struct sigaction act, oldact;
1542 act.sa_handler = SIG_IGN;
1545 sigaction(sig, &act, &oldact);
1546 sigaction(sig, &oldact, NULL);
1551 * hup - Catch SIGHUP signal.
1553 * Indicates that the physical layer has been disconnected.
1554 * We don't rely on this indication; if the user has sent this
1555 * signal, we just take the link down.
1561 info("Hangup (SIGHUP)");
1563 if (status != EXIT_HANGUP)
1564 status = EXIT_USER_REQUEST;
1566 /* Send the signal to the [dis]connector process(es) also */
1569 kill(charshunt_pid, sig);
1571 siglongjmp(sigjmp, 1);
1576 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1578 * Indicates that we should initiate a graceful disconnect and exit.
1585 info("Terminating on signal %d.", sig);
1586 persist = 0; /* don't try to restart */
1588 status = EXIT_USER_REQUEST;
1590 /* Send the signal to the [dis]connector process(es) also */
1593 kill(charshunt_pid, sig);
1595 siglongjmp(sigjmp, 1);
1600 * chld - Catch SIGCHLD signal.
1601 * Sets a flag so we will call reap_kids in the mainline.
1609 siglongjmp(sigjmp, 1);
1614 * toggle_debug - Catch SIGUSR1 signal.
1616 * Toggle debug flag.
1625 setlogmask(LOG_UPTO(LOG_DEBUG));
1627 setlogmask(LOG_UPTO(LOG_WARNING));
1633 * open_ccp - Catch SIGUSR2 signal.
1635 * Try to (re)negotiate compression.
1644 siglongjmp(sigjmp, 1);
1649 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1655 static int crashed = 0;
1660 error("Fatal signal %d", sig);
1662 kill_my_pg(SIGTERM);
1664 kill(charshunt_pid, SIGTERM);
1670 * device_script - run a program to talk to the serial device
1671 * (e.g. to run the connector or disconnector script).
1674 device_script(program, in, out, dont_wait)
1688 error("Failed to create child process: %m");
1697 int newin = dup(in);
1701 } else if (out == 2) {
1704 if (log_to_fd >= 0) {
1709 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1710 if (errfd >= 0 && errfd != 2) {
1730 if (getuid() != uid) {
1731 error("setuid failed");
1735 execl("/bin/sh", "sh", "-c", program, (char *)0);
1736 error("could not exec /bin/sh: %m");
1742 record_child(pid, program, NULL, NULL);
1745 while (waitpid(pid, &status, 0) < 0) {
1748 fatal("error waiting for (dis)connection process: %m");
1753 return (status == 0 ? 0 : -1);
1758 * run-program - execute a program with given arguments,
1759 * but don't wait for it.
1760 * If the program can't be executed, logs an error unless
1761 * must_exist is 0 and the program file doesn't exist.
1762 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1763 * or isn't an executable plain file, or the process ID of the child.
1764 * If done != NULL, (*done)(arg) will be called later (within
1765 * reap_kids) iff the return value is > 0.
1768 run_program(prog, args, must_exist, done, arg)
1772 void (*done) __P((void *));
1779 * First check if the file exists and is executable.
1780 * We don't use access() because that would use the
1781 * real user-id, which might not be root, and the script
1782 * might be accessible only to root.
1785 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1786 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1787 if (must_exist || errno != ENOENT)
1788 warn("Can't execute %s: %m", prog);
1794 error("Failed to create child process for %s: %m", prog);
1800 /* Leave the current location */
1801 (void) setsid(); /* No controlling tty. */
1802 (void) umask (S_IRWXG|S_IRWXO);
1803 (void) chdir ("/"); /* no current directory. */
1804 setuid(0); /* set real UID = root */
1807 /* Ensure that nothing of our device environment is inherited. */
1813 close (ttyfd); /* tty interface to the ppp device */
1814 if (real_ttyfd >= 0)
1817 /* Don't pass handles to the PPP device, even by accident. */
1818 new_fd = open (_PATH_DEVNULL, O_RDWR);
1821 dup2 (new_fd, 0); /* stdin <- /dev/null */
1824 dup2 (0, 1); /* stdout -> /dev/null */
1825 dup2 (0, 2); /* stderr -> /dev/null */
1829 /* Force the priority back to zero if pppd is running higher. */
1830 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1831 warn("can't reset priority to 0: %m");
1834 /* SysV recommends a second fork at this point. */
1836 /* run the program */
1837 execve(prog, args, script_env);
1838 if (must_exist || errno != ENOENT) {
1839 /* have to reopen the log, there's nowhere else
1840 for the message to go. */
1842 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1849 dbglog("Script %s started (pid %d)", prog, pid);
1850 record_child(pid, prog, done, arg);
1857 * record_child - add a child process to the list for reap_kids
1861 record_child(pid, prog, done, arg)
1864 void (*done) __P((void *));
1867 struct subprocess *chp;
1871 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1873 warn("losing track of %s process", prog);
1879 chp->next = children;
1886 * reap_kids - get status from any dead child processes,
1887 * and log a message for abnormal terminations.
1894 struct subprocess *chp, **prevp;
1897 if (n_children == 0)
1899 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1901 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1902 if (chp->pid == pid) {
1908 if (WIFSIGNALED(status)) {
1909 warn("Child process %s (pid %d) terminated with signal %d",
1910 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1912 dbglog("Script %s finished (pid %d), status = 0x%x",
1913 (chp? chp->prog: "??"), pid, status);
1914 if (chp && chp->done)
1915 (*chp->done)(chp->arg);
1920 if (errno == ECHILD)
1923 error("Error waiting for child process: %m");
1930 * novm - log an error message saying we ran out of memory, and die.
1936 fatal("Virtual memory exhausted allocating %s\n", msg);
1940 * script_setenv - set an environment variable value to be used
1941 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1944 script_setenv(var, value, iskey)
1948 size_t varl = strlen(var);
1949 size_t vl = varl + strlen(value) + 2;
1951 char *p, *newstring;
1953 newstring = (char *) malloc(vl+1);
1956 *newstring++ = iskey;
1957 slprintf(newstring, vl, "%s=%s", var, value);
1959 /* check if this variable is already set */
1960 if (script_env != 0) {
1961 for (i = 0; (p = script_env[i]) != 0; ++i) {
1962 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1963 if (p[-1] && pppdb != NULL)
1966 script_env[i] = newstring;
1967 if (iskey && pppdb != NULL)
1968 add_db_key(newstring);
1974 /* no space allocated for script env. ptrs. yet */
1976 script_env = (char **) malloc(16 * sizeof(char *));
1977 if (script_env == 0)
1982 /* reallocate script_env with more space if needed */
1983 if (i + 1 >= s_env_nalloc) {
1985 char **newenv = (char **) realloc((void *)script_env,
1986 new_n * sizeof(char *));
1989 script_env = newenv;
1990 s_env_nalloc = new_n;
1993 script_env[i] = newstring;
1994 script_env[i+1] = 0;
1996 if (pppdb != NULL) {
1998 add_db_key(newstring);
2004 * script_unsetenv - remove a variable from the environment
2008 script_unsetenv(var)
2011 int vl = strlen(var);
2015 if (script_env == 0)
2017 for (i = 0; (p = script_env[i]) != 0; ++i) {
2018 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2019 if (p[-1] && pppdb != NULL)
2022 while ((script_env[i] = script_env[i+1]) != 0)
2032 * update_db_entry - update our entry in the database.
2041 if (script_env == NULL)
2044 for (i = 0; (p = script_env[i]) != 0; ++i)
2045 vlen += strlen(p) + 1;
2046 vbuf = malloc(vlen);
2048 novm("database entry");
2050 for (i = 0; (p = script_env[i]) != 0; ++i)
2051 q += slprintf(q, vbuf + vlen - q, "%s;", p);
2054 key.dsize = strlen(db_key);
2057 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2058 error("tdb_store failed: %s", tdb_error(pppdb));
2063 * add_db_key - add a key that we can use to look up our database entry.
2071 key.dptr = (char *) str;
2072 key.dsize = strlen(str);
2074 dbuf.dsize = strlen(db_key);
2075 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2076 error("tdb_store key failed: %s", tdb_error(pppdb));
2080 * delete_db_key - delete a key for looking up our database entry.
2088 key.dptr = (char *) str;
2089 key.dsize = strlen(str);
2090 tdb_delete(pppdb, key);
2094 * cleanup_db - delete all the entries we put in the database.
2104 key.dsize = strlen(db_key);
2105 tdb_delete(pppdb, key);
2106 for (i = 0; (p = script_env[i]) != 0; ++i)
2112 * open_socket - establish a stream socket connection to the nominated
2119 char *sep, *endp = NULL;
2120 int sock, port = -1;
2122 struct hostent *hent;
2123 struct sockaddr_in sad;
2125 /* parse host:port and resolve host to an IP address */
2126 sep = strchr(dest, ':');
2128 port = strtol(sep+1, &endp, 10);
2129 if (port < 0 || endp == sep+1 || sep == dest) {
2130 error("Can't parse host:port for socket destination");
2134 host = inet_addr(dest);
2135 if (host == (u_int32_t) -1) {
2136 hent = gethostbyname(dest);
2138 error("%s: unknown host in socket option", dest);
2142 host = *(u_int32_t *)(hent->h_addr_list[0]);
2146 /* get a socket and connect it to the other end */
2147 sock = socket(PF_INET, SOCK_STREAM, 0);
2149 error("Can't create socket: %m");
2152 memset(&sad, 0, sizeof(sad));
2153 sad.sin_family = AF_INET;
2154 sad.sin_port = htons(port);
2155 sad.sin_addr.s_addr = host;
2156 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
2157 error("Can't connect to %s: %m", dest);
2166 * start_charshunt - create a child process to run the character shunt.
2169 start_charshunt(ifd, ofd)
2176 error("Can't fork process for character shunt: %m");
2183 if (getuid() != uid)
2184 fatal("setuid failed");
2188 charshunt(ifd, ofd, record_file);
2191 charshunt_pid = cpid;
2195 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2207 * charshunt - the character shunt, which passes characters between
2208 * the pty master side and the serial port (or stdin/stdout).
2209 * This runs as the user (not as root).
2210 * (We assume ofd >= ifd which is true the way this gets called. :-).
2213 charshunt(ifd, ofd, record_file)
2218 fd_set ready, writey;
2219 u_char *ibufp, *obufp;
2222 int pty_readable, stdin_readable;
2223 struct timeval lasttime;
2224 FILE *recordf = NULL;
2225 int ilevel, olevel, max_level;
2226 struct timeval levelt, tout, *top;
2229 * Reset signal handlers.
2231 signal(SIGHUP, SIG_IGN); /* Hangup */
2232 signal(SIGINT, SIG_DFL); /* Interrupt */
2233 signal(SIGTERM, SIG_DFL); /* Terminate */
2234 signal(SIGCHLD, SIG_DFL);
2235 signal(SIGUSR1, SIG_DFL);
2236 signal(SIGUSR2, SIG_DFL);
2237 signal(SIGABRT, SIG_DFL);
2238 signal(SIGALRM, SIG_DFL);
2239 signal(SIGFPE, SIG_DFL);
2240 signal(SIGILL, SIG_DFL);
2241 signal(SIGPIPE, SIG_DFL);
2242 signal(SIGQUIT, SIG_DFL);
2243 signal(SIGSEGV, SIG_DFL);
2245 signal(SIGBUS, SIG_DFL);
2248 signal(SIGEMT, SIG_DFL);
2251 signal(SIGPOLL, SIG_DFL);
2254 signal(SIGPROF, SIG_DFL);
2257 signal(SIGSYS, SIG_DFL);
2260 signal(SIGTRAP, SIG_DFL);
2263 signal(SIGVTALRM, SIG_DFL);
2266 signal(SIGXCPU, SIG_DFL);
2269 signal(SIGXFSZ, SIG_DFL);
2273 * Open the record file if required.
2275 if (record_file != NULL) {
2276 recordf = fopen(record_file, "a");
2277 if (recordf == NULL)
2278 error("Couldn't create record file %s: %m", record_file);
2281 /* set all the fds to non-blocking mode */
2282 flags = fcntl(pty_master, F_GETFL);
2284 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2285 warn("couldn't set pty master to nonblock: %m");
2286 flags = fcntl(ifd, F_GETFL);
2288 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2289 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2291 flags = fcntl(ofd, F_GETFL);
2293 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2294 warn("couldn't set stdout to nonblock: %m");
2298 ibufp = obufp = NULL;
2299 pty_readable = stdin_readable = 1;
2301 ilevel = olevel = 0;
2302 gettimeofday(&levelt, NULL);
2303 if (max_data_rate) {
2304 max_level = max_data_rate / 10;
2305 if (max_level < 100)
2308 max_level = sizeof(inpacket_buf) + 1;
2310 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2311 if (recordf != NULL) {
2312 gettimeofday(&lasttime, NULL);
2313 putc(7, recordf); /* put start marker */
2314 putc(lasttime.tv_sec >> 24, recordf);
2315 putc(lasttime.tv_sec >> 16, recordf);
2316 putc(lasttime.tv_sec >> 8, recordf);
2317 putc(lasttime.tv_sec, recordf);
2318 lasttime.tv_usec = 0;
2321 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2324 tout.tv_usec = 10000;
2328 if (ilevel >= max_level)
2331 FD_SET(pty_master, &writey);
2332 } else if (stdin_readable)
2333 FD_SET(ifd, &ready);
2335 if (olevel >= max_level)
2338 FD_SET(ofd, &writey);
2339 } else if (pty_readable)
2340 FD_SET(pty_master, &ready);
2341 if (select(nfds, &ready, &writey, NULL, top) < 0) {
2346 if (max_data_rate) {
2351 gettimeofday(&now, NULL);
2352 dt = (now.tv_sec - levelt.tv_sec
2353 + (now.tv_usec - levelt.tv_usec) / 1e6);
2354 nbt = (int)(dt * max_data_rate);
2355 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2356 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2359 ilevel = olevel = 0;
2360 if (FD_ISSET(ifd, &ready)) {
2361 ibufp = inpacket_buf;
2362 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2363 if (nibuf < 0 && errno == EIO)
2366 if (!(errno == EINTR || errno == EAGAIN)) {
2367 error("Error reading standard input: %m");
2371 } else if (nibuf == 0) {
2372 /* end of file from stdin */
2374 /* do a 0-length write, hopefully this will generate
2375 an EOF (hangup) on the slave side. */
2376 write(pty_master, inpacket_buf, 0);
2378 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2381 FD_SET(pty_master, &writey);
2383 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2387 if (FD_ISSET(pty_master, &ready)) {
2388 obufp = outpacket_buf;
2389 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2390 if (nobuf < 0 && errno == EIO)
2393 if (!(errno == EINTR || errno == EAGAIN)) {
2394 error("Error reading pseudo-tty master: %m");
2398 } else if (nobuf == 0) {
2399 /* end of file from the pty - slave side has closed */
2401 stdin_readable = 0; /* pty is not writable now */
2405 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2408 FD_SET(ofd, &writey);
2410 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2414 if (FD_ISSET(ofd, &writey)) {
2416 if (olevel + n > max_level)
2417 n = max_level - olevel;
2418 n = write(ofd, obufp, n);
2421 error("Error writing standard output: %m");
2432 if (FD_ISSET(pty_master, &writey)) {
2434 if (ilevel + n > max_level)
2435 n = max_level - ilevel;
2436 n = write(pty_master, ibufp, n);
2439 error("Error writing pseudo-tty master: %m");
2455 record_write(f, code, buf, nb, tp)
2465 gettimeofday(&now, NULL);
2466 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2467 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2471 putc(diff >> 24, f);
2472 putc(diff >> 16, f);
2485 fwrite(buf, nb, 1, f);
2489 error("Error writing record file: %m");