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.92 2000/04/04 07:06:51 paulus 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 = -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 int open_socket __P((char *));
183 static int start_charshunt __P((int, int));
184 static void charshunt_done __P((void *));
185 static void charshunt __P((int, int, char *));
186 static int record_write __P((FILE *, int code, u_char *buf, int nb,
189 extern char *ttyname __P((int));
190 extern char *getlogin __P((void));
191 int main __P((int, char *[]));
195 #define O_NONBLOCK O_NDELAY
199 #define setlogmask(x)
203 * PPP Data Link Layer "protocol" table.
204 * One entry per supported protocol.
205 * The last entry must be NULL.
207 struct protent *protocols[] = {
238 struct protent *protp;
242 new_phase(PHASE_INITIALIZE);
245 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
246 * This way we can close 0, 1, 2 in detach() without clobbering
247 * a fd that we are using.
249 if ((i = open("/dev/null", O_RDWR)) >= 0) {
250 while (0 <= i && i <= 2)
258 /* Initialize syslog facilities */
261 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
262 option_error("Couldn't get hostname: %m");
265 hostname[MAXNAMELEN-1] = 0;
267 /* make sure we don't create world or group writable files. */
268 umask(umask(0777) | 022);
271 privileged = uid == 0;
272 slprintf(numbuf, sizeof(numbuf), "%d", uid);
273 script_setenv("ORIG_UID", numbuf, 0);
275 ngroups = getgroups(NGROUPS_MAX, groups);
278 * Initialize magic number generator now so that protocols may
279 * use magic numbers in initialization.
284 * Initialize to the standard option set, then parse, in order,
285 * the system options file, the user's options file,
286 * the tty's options file, and the command line arguments.
288 for (i = 0; (protp = protocols[i]) != NULL; ++i)
294 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
295 || !options_from_user())
296 exit(EXIT_OPTION_ERROR);
298 /* scan command line and options files to find device name */
300 parse_args(argc-1, argv+1);
304 * Work out the device name, if it hasn't already been specified.
306 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
307 if (!using_pty && default_device) {
309 if (!isatty(0) || (p = ttyname(0)) == NULL) {
310 option_error("no device specified and stdin is not a tty");
311 exit(EXIT_OPTION_ERROR);
313 strlcpy(devnam, p, sizeof(devnam));
314 if (stat(devnam, &devstat) < 0)
315 fatal("Couldn't stat default device %s: %m", devnam);
319 * Parse the tty options file and the command line.
320 * The per-tty options file should not change
321 * ptycommand, pty_socket, notty or devnam.
325 if (!options_for_tty())
326 exit(EXIT_OPTION_ERROR);
330 if (!parse_args(argc-1, argv+1))
331 exit(EXIT_OPTION_ERROR);
334 * Check that we are running as root.
336 if (geteuid() != 0) {
337 option_error("must be root to run %s, since it is not setuid-root",
342 if (!ppp_available()) {
343 option_error(no_ppp_msg);
344 exit(EXIT_NO_KERNEL_SUPPORT);
348 * Check that the options given are valid and consistent.
350 if (!sys_check_options())
351 exit(EXIT_OPTION_ERROR);
352 auth_check_options();
353 #ifdef HAVE_MULTILINK
356 for (i = 0; (protp = protocols[i]) != NULL; ++i)
357 if (protp->check_options != NULL)
358 (*protp->check_options)();
359 if (demand && connect_script == 0) {
360 option_error("connect script is required for demand-dialling\n");
361 exit(EXIT_OPTION_ERROR);
363 /* default holdoff to 0 if no connect script has been given */
364 if (connect_script == 0 && !holdoff_specified)
368 if (!default_device) {
369 option_error("%s option precludes specifying device name",
370 notty? "notty": "pty");
371 exit(EXIT_OPTION_ERROR);
373 if (ptycommand != NULL && notty) {
374 option_error("pty option is incompatible with notty option");
375 exit(EXIT_OPTION_ERROR);
377 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
378 option_error("socket option is incompatible with pty and notty");
379 exit(EXIT_OPTION_ERROR);
381 default_device = notty;
384 if (notty && log_to_fd <= 1)
388 * If the user has specified a device which is the same as
389 * the one on stdin, pretend they didn't specify any.
390 * If the device is already open read/write on stdin,
391 * we assume we don't need to lock it, and we can open it as root.
393 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
394 && statbuf.st_rdev == devstat.st_rdev) {
396 fdflags = fcntl(0, F_GETFL);
397 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
405 * Don't send log messages to the serial port, it tends to
406 * confuse the peer. :-)
408 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
409 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
413 * Initialize system-dependent stuff.
417 setlogmask(LOG_UPTO(LOG_DEBUG));
419 pppdb = tdb_open(_PATH_PPPDB, 0, TDB_CLEAR_IF_FIRST, O_RDWR|O_CREAT, 0644);
421 slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
424 warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
426 warn("Warning: disabling multilink");
432 * Detach ourselves from the terminal, if required,
433 * and identify who is running us.
435 if (!nodetach && !updetach)
440 if (pw != NULL && pw->pw_name != NULL)
445 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
446 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
447 script_setenv("PPPLOGNAME", p, 0);
450 script_setenv("DEVICE", devnam, 1);
456 create_linkpidfile();
459 * If we're doing dial-on-demand, set up the interface now.
463 * Open the loopback channel and set it up to be the ppp interface.
465 fd_loop = open_ppp_loopback();
469 * Configure the interface and mark it up, etc.
482 doing_callback = do_callback;
485 if (demand && !doing_callback) {
487 * Don't do anything until we see some activity.
490 new_phase(PHASE_DORMANT);
494 if (sigsetjmp(sigjmp, 1) == 0) {
495 sigprocmask(SIG_BLOCK, &mask, NULL);
496 if (kill_link || got_sigchld) {
497 sigprocmask(SIG_UNBLOCK, &mask, NULL);
500 sigprocmask(SIG_UNBLOCK, &mask, NULL);
501 wait_input(timeleft(&timo));
511 if (get_loop_output())
517 if (kill_link && !persist)
521 * Now we want to bring up the link.
524 info("Starting link");
527 new_phase(PHASE_SERIALCONN);
530 * Get a pty master/slave pair if the pty, notty, socket,
531 * or record options were specified.
533 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
536 if (using_pty || record_file != NULL) {
537 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
538 error("Couldn't allocate pseudo-tty");
539 status = EXIT_FATAL_ERROR;
542 set_up_tty(pty_slave, 1);
546 * Lock the device if we've been asked to.
548 status = EXIT_LOCK_FAILED;
549 if (lockflag && !privopen) {
550 if (lock(devnam) < 0)
556 * Open the serial device and set it up to be the ppp interface.
557 * First we open it in non-blocking mode so we can set the
558 * various termios flags appropriately. If we aren't dialling
559 * out and we want to use the modem lines, we reopen it later
560 * in order to wait for the carrier detect signal from the modem.
564 connector = doing_callback? callback_script: connect_script;
565 if (devnam[0] != 0) {
567 /* If the user specified the device name, become the
568 user before opening it. */
570 if (!devnam_info.priv && !privopen)
572 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
574 if (!devnam_info.priv && !privopen)
580 error("Failed to open %s: %m", devnam);
581 status = EXIT_OPEN_FAILED;
583 if (!persist || err != EINTR)
586 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
587 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
588 warn("Couldn't reset non-blocking mode on device: %m");
591 * Do the equivalent of `mesg n' to stop broadcast messages.
593 if (fstat(ttyfd, &statbuf) < 0
594 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
595 warn("Couldn't restrict write permissions to %s: %m", devnam);
597 tty_mode = statbuf.st_mode;
600 * Set line speed, flow control, etc.
601 * If we have a non-null connection or initializer script,
602 * on most systems we set CLOCAL for now so that we can talk
603 * to the modem before carrier comes up. But this has the
604 * side effect that we might miss it if CD drops before we
605 * get to clear CLOCAL below. On systems where we can talk
606 * successfully to the modem with CLOCAL clear and CD down,
607 * we could clear CLOCAL at this point.
609 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
610 || initializer != NULL));
615 * If the pty, socket, notty and/or record option was specified,
616 * start up the character shunt now.
618 status = EXIT_PTYCMD_FAILED;
619 if (ptycommand != NULL) {
620 if (record_file != NULL) {
621 int ipipe[2], opipe[2], ok;
623 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
624 fatal("Couldn't create pipes for record option: %m");
625 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
626 && start_charshunt(ipipe[0], opipe[1]);
634 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
640 } else if (pty_socket != NULL) {
641 int fd = open_socket(pty_socket);
644 if (!start_charshunt(fd, fd))
647 if (!start_charshunt(0, 1))
649 } else if (record_file != NULL) {
650 if (!start_charshunt(ttyfd, ttyfd))
654 /* run connection script */
655 if ((connector && connector[0]) || initializer) {
656 if (real_ttyfd != -1) {
657 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
658 if (!default_device && modem) {
659 setdtr(real_ttyfd, 0); /* in case modem is off hook */
661 setdtr(real_ttyfd, 1);
665 if (initializer && initializer[0]) {
666 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
667 error("Initializer script failed");
668 status = EXIT_INIT_FAILED;
674 info("Serial port initialized.");
677 if (connector && connector[0]) {
678 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
679 error("Connect script failed");
680 status = EXIT_CONNECT_FAILED;
686 info("Serial connection established.");
689 /* set line speed, flow control, etc.;
690 clear CLOCAL if modem option */
691 if (real_ttyfd != -1)
692 set_up_tty(real_ttyfd, 0);
694 if (doing_callback == CALLBACK_DIALIN)
698 /* reopen tty if necessary to wait for carrier */
699 if (connector == NULL && modem && devnam[0] != 0) {
701 if ((i = open(devnam, O_RDWR)) >= 0)
703 if (errno != EINTR) {
704 error("Failed to reopen %s: %m", devnam);
705 status = EXIT_OPEN_FAILED;
707 if (!persist || errno != EINTR || hungup || kill_link)
713 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
714 script_setenv("SPEED", numbuf, 0);
716 /* run welcome script, if any */
717 if (welcomer && welcomer[0]) {
718 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
719 warn("Welcome script failed");
722 /* set up the serial device as a ppp interface */
723 fd_ppp = establish_ppp(ttyfd);
725 status = EXIT_FATAL_ERROR;
729 if (!demand && ifunit >= 0)
733 * Start opening the connection and wait for
734 * incoming events (reply, timeout, etc.).
736 notice("Connect: %s <--> %s", ifname, ppp_devnam);
737 gettimeofday(&start_time, NULL);
738 link_stats_valid = 0;
739 script_unsetenv("CONNECT_TIME");
740 script_unsetenv("BYTES_SENT");
741 script_unsetenv("BYTES_RCVD");
745 * If we are initiating this connection, wait for a short
746 * time for something from the peer. This can avoid bouncing
747 * our packets off his tty before he has it set up.
750 if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
752 t.tv_sec = connect_delay / 1000;
753 t.tv_usec = connect_delay % 1000;
757 lcp_open(0); /* Start protocol */
759 status = EXIT_NEGOTIATION_FAILED;
760 new_phase(PHASE_ESTABLISH);
761 while (phase != PHASE_DEAD) {
762 if (sigsetjmp(sigjmp, 1) == 0) {
763 sigprocmask(SIG_BLOCK, &mask, NULL);
764 if (kill_link || open_ccp_flag || got_sigchld) {
765 sigprocmask(SIG_UNBLOCK, &mask, NULL);
768 sigprocmask(SIG_UNBLOCK, &mask, NULL);
769 wait_input(timeleft(&timo));
776 lcp_close(0, "User request");
780 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
781 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
782 (*ccp_protent.open)(0);
787 reap_kids(0); /* Don't leave dead kids lying around */
791 * Print connect time and statistics.
793 if (link_stats_valid) {
794 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
795 info("Connect time %d.%d minutes.", t/10, t%10);
796 info("Sent %d bytes, received %d bytes.",
797 link_stats.bytes_out, link_stats.bytes_in);
801 * Delete pid file before disestablishing ppp. Otherwise it
802 * can happen that another pppd gets the same unit and then
803 * we delete its pid file.
806 if (pidfilename[0] != 0
807 && unlink(pidfilename) < 0 && errno != ENOENT)
808 warn("unable to delete pid file %s: %m", pidfilename);
813 * If we may want to bring the link up again, transfer
814 * the ppp unit back to the loopback. Set the
815 * real serial device back to its normal mode of operation.
821 disestablish_ppp(ttyfd);
827 * Run disconnector script, if requested.
828 * XXX we may not be able to do this if the line has hung up!
831 if (disconnect_script && !hungup) {
832 new_phase(PHASE_DISCONNECT);
834 set_up_tty(real_ttyfd, 1);
835 if (device_script(disconnect_script, 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 %s: %m", pidfilename);
861 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
867 t = need_holdoff? holdoff: 0;
869 t = (*holdoff_hook)();
871 new_phase(PHASE_HOLDOFF);
872 TIMEOUT(holdoff_end, NULL, t);
874 if (sigsetjmp(sigjmp, 1) == 0) {
875 sigprocmask(SIG_BLOCK, &mask, NULL);
876 if (kill_link || got_sigchld) {
877 sigprocmask(SIG_UNBLOCK, &mask, NULL);
880 sigprocmask(SIG_UNBLOCK, &mask, NULL);
881 wait_input(timeleft(&timo));
888 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
892 } while (phase == PHASE_HOLDOFF);
898 /* Wait for scripts to finish */
899 /* XXX should have a timeout here */
900 while (n_children > 0) {
902 struct subprocess *chp;
903 dbglog("Waiting for %d child processes...", n_children);
904 for (chp = children; chp != NULL; chp = chp->next)
905 dbglog(" script %s, pid %d", chp->prog, chp->pid);
907 if (reap_kids(1) < 0)
916 * setup_signals - initialize signal handling.
925 * Compute mask of all interesting signals and install signal handlers
926 * for each. Only one signal handler may be active at a time. Therefore,
927 * all other signals should be masked when any handler is executing.
930 sigaddset(&mask, SIGHUP);
931 sigaddset(&mask, SIGINT);
932 sigaddset(&mask, SIGTERM);
933 sigaddset(&mask, SIGCHLD);
934 sigaddset(&mask, SIGUSR2);
936 #define SIGNAL(s, handler) do { \
937 sa.sa_handler = handler; \
938 if (sigaction(s, &sa, NULL) < 0) \
939 fatal("Couldn't establish signal handler (%d): %m", s); \
944 SIGNAL(SIGHUP, hup); /* Hangup */
945 SIGNAL(SIGINT, term); /* Interrupt */
946 SIGNAL(SIGTERM, term); /* Terminate */
947 SIGNAL(SIGCHLD, chld);
949 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
950 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
953 * Install a handler for other signals which would otherwise
954 * cause pppd to exit without cleaning up.
956 SIGNAL(SIGABRT, bad_signal);
957 SIGNAL(SIGALRM, bad_signal);
958 SIGNAL(SIGFPE, bad_signal);
959 SIGNAL(SIGILL, bad_signal);
960 SIGNAL(SIGPIPE, bad_signal);
961 SIGNAL(SIGQUIT, bad_signal);
962 SIGNAL(SIGSEGV, bad_signal);
964 SIGNAL(SIGBUS, bad_signal);
967 SIGNAL(SIGEMT, bad_signal);
970 SIGNAL(SIGPOLL, bad_signal);
973 SIGNAL(SIGPROF, bad_signal);
976 SIGNAL(SIGSYS, bad_signal);
979 SIGNAL(SIGTRAP, bad_signal);
982 SIGNAL(SIGVTALRM, bad_signal);
985 SIGNAL(SIGXCPU, bad_signal);
988 SIGNAL(SIGXFSZ, bad_signal);
992 * Apparently we can get a SIGPIPE when we call syslog, if
993 * syslogd has died and been restarted. Ignoring it seems
996 signal(SIGPIPE, SIG_IGN);
1000 * set_ifunit - do things we need to do once we know which ppp
1001 * unit we are using.
1007 info("Using interface ppp%d", ifunit);
1008 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
1009 script_setenv("IFNAME", ifname, iskey);
1010 create_pidfile(); /* write pid to file */
1011 create_linkpidfile();
1015 * detach - detach us from the controlling terminal.
1024 if ((pid = fork()) < 0) {
1025 error("Couldn't detach (fork failed: %m)");
1026 die(1); /* or just return? */
1032 exit(0); /* parent dies */
1041 /* update pid files if they have been written already */
1045 create_linkpidfile();
1049 * reopen_log - (re)open our connection to syslog.
1055 openlog("pppd", LOG_PID);
1057 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1058 setlogmask(LOG_UPTO(LOG_INFO));
1063 * Create a file containing our process ID.
1071 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1072 _PATH_VARRUN, ifname);
1073 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1074 fprintf(pidfile, "%d\n", getpid());
1075 (void) fclose(pidfile);
1077 error("Failed to create pid file %s: %m", pidfilename);
1080 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1081 script_setenv("PPPD_PID", numbuf, 1);
1085 create_linkpidfile()
1089 if (linkname[0] == 0)
1091 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1092 _PATH_VARRUN, linkname);
1093 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1094 fprintf(pidfile, "%d\n", getpid());
1096 fprintf(pidfile, "%s\n", ifname);
1097 (void) fclose(pidfile);
1099 error("Failed to create pid file %s: %m", linkpidfile);
1102 script_setenv("LINKNAME", linkname, 1);
1106 * holdoff_end - called via a timeout when the holdoff period ends.
1112 new_phase(PHASE_DORMANT);
1115 /* List of protocol names, to make our messages a little more informative. */
1116 struct protocol_list {
1119 } protocol_list[] = {
1121 { 0x23, "OSI Network Layer" },
1122 { 0x25, "Xerox NS IDP" },
1123 { 0x27, "DECnet Phase IV" },
1124 { 0x29, "Appletalk" },
1125 { 0x2b, "Novell IPX" },
1126 { 0x2d, "VJ compressed TCP/IP" },
1127 { 0x2f, "VJ uncompressed TCP/IP" },
1128 { 0x31, "Bridging PDU" },
1129 { 0x33, "Stream Protocol ST-II" },
1130 { 0x35, "Banyan Vines" },
1131 { 0x39, "AppleTalk EDDP" },
1132 { 0x3b, "AppleTalk SmartBuffered" },
1133 { 0x3d, "Multi-Link" },
1134 { 0x3f, "NETBIOS Framing" },
1135 { 0x41, "Cisco Systems" },
1136 { 0x43, "Ascom Timeplex" },
1137 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
1138 { 0x47, "DCA Remote Lan" },
1139 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
1140 { 0x4b, "SNA over 802.2" },
1142 { 0x4f, "IP6 Header Compression" },
1143 { 0x6f, "Stampede Bridging" },
1144 { 0xfb, "single-link compression" },
1145 { 0xfd, "1st choice compression" },
1146 { 0x0201, "802.1d Hello Packets" },
1147 { 0x0203, "IBM Source Routing BPDU" },
1148 { 0x0205, "DEC LANBridge100 Spanning Tree" },
1149 { 0x0231, "Luxcom" },
1150 { 0x0233, "Sigma Network Systems" },
1151 { 0x8021, "Internet Protocol Control Protocol" },
1152 { 0x8023, "OSI Network Layer Control Protocol" },
1153 { 0x8025, "Xerox NS IDP Control Protocol" },
1154 { 0x8027, "DECnet Phase IV Control Protocol" },
1155 { 0x8029, "Appletalk Control Protocol" },
1156 { 0x802b, "Novell IPX Control Protocol" },
1157 { 0x8031, "Bridging NCP" },
1158 { 0x8033, "Stream Protocol Control Protocol" },
1159 { 0x8035, "Banyan Vines Control Protocol" },
1160 { 0x803d, "Multi-Link Control Protocol" },
1161 { 0x803f, "NETBIOS Framing Control Protocol" },
1162 { 0x8041, "Cisco Systems Control Protocol" },
1163 { 0x8043, "Ascom Timeplex" },
1164 { 0x8045, "Fujitsu LBLB Control Protocol" },
1165 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
1166 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
1167 { 0x804b, "SNA over 802.2 Control Protocol" },
1168 { 0x804d, "SNA Control Protocol" },
1169 { 0x804f, "IP6 Header Compression Control Protocol" },
1170 { 0x006f, "Stampede Bridging Control Protocol" },
1171 { 0x80fb, "Single Link Compression Control Protocol" },
1172 { 0x80fd, "Compression Control Protocol" },
1173 { 0xc021, "Link Control Protocol" },
1174 { 0xc023, "Password Authentication Protocol" },
1175 { 0xc025, "Link Quality Report" },
1176 { 0xc027, "Shiva Password Authentication Protocol" },
1177 { 0xc029, "CallBack Control Protocol (CBCP)" },
1178 { 0xc081, "Container Control Protocol" },
1179 { 0xc223, "Challenge Handshake Authentication Protocol" },
1180 { 0xc281, "Proprietary Authentication Protocol" },
1185 * protocol_name - find a name for a PPP protocol.
1188 protocol_name(proto)
1191 struct protocol_list *lp;
1193 for (lp = protocol_list; lp->proto != 0; ++lp)
1194 if (proto == lp->proto)
1200 * get_input - called when incoming data is available.
1208 struct protent *protp;
1210 p = inpacket_buf; /* point to beginning of packet buffer */
1212 len = read_packet(inpacket_buf);
1217 notice("Modem hangup");
1219 status = EXIT_HANGUP;
1220 lcp_lowerdown(0); /* serial link is no longer available */
1225 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1226 dbglog("rcvd %P", p, len);
1228 if (len < PPP_HDRLEN) {
1229 MAINDEBUG(("io(): Received short packet."));
1233 p += 2; /* Skip address and control */
1234 GETSHORT(protocol, p);
1238 * Toss all non-LCP packets unless LCP is OPEN.
1240 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1241 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1246 * Until we get past the authentication phase, toss all packets
1247 * except LCP, LQR and authentication packets.
1249 if (phase <= PHASE_AUTHENTICATE
1250 && !(protocol == PPP_LCP || protocol == PPP_LQR
1251 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1252 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1258 * Upcall the proper protocol input routine.
1260 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1261 if (protp->protocol == protocol && protp->enabled_flag) {
1262 (*protp->input)(0, p, len);
1265 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1266 && protp->datainput != NULL) {
1267 (*protp->datainput)(0, p, len);
1273 const char *pname = protocol_name(protocol);
1275 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1277 warn("Unsupported protocol 0x%x received", protocol);
1279 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1283 * new_phase - signal the start of a new phase of pppd's operation.
1291 (*new_phase_hook)(p);
1295 * die - clean up state and exit with the specified status.
1302 syslog(LOG_INFO, "Exit.");
1307 * cleanup - restore anything which needs to be restored before we exit
1316 disestablish_ppp(ttyfd);
1317 if (real_ttyfd >= 0)
1320 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1321 warn("unable to delete pid file %s: %m", pidfilename);
1323 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1324 warn("unable to delete pid file %s: %m", linkpidfile);
1330 if (pppdb != NULL) {
1334 key.dsize = strlen(db_key);
1335 tdb_delete(pppdb, key);
1340 * close_tty - restore the terminal device and close it.
1345 /* drop dtr to hang up */
1346 if (!default_device && modem) {
1347 setdtr(real_ttyfd, 0);
1349 * This sleep is in case the serial port has CLOCAL set by default,
1350 * and consequently will reassert DTR when we close the device.
1355 restore_tty(real_ttyfd);
1357 if (tty_mode != (mode_t) -1) {
1358 if (fchmod(real_ttyfd, tty_mode) != 0) {
1359 /* XXX if devnam is a symlink, this will change the link */
1360 chmod(devnam, tty_mode);
1369 * update_link_stats - get stats at link termination.
1372 update_link_stats(u)
1378 if (!get_ppp_stats(u, &link_stats)
1379 || gettimeofday(&now, NULL) < 0)
1381 link_connect_time = now.tv_sec - start_time.tv_sec;
1382 link_stats_valid = 1;
1384 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1385 script_setenv("CONNECT_TIME", numbuf, 0);
1386 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1387 script_setenv("BYTES_SENT", numbuf, 0);
1388 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1389 script_setenv("BYTES_RCVD", numbuf, 0);
1394 struct timeval c_time; /* time at which to call routine */
1395 void *c_arg; /* argument to routine */
1396 void (*c_func) __P((void *)); /* routine */
1397 struct callout *c_next;
1400 static struct callout *callout = NULL; /* Callout list */
1401 static struct timeval timenow; /* Current time */
1404 * timeout - Schedule a timeout.
1406 * Note that this timeout takes the number of seconds, NOT hz (as in
1410 timeout(func, arg, time)
1411 void (*func) __P((void *));
1415 struct callout *newp, *p, **pp;
1417 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1422 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1423 fatal("Out of memory in timeout()!");
1425 newp->c_func = func;
1426 gettimeofday(&timenow, NULL);
1427 newp->c_time.tv_sec = timenow.tv_sec + time;
1428 newp->c_time.tv_usec = timenow.tv_usec;
1431 * Find correct place and link it in.
1433 for (pp = &callout; (p = *pp); pp = &p->c_next)
1434 if (newp->c_time.tv_sec < p->c_time.tv_sec
1435 || (newp->c_time.tv_sec == p->c_time.tv_sec
1436 && newp->c_time.tv_usec < p->c_time.tv_usec))
1444 * untimeout - Unschedule a timeout.
1447 untimeout(func, arg)
1448 void (*func) __P((void *));
1451 struct callout **copp, *freep;
1453 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1456 * Find first matching timeout and remove it from the list.
1458 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1459 if (freep->c_func == func && freep->c_arg == arg) {
1460 *copp = freep->c_next;
1461 free((char *) freep);
1468 * calltimeout - Call any timeout routines which are now due.
1475 while (callout != NULL) {
1478 if (gettimeofday(&timenow, NULL) < 0)
1479 fatal("Failed to get time of day: %m");
1480 if (!(p->c_time.tv_sec < timenow.tv_sec
1481 || (p->c_time.tv_sec == timenow.tv_sec
1482 && p->c_time.tv_usec <= timenow.tv_usec)))
1483 break; /* no, it's not time yet */
1485 callout = p->c_next;
1486 (*p->c_func)(p->c_arg);
1494 * timeleft - return the length of time until the next timeout is due.
1496 static struct timeval *
1498 struct timeval *tvp;
1500 if (callout == NULL)
1503 gettimeofday(&timenow, NULL);
1504 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1505 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1506 if (tvp->tv_usec < 0) {
1507 tvp->tv_usec += 1000000;
1510 if (tvp->tv_sec < 0)
1511 tvp->tv_sec = tvp->tv_usec = 0;
1518 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1524 struct sigaction act, oldact;
1526 act.sa_handler = SIG_IGN;
1529 sigaction(sig, &act, &oldact);
1530 sigaction(sig, &oldact, NULL);
1535 * hup - Catch SIGHUP signal.
1537 * Indicates that the physical layer has been disconnected.
1538 * We don't rely on this indication; if the user has sent this
1539 * signal, we just take the link down.
1545 info("Hangup (SIGHUP)");
1547 if (status != EXIT_HANGUP)
1548 status = EXIT_USER_REQUEST;
1550 /* Send the signal to the [dis]connector process(es) also */
1553 kill(charshunt_pid, sig);
1555 siglongjmp(sigjmp, 1);
1560 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1562 * Indicates that we should initiate a graceful disconnect and exit.
1569 info("Terminating on signal %d.", sig);
1570 persist = 0; /* don't try to restart */
1572 status = EXIT_USER_REQUEST;
1574 /* Send the signal to the [dis]connector process(es) also */
1577 kill(charshunt_pid, sig);
1579 siglongjmp(sigjmp, 1);
1584 * chld - Catch SIGCHLD signal.
1585 * Sets a flag so we will call reap_kids in the mainline.
1593 siglongjmp(sigjmp, 1);
1598 * toggle_debug - Catch SIGUSR1 signal.
1600 * Toggle debug flag.
1609 setlogmask(LOG_UPTO(LOG_DEBUG));
1611 setlogmask(LOG_UPTO(LOG_WARNING));
1617 * open_ccp - Catch SIGUSR2 signal.
1619 * Try to (re)negotiate compression.
1628 siglongjmp(sigjmp, 1);
1633 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1639 static int crashed = 0;
1644 error("Fatal signal %d", sig);
1646 kill_my_pg(SIGTERM);
1648 kill(charshunt_pid, SIGTERM);
1654 * device_script - run a program to talk to the serial device
1655 * (e.g. to run the connector or disconnector script).
1658 device_script(program, in, out, dont_wait)
1672 error("Failed to create child process: %m");
1681 int newin = dup(in);
1685 } else if (out == 2) {
1688 if (log_to_fd >= 0) {
1693 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1694 if (errfd >= 0 && errfd != 2) {
1714 if (getuid() != uid) {
1715 error("setuid failed");
1719 execl("/bin/sh", "sh", "-c", program, (char *)0);
1720 error("could not exec /bin/sh: %m");
1726 record_child(pid, program, NULL, NULL);
1729 while (waitpid(pid, &status, 0) < 0) {
1732 fatal("error waiting for (dis)connection process: %m");
1737 return (status == 0 ? 0 : -1);
1742 * run-program - execute a program with given arguments,
1743 * but don't wait for it.
1744 * If the program can't be executed, logs an error unless
1745 * must_exist is 0 and the program file doesn't exist.
1746 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1747 * or isn't an executable plain file, or the process ID of the child.
1748 * If done != NULL, (*done)(arg) will be called later (within
1749 * reap_kids) iff the return value is > 0.
1752 run_program(prog, args, must_exist, done, arg)
1756 void (*done) __P((void *));
1763 * First check if the file exists and is executable.
1764 * We don't use access() because that would use the
1765 * real user-id, which might not be root, and the script
1766 * might be accessible only to root.
1769 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1770 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1771 if (must_exist || errno != ENOENT)
1772 warn("Can't execute %s: %m", prog);
1778 error("Failed to create child process for %s: %m", prog);
1784 /* Leave the current location */
1785 (void) setsid(); /* No controlling tty. */
1786 (void) umask (S_IRWXG|S_IRWXO);
1787 (void) chdir ("/"); /* no current directory. */
1788 setuid(0); /* set real UID = root */
1791 /* Ensure that nothing of our device environment is inherited. */
1797 close (ttyfd); /* tty interface to the ppp device */
1798 if (real_ttyfd >= 0)
1801 /* Don't pass handles to the PPP device, even by accident. */
1802 new_fd = open (_PATH_DEVNULL, O_RDWR);
1805 dup2 (new_fd, 0); /* stdin <- /dev/null */
1808 dup2 (0, 1); /* stdout -> /dev/null */
1809 dup2 (0, 2); /* stderr -> /dev/null */
1813 /* Force the priority back to zero if pppd is running higher. */
1814 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1815 warn("can't reset priority to 0: %m");
1818 /* SysV recommends a second fork at this point. */
1820 /* run the program */
1821 execve(prog, args, script_env);
1822 if (must_exist || errno != ENOENT) {
1823 /* have to reopen the log, there's nowhere else
1824 for the message to go. */
1826 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1833 dbglog("Script %s started (pid %d)", prog, pid);
1834 record_child(pid, prog, done, arg);
1841 * record_child - add a child process to the list for reap_kids
1845 record_child(pid, prog, done, arg)
1848 void (*done) __P((void *));
1851 struct subprocess *chp;
1855 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1857 warn("losing track of %s process", prog);
1863 chp->next = children;
1870 * reap_kids - get status from any dead child processes,
1871 * and log a message for abnormal terminations.
1878 struct subprocess *chp, **prevp;
1881 if (n_children == 0)
1883 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1885 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1886 if (chp->pid == pid) {
1892 if (WIFSIGNALED(status)) {
1893 warn("Child process %s (pid %d) terminated with signal %d",
1894 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1896 dbglog("Script %s finished (pid %d), status = 0x%x",
1897 (chp? chp->prog: "??"), pid, status);
1898 if (chp && chp->done)
1899 (*chp->done)(chp->arg);
1904 if (errno == ECHILD)
1907 error("Error waiting for child process: %m");
1914 * novm - log an error message saying we ran out of memory, and die.
1920 fatal("Virtual memory exhausted allocating %s\n", msg);
1924 * script_setenv - set an environment variable value to be used
1925 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1928 script_setenv(var, value, iskey)
1932 size_t varl = strlen(var);
1933 size_t vl = varl + strlen(value) + 2;
1935 char *p, *newstring;
1937 newstring = (char *) malloc(vl);
1940 slprintf(newstring, vl, "%s=%s", var, value);
1942 /* check if this variable is already set */
1943 if (script_env != 0) {
1944 for (i = 0; (p = script_env[i]) != 0; ++i) {
1945 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1946 if (iskey && pppdb != NULL) {
1948 add_db_key(newstring);
1951 script_env[i] = newstring;
1956 /* no space allocated for script env. ptrs. yet */
1958 script_env = (char **) malloc(16 * sizeof(char *));
1959 if (script_env == 0)
1964 /* reallocate script_env with more space if needed */
1965 if (i + 1 >= s_env_nalloc) {
1967 char **newenv = (char **) realloc((void *)script_env,
1968 new_n * sizeof(char *));
1971 script_env = newenv;
1972 s_env_nalloc = new_n;
1975 script_env[i] = newstring;
1976 script_env[i+1] = 0;
1978 if (pppdb != NULL) {
1980 add_db_key(newstring);
1986 * script_unsetenv - remove a variable from the environment
1990 script_unsetenv(var)
1993 int vl = strlen(var);
1997 if (script_env == 0)
1999 for (i = 0; (p = script_env[i]) != 0; ++i) {
2000 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2002 while ((script_env[i] = script_env[i+1]) != 0)
2012 * update_db_entry - update our entry in the database.
2021 if (script_env == NULL)
2024 for (i = 0; (p = script_env[i]) != 0; ++i)
2025 vlen += strlen(p) + 1;
2026 vbuf = malloc(vlen);
2028 novm("database entry");
2030 for (i = 0; (p = script_env[i]) != 0; ++i)
2031 q += slprintf(q, vbuf + vlen - q, "%s;", p);
2034 key.dsize = strlen(db_key);
2037 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2038 error("tdb_store failed: %s", tdb_error(pppdb));
2043 * add_db_key - add a key that we can use to look up our database entry.
2051 key.dptr = (char *) str;
2052 key.dsize = strlen(str);
2054 dbuf.dsize = strlen(db_key);
2055 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2056 error("tdb_store key failed: %s", tdb_error(pppdb));
2060 * delete_db_key - delete a key for looking up our database entry.
2068 key.dptr = (char *) str;
2069 key.dsize = strlen(str);
2070 tdb_delete(pppdb, key);
2074 * open_socket - establish a stream socket connection to the nominated
2081 char *sep, *endp = NULL;
2082 int sock, port = -1;
2084 struct hostent *hent;
2085 struct sockaddr_in sad;
2087 /* parse host:port and resolve host to an IP address */
2088 sep = strchr(dest, ':');
2090 port = strtol(sep+1, &endp, 10);
2091 if (port < 0 || endp == sep+1 || sep == dest) {
2092 error("Can't parse host:port for socket destination");
2096 host = inet_addr(dest);
2097 if (host == (u_int32_t) -1) {
2098 hent = gethostbyname(dest);
2100 error("%s: unknown host in socket option", dest);
2104 host = *(u_int32_t *)(hent->h_addr_list[0]);
2108 /* get a socket and connect it to the other end */
2109 sock = socket(PF_INET, SOCK_STREAM, 0);
2111 error("Can't create socket: %m");
2114 memset(&sad, 0, sizeof(sad));
2115 sad.sin_family = AF_INET;
2116 sad.sin_port = htons(port);
2117 sad.sin_addr.s_addr = host;
2118 if (connect(sock, &sad, sizeof(sad)) < 0) {
2119 error("Can't connect to %s: %m", dest);
2128 * start_charshunt - create a child process to run the character shunt.
2131 start_charshunt(ifd, ofd)
2138 error("Can't fork process for character shunt: %m");
2145 if (getuid() != uid)
2146 fatal("setuid failed");
2150 charshunt(ifd, ofd, record_file);
2153 charshunt_pid = cpid;
2157 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2169 * charshunt - the character shunt, which passes characters between
2170 * the pty master side and the serial port (or stdin/stdout).
2171 * This runs as the user (not as root).
2172 * (We assume ofd >= ifd which is true the way this gets called. :-).
2175 charshunt(ifd, ofd, record_file)
2180 fd_set ready, writey;
2181 u_char *ibufp, *obufp;
2184 int pty_readable, stdin_readable;
2185 struct timeval lasttime;
2186 FILE *recordf = NULL;
2187 int ilevel, olevel, max_level;
2188 struct timeval levelt, tout, *top;
2191 * Reset signal handlers.
2193 signal(SIGHUP, SIG_IGN); /* Hangup */
2194 signal(SIGINT, SIG_DFL); /* Interrupt */
2195 signal(SIGTERM, SIG_DFL); /* Terminate */
2196 signal(SIGCHLD, SIG_DFL);
2197 signal(SIGUSR1, SIG_DFL);
2198 signal(SIGUSR2, SIG_DFL);
2199 signal(SIGABRT, SIG_DFL);
2200 signal(SIGALRM, SIG_DFL);
2201 signal(SIGFPE, SIG_DFL);
2202 signal(SIGILL, SIG_DFL);
2203 signal(SIGPIPE, SIG_DFL);
2204 signal(SIGQUIT, SIG_DFL);
2205 signal(SIGSEGV, SIG_DFL);
2207 signal(SIGBUS, SIG_DFL);
2210 signal(SIGEMT, SIG_DFL);
2213 signal(SIGPOLL, SIG_DFL);
2216 signal(SIGPROF, SIG_DFL);
2219 signal(SIGSYS, SIG_DFL);
2222 signal(SIGTRAP, SIG_DFL);
2225 signal(SIGVTALRM, SIG_DFL);
2228 signal(SIGXCPU, SIG_DFL);
2231 signal(SIGXFSZ, SIG_DFL);
2235 * Open the record file if required.
2237 if (record_file != NULL) {
2238 recordf = fopen(record_file, "a");
2239 if (recordf == NULL)
2240 error("Couldn't create record file %s: %m", record_file);
2243 /* set all the fds to non-blocking mode */
2244 flags = fcntl(pty_master, F_GETFL);
2246 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2247 warn("couldn't set pty master to nonblock: %m");
2248 flags = fcntl(ifd, F_GETFL);
2250 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2251 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2253 flags = fcntl(ofd, F_GETFL);
2255 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2256 warn("couldn't set stdout to nonblock: %m");
2260 ibufp = obufp = NULL;
2261 pty_readable = stdin_readable = 1;
2263 ilevel = olevel = 0;
2264 gettimeofday(&levelt, NULL);
2265 if (max_data_rate) {
2266 max_level = max_data_rate / 10;
2267 if (max_level < 100)
2270 max_level = sizeof(inpacket_buf) + 1;
2272 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2273 if (recordf != NULL) {
2274 gettimeofday(&lasttime, NULL);
2275 putc(7, recordf); /* put start marker */
2276 putc(lasttime.tv_sec >> 24, recordf);
2277 putc(lasttime.tv_sec >> 16, recordf);
2278 putc(lasttime.tv_sec >> 8, recordf);
2279 putc(lasttime.tv_sec, recordf);
2280 lasttime.tv_usec = 0;
2283 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2286 tout.tv_usec = 10000;
2290 if (ilevel >= max_level)
2293 FD_SET(pty_master, &writey);
2294 } else if (stdin_readable)
2295 FD_SET(ifd, &ready);
2297 if (olevel >= max_level)
2300 FD_SET(ofd, &writey);
2301 } else if (pty_readable)
2302 FD_SET(pty_master, &ready);
2303 if (select(nfds, &ready, &writey, NULL, top) < 0) {
2308 if (max_data_rate) {
2313 gettimeofday(&now, NULL);
2314 dt = (now.tv_sec - levelt.tv_sec
2315 + (now.tv_usec - levelt.tv_usec) / 1e6);
2316 nbt = (int)(dt * max_data_rate);
2317 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2318 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2321 ilevel = olevel = 0;
2322 if (FD_ISSET(ifd, &ready)) {
2323 ibufp = inpacket_buf;
2324 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2325 if (nibuf < 0 && errno == EIO)
2328 if (!(errno == EINTR || errno == EAGAIN)) {
2329 error("Error reading standard input: %m");
2333 } else if (nibuf == 0) {
2334 /* end of file from stdin */
2336 /* do a 0-length write, hopefully this will generate
2337 an EOF (hangup) on the slave side. */
2338 write(pty_master, inpacket_buf, 0);
2340 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2343 FD_SET(pty_master, &writey);
2345 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2349 if (FD_ISSET(pty_master, &ready)) {
2350 obufp = outpacket_buf;
2351 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2352 if (nobuf < 0 && errno == EIO)
2355 if (!(errno == EINTR || errno == EAGAIN)) {
2356 error("Error reading pseudo-tty master: %m");
2360 } else if (nobuf == 0) {
2361 /* end of file from the pty - slave side has closed */
2363 stdin_readable = 0; /* pty is not writable now */
2367 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2370 FD_SET(ofd, &writey);
2372 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2376 if (FD_ISSET(ofd, &writey)) {
2378 if (olevel + n > max_level)
2379 n = max_level - olevel;
2380 n = write(ofd, obufp, n);
2383 error("Error writing standard output: %m");
2394 if (FD_ISSET(pty_master, &writey)) {
2396 if (ilevel + n > max_level)
2397 n = max_level - ilevel;
2398 n = write(pty_master, ibufp, n);
2401 error("Error writing pseudo-tty master: %m");
2417 record_write(f, code, buf, nb, tp)
2427 gettimeofday(&now, NULL);
2428 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2429 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2433 putc(diff >> 24, f);
2434 putc(diff >> 16, f);
2447 fwrite(buf, nb, 1, f);
2451 error("Error writing record file: %m");