]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
ad7c90d0910bd0b5831c01cf0ae87fa64106c3c0
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
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.
18  */
19
20 #define RCSID   "$Id: main.c,v 1.94 2000/04/15 01:27:13 masputra Exp $"
21
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <pwd.h>
34 #include <setjmp.h>
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 #include "pppd.h"
46 #include "magic.h"
47 #include "fsm.h"
48 #include "lcp.h"
49 #include "ipcp.h"
50 #ifdef INET6
51 #include "ipv6cp.h"
52 #endif
53 #include "upap.h"
54 #include "chap.h"
55 #include "ccp.h"
56 #include "pathnames.h"
57 #include "patchlevel.h"
58 #include "tdb.h"
59
60 #ifdef CBCP_SUPPORT
61 #include "cbcp.h"
62 #endif
63
64 #ifdef IPX_CHANGE
65 #include "ipxcp.h"
66 #endif /* IPX_CHANGE */
67 #ifdef AT_CHANGE
68 #include "atcp.h"
69 #endif
70
71 static const char rcsid[] = RCSID;
72
73 /* interface vars */
74 char ifname[32];                /* Interface name */
75 int ifunit;                     /* Interface unit number */
76
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 */
84
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. */
101 char db_key[32];
102
103 int (*holdoff_hook) __P((void)) = NULL;
104 int (*new_phase_hook) __P((int)) = NULL;
105
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) */
111
112 int phase;                      /* where the link is at */
113 int kill_link;
114 int open_ccp_flag;
115
116 static int waiting;
117 static sigjmp_buf sigjmp;
118
119 char **script_env;              /* Env. variable values for scripts */
120 int s_env_nalloc;               /* # words avail at script_env */
121
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 */
124
125 static int n_children;          /* # child processes still running */
126 static int got_sigchld;         /* set if we have received a SIGCHLD */
127
128 static int locked;              /* lock() has succeeded */
129 static int privopen;            /* don't lock, open device as root */
130
131 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
132
133 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
134 int ngroups;                    /* How many groups valid in groups */
135
136 static struct timeval start_time;       /* Time when link was started. */
137
138 struct pppd_stats link_stats;
139 int link_connect_time;
140 int link_stats_valid;
141
142 static int charshunt_pid;       /* Process ID for charshunt */
143
144 /*
145  * We maintain a list of child process pids and
146  * functions to call when they exit.
147  */
148 struct subprocess {
149     pid_t       pid;
150     char        *prog;
151     void        (*done) __P((void *));
152     void        *arg;
153     struct subprocess *next;
154 };
155
156 static struct subprocess *children;
157
158 /* Prototypes for procedures local to this file. */
159
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,
188                              struct timeval *));
189
190 extern  char    *ttyname __P((int));
191 extern  char    *getlogin __P((void));
192 int main __P((int, char *[]));
193
194 #ifdef ultrix
195 #undef  O_NONBLOCK
196 #define O_NONBLOCK      O_NDELAY
197 #endif
198
199 #ifdef ULTRIX
200 #define setlogmask(x)
201 #endif
202
203 /*
204  * PPP Data Link Layer "protocol" table.
205  * One entry per supported protocol.
206  * The last entry must be NULL.
207  */
208 struct protent *protocols[] = {
209     &lcp_protent,
210     &pap_protent,
211     &chap_protent,
212 #ifdef CBCP_SUPPORT
213     &cbcp_protent,
214 #endif
215     &ipcp_protent,
216 #ifdef INET6
217     &ipv6cp_protent,
218 #endif
219     &ccp_protent,
220 #ifdef IPX_CHANGE
221     &ipxcp_protent,
222 #endif
223 #ifdef AT_CHANGE
224     &atcp_protent,
225 #endif
226     NULL
227 };
228
229 int
230 main(argc, argv)
231     int argc;
232     char *argv[];
233 {
234     int i, fdflags, t;
235     char *p, *connector;
236     struct passwd *pw;
237     struct timeval timo;
238     sigset_t mask;
239     struct protent *protp;
240     struct stat statbuf;
241     char numbuf[16];
242
243     new_phase(PHASE_INITIALIZE);
244
245     /*
246      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
247      * This way we can close 0, 1, 2 in detach() without clobbering
248      * a fd that we are using.
249      */
250     if ((i = open("/dev/null", O_RDWR)) >= 0) {
251         while (0 <= i && i <= 2)
252             i = dup(i);
253         if (i >= 0)
254             close(i);
255     }
256
257     script_env = NULL;
258
259     /* Initialize syslog facilities */
260     reopen_log();
261
262     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
263         option_error("Couldn't get hostname: %m");
264         exit(1);
265     }
266     hostname[MAXNAMELEN-1] = 0;
267
268     /* make sure we don't create world or group writable files. */
269     umask(umask(0777) | 022);
270
271     uid = getuid();
272     privileged = uid == 0;
273     slprintf(numbuf, sizeof(numbuf), "%d", uid);
274     script_setenv("ORIG_UID", numbuf, 0);
275
276     ngroups = getgroups(NGROUPS_MAX, groups);
277
278     /*
279      * Initialize magic number generator now so that protocols may
280      * use magic numbers in initialization.
281      */
282     magic_init();
283
284     /*
285      * Initialize to the standard option set, then parse, in order,
286      * the system options file, the user's options file,
287      * the tty's options file, and the command line arguments.
288      */
289     for (i = 0; (protp = protocols[i]) != NULL; ++i)
290         (*protp->init)(0);
291
292     progname = *argv;
293
294     prepass = 0;
295     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
296         || !options_from_user())
297         exit(EXIT_OPTION_ERROR);
298
299     /* scan command line and options files to find device name */
300     prepass = 1;
301     parse_args(argc-1, argv+1);
302     prepass = 0;
303
304     /*
305      * Work out the device name, if it hasn't already been specified.
306      */
307     using_pty = notty || ptycommand != NULL || pty_socket != NULL;
308     if (!using_pty && default_device) {
309         char *p;
310         if (!isatty(0) || (p = ttyname(0)) == NULL) {
311             option_error("no device specified and stdin is not a tty");
312             exit(EXIT_OPTION_ERROR);
313         }
314         strlcpy(devnam, p, sizeof(devnam));
315         if (stat(devnam, &devstat) < 0)
316             fatal("Couldn't stat default device %s: %m", devnam);
317     }
318
319     /*
320      * Parse the tty options file and the command line.
321      * The per-tty options file should not change
322      * ptycommand, pty_socket, notty or devnam.
323      */
324     devnam_fixed = 1;
325     if (!using_pty) {
326         if (!options_for_tty())
327             exit(EXIT_OPTION_ERROR);
328     }
329
330     devnam_fixed = 0;
331     if (!parse_args(argc-1, argv+1))
332         exit(EXIT_OPTION_ERROR);
333
334     /*
335      * Check that we are running as root.
336      */
337     if (geteuid() != 0) {
338         option_error("must be root to run %s, since it is not setuid-root",
339                      argv[0]);
340         exit(EXIT_NOT_ROOT);
341     }
342
343     if (!ppp_available()) {
344         option_error(no_ppp_msg);
345         exit(EXIT_NO_KERNEL_SUPPORT);
346     }
347
348     /*
349      * Check that the options given are valid and consistent.
350      */
351     if (!sys_check_options())
352         exit(EXIT_OPTION_ERROR);
353     auth_check_options();
354 #ifdef HAVE_MULTILINK
355     mp_check_options();
356 #endif
357     for (i = 0; (protp = protocols[i]) != NULL; ++i)
358         if (protp->check_options != NULL)
359             (*protp->check_options)();
360     if (demand && connect_script == 0) {
361         option_error("connect script is required for demand-dialling\n");
362         exit(EXIT_OPTION_ERROR);
363     }
364     /* default holdoff to 0 if no connect script has been given */
365     if (connect_script == 0 && !holdoff_specified)
366         holdoff = 0;
367
368     if (using_pty) {
369         if (!default_device) {
370             option_error("%s option precludes specifying device name",
371                          notty? "notty": "pty");
372             exit(EXIT_OPTION_ERROR);
373         }
374         if (ptycommand != NULL && notty) {
375             option_error("pty option is incompatible with notty option");
376             exit(EXIT_OPTION_ERROR);
377         }
378         if (pty_socket != NULL && (ptycommand != NULL || notty)) {
379             option_error("socket option is incompatible with pty and notty");
380             exit(EXIT_OPTION_ERROR);
381         }
382         default_device = notty;
383         lockflag = 0;
384         modem = 0;
385         if (notty && log_to_fd <= 1)
386             log_to_fd = -1;
387     } else {
388         /*
389          * If the user has specified a device which is the same as
390          * the one on stdin, pretend they didn't specify any.
391          * If the device is already open read/write on stdin,
392          * we assume we don't need to lock it, and we can open it as root.
393          */
394         if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
395             && statbuf.st_rdev == devstat.st_rdev) {
396             default_device = 1;
397             fdflags = fcntl(0, F_GETFL);
398             if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
399                 privopen = 1;
400         }
401     }
402     if (default_device)
403         nodetach = 1;
404
405     /*
406      * Don't send log messages to the serial port, it tends to
407      * confuse the peer. :-)
408      */
409     if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
410         && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
411         log_to_fd = -1;
412
413     /*
414      * Initialize system-dependent stuff.
415      */
416     sys_init();
417     if (debug)
418         setlogmask(LOG_UPTO(LOG_DEBUG));
419
420     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
421     if (pppdb != NULL) {
422         slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
423         update_db_entry();
424     } else {
425         warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
426         if (multilink) {
427             warn("Warning: disabling multilink");
428             multilink = 0;
429         }
430     }
431
432     /*
433      * Detach ourselves from the terminal, if required,
434      * and identify who is running us.
435      */
436     if (!nodetach && !updetach)
437         detach();
438     p = getlogin();
439     if (p == NULL) {
440         pw = getpwuid(uid);
441         if (pw != NULL && pw->pw_name != NULL)
442             p = pw->pw_name;
443         else
444             p = "(unknown)";
445     }
446     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
447            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
448     script_setenv("PPPLOGNAME", p, 0);
449
450     if (devnam[0])
451         script_setenv("DEVICE", devnam, 1);
452     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
453     script_setenv("PPPD_PID", numbuf, 1);
454
455     setup_signals();
456
457     waiting = 0;
458
459     create_linkpidfile();
460
461     /*
462      * If we're doing dial-on-demand, set up the interface now.
463      */
464     if (demand) {
465         /*
466          * Open the loopback channel and set it up to be the ppp interface.
467          */
468         tdb_writelock(pppdb);
469         fd_loop = open_ppp_loopback();
470         set_ifunit(1);
471         tdb_writeunlock(pppdb);
472
473         /*
474          * Configure the interface and mark it up, etc.
475          */
476         demand_conf();
477     }
478
479     do_callback = 0;
480     for (;;) {
481
482         need_holdoff = 1;
483         ttyfd = -1;
484         real_ttyfd = -1;
485         status = EXIT_OK;
486         ++unsuccess;
487         doing_callback = do_callback;
488         do_callback = 0;
489
490         if (demand && !doing_callback) {
491             /*
492              * Don't do anything until we see some activity.
493              */
494             kill_link = 0;
495             new_phase(PHASE_DORMANT);
496             demand_unblock();
497             add_fd(fd_loop);
498             for (;;) {
499                 if (sigsetjmp(sigjmp, 1) == 0) {
500                     sigprocmask(SIG_BLOCK, &mask, NULL);
501                     if (kill_link || got_sigchld) {
502                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
503                     } else {
504                         waiting = 1;
505                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
506                         wait_input(timeleft(&timo));
507                     }
508                 }
509                 waiting = 0;
510                 calltimeout();
511                 if (kill_link) {
512                     if (!persist)
513                         break;
514                     kill_link = 0;
515                 }
516                 if (get_loop_output())
517                     break;
518                 if (got_sigchld)
519                     reap_kids(0);
520             }
521             remove_fd(fd_loop);
522             if (kill_link && !persist)
523                 break;
524
525             /*
526              * Now we want to bring up the link.
527              */
528             demand_block();
529             info("Starting link");
530         }
531
532         new_phase(PHASE_SERIALCONN);
533
534         /*
535          * Get a pty master/slave pair if the pty, notty, socket,
536          * or record options were specified.
537          */
538         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
539         pty_master = -1;
540         pty_slave = -1;
541         if (using_pty || record_file != NULL) {
542             if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
543                 error("Couldn't allocate pseudo-tty");
544                 status = EXIT_FATAL_ERROR;
545                 goto fail;
546             }
547             set_up_tty(pty_slave, 1);
548         }
549
550         /*
551          * Lock the device if we've been asked to.
552          */
553         status = EXIT_LOCK_FAILED;
554         if (lockflag && !privopen) {
555             if (lock(devnam) < 0)
556                 goto fail;
557             locked = 1;
558         }
559
560         /*
561          * Open the serial device and set it up to be the ppp interface.
562          * First we open it in non-blocking mode so we can set the
563          * various termios flags appropriately.  If we aren't dialling
564          * out and we want to use the modem lines, we reopen it later
565          * in order to wait for the carrier detect signal from the modem.
566          */
567         hungup = 0;
568         kill_link = 0;
569         connector = doing_callback? callback_script: connect_script;
570         if (devnam[0] != 0) {
571             for (;;) {
572                 /* If the user specified the device name, become the
573                    user before opening it. */
574                 int err;
575                 if (!devnam_info.priv && !privopen)
576                     seteuid(uid);
577                 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
578                 err = errno;
579                 if (!devnam_info.priv && !privopen)
580                     seteuid(0);
581                 if (ttyfd >= 0)
582                     break;
583                 errno = err;
584                 if (err != EINTR) {
585                     error("Failed to open %s: %m", devnam);
586                     status = EXIT_OPEN_FAILED;
587                 }
588                 if (!persist || err != EINTR)
589                     goto fail;
590             }
591             if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
592                 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
593                 warn("Couldn't reset non-blocking mode on device: %m");
594
595             /*
596              * Do the equivalent of `mesg n' to stop broadcast messages.
597              */
598             if (fstat(ttyfd, &statbuf) < 0
599                 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
600                 warn("Couldn't restrict write permissions to %s: %m", devnam);
601             } else
602                 tty_mode = statbuf.st_mode;
603
604             /*
605              * Set line speed, flow control, etc.
606              * If we have a non-null connection or initializer script,
607              * on most systems we set CLOCAL for now so that we can talk
608              * to the modem before carrier comes up.  But this has the
609              * side effect that we might miss it if CD drops before we
610              * get to clear CLOCAL below.  On systems where we can talk
611              * successfully to the modem with CLOCAL clear and CD down,
612              * we could clear CLOCAL at this point.
613              */
614             set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
615                                || initializer != NULL));
616             real_ttyfd = ttyfd;
617         }
618
619         /*
620          * If the pty, socket, notty and/or record option was specified,
621          * start up the character shunt now.
622          */
623         status = EXIT_PTYCMD_FAILED;
624         if (ptycommand != NULL) {
625             if (record_file != NULL) {
626                 int ipipe[2], opipe[2], ok;
627
628                 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
629                     fatal("Couldn't create pipes for record option: %m");
630                 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
631                     && start_charshunt(ipipe[0], opipe[1]);
632                 close(ipipe[0]);
633                 close(ipipe[1]);
634                 close(opipe[0]);
635                 close(opipe[1]);
636                 if (!ok)
637                     goto fail;
638             } else {
639                 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
640                     goto fail;
641                 ttyfd = pty_slave;
642                 close(pty_master);
643                 pty_master = -1;
644             }
645         } else if (pty_socket != NULL) {
646             int fd = open_socket(pty_socket);
647             if (fd < 0)
648                 goto fail;
649             if (!start_charshunt(fd, fd))
650                 goto fail;
651         } else if (notty) {
652             if (!start_charshunt(0, 1))
653                 goto fail;
654         } else if (record_file != NULL) {
655             if (!start_charshunt(ttyfd, ttyfd))
656                 goto fail;
657         }
658
659         /* run connection script */
660         if ((connector && connector[0]) || initializer) {
661             if (real_ttyfd != -1) {
662                 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
663                 if (!default_device && modem) {
664                     setdtr(real_ttyfd, 0);      /* in case modem is off hook */
665                     sleep(1);
666                     setdtr(real_ttyfd, 1);
667                 }
668             }
669
670             if (initializer && initializer[0]) {
671                 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
672                     error("Initializer script failed");
673                     status = EXIT_INIT_FAILED;
674                     goto fail;
675                 }
676                 if (kill_link)
677                     goto disconnect;
678
679                 info("Serial port initialized.");
680             }
681
682             if (connector && connector[0]) {
683                 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
684                     error("Connect script failed");
685                     status = EXIT_CONNECT_FAILED;
686                     goto fail;
687                 }
688                 if (kill_link)
689                     goto disconnect;
690
691                 info("Serial connection established.");
692             }
693
694             /* set line speed, flow control, etc.;
695                clear CLOCAL if modem option */
696             if (real_ttyfd != -1)
697                 set_up_tty(real_ttyfd, 0);
698
699             if (doing_callback == CALLBACK_DIALIN)
700                 connector = NULL;
701         }
702
703         /* reopen tty if necessary to wait for carrier */
704         if (connector == NULL && modem && devnam[0] != 0) {
705             for (;;) {
706                 if ((i = open(devnam, O_RDWR)) >= 0)
707                     break;
708                 if (errno != EINTR) {
709                     error("Failed to reopen %s: %m", devnam);
710                     status = EXIT_OPEN_FAILED;
711                 }
712                 if (!persist || errno != EINTR || hungup || kill_link)
713                     goto fail;
714             }
715             close(i);
716         }
717
718         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
719         script_setenv("SPEED", numbuf, 0);
720
721         /* run welcome script, if any */
722         if (welcomer && welcomer[0]) {
723             if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
724                 warn("Welcome script failed");
725         }
726
727         /* set up the serial device as a ppp interface */
728         tdb_writelock(pppdb);
729         fd_ppp = establish_ppp(ttyfd);
730         if (fd_ppp < 0) {
731             tdb_writeunlock(pppdb);
732             status = EXIT_FATAL_ERROR;
733             goto disconnect;
734         }
735
736         if (!demand && ifunit >= 0)
737             set_ifunit(1);
738         tdb_writeunlock(pppdb);
739
740         /*
741          * Start opening the connection and wait for
742          * incoming events (reply, timeout, etc.).
743          */
744         notice("Connect: %s <--> %s", ifname, ppp_devnam);
745         gettimeofday(&start_time, NULL);
746         link_stats_valid = 0;
747         script_unsetenv("CONNECT_TIME");
748         script_unsetenv("BYTES_SENT");
749         script_unsetenv("BYTES_RCVD");
750         lcp_lowerup(0);
751
752         /*
753          * If we are initiating this connection, wait for a short
754          * time for something from the peer.  This can avoid bouncing
755          * our packets off his tty before he has it set up.
756          */
757         add_fd(fd_ppp);
758         if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
759             struct timeval t;
760             t.tv_sec = connect_delay / 1000;
761             t.tv_usec = connect_delay % 1000;
762             wait_input(&t);
763         }
764
765         lcp_open(0);            /* Start protocol */
766         open_ccp_flag = 0;
767         status = EXIT_NEGOTIATION_FAILED;
768         new_phase(PHASE_ESTABLISH);
769         while (phase != PHASE_DEAD) {
770             if (sigsetjmp(sigjmp, 1) == 0) {
771                 sigprocmask(SIG_BLOCK, &mask, NULL);
772                 if (kill_link || open_ccp_flag || got_sigchld) {
773                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
774                 } else {
775                     waiting = 1;
776                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
777                     wait_input(timeleft(&timo));
778                 }
779             }
780             waiting = 0;
781             calltimeout();
782             get_input();
783             if (kill_link) {
784                 lcp_close(0, "User request");
785                 kill_link = 0;
786             }
787             if (open_ccp_flag) {
788                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
789                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
790                     (*ccp_protent.open)(0);
791                 }
792                 open_ccp_flag = 0;
793             }
794             if (got_sigchld)
795                 reap_kids(0);   /* Don't leave dead kids lying around */
796         }
797
798         /*
799          * Print connect time and statistics.
800          */
801         if (link_stats_valid) {
802             int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
803             info("Connect time %d.%d minutes.", t/10, t%10);
804             info("Sent %d bytes, received %d bytes.",
805                  link_stats.bytes_out, link_stats.bytes_in);
806         }
807
808         /*
809          * Delete pid file before disestablishing ppp.  Otherwise it
810          * can happen that another pppd gets the same unit and then
811          * we delete its pid file.
812          */
813         if (!demand) {
814             if (pidfilename[0] != 0
815                 && unlink(pidfilename) < 0 && errno != ENOENT) 
816                 warn("unable to delete pid file %s: %m", pidfilename);
817             pidfilename[0] = 0;
818         }
819
820         /*
821          * If we may want to bring the link up again, transfer
822          * the ppp unit back to the loopback.  Set the
823          * real serial device back to its normal mode of operation.
824          */
825         remove_fd(fd_ppp);
826         clean_check();
827         if (demand)
828             restore_loop();
829         disestablish_ppp(ttyfd);
830         fd_ppp = -1;
831         if (!hungup)
832             lcp_lowerdown(0);
833         if (!demand)
834             script_unsetenv("IFNAME");
835
836         /*
837          * Run disconnector script, if requested.
838          * XXX we may not be able to do this if the line has hung up!
839          */
840     disconnect:
841         if (disconnect_script && !hungup) {
842             new_phase(PHASE_DISCONNECT);
843             if (real_ttyfd >= 0)
844                 set_up_tty(real_ttyfd, 1);
845             if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
846                 warn("disconnect script failed");
847             } else {
848                 info("Serial link disconnected.");
849             }
850         }
851
852     fail:
853         if (pty_master >= 0)
854             close(pty_master);
855         if (pty_slave >= 0)
856             close(pty_slave);
857         if (real_ttyfd >= 0)
858             close_tty();
859         if (locked) {
860             unlock();
861             locked = 0;
862         }
863
864         if (!demand) {
865             if (pidfilename[0] != 0
866                 && unlink(pidfilename) < 0 && errno != ENOENT) 
867                 warn("unable to delete pid file %s: %m", pidfilename);
868             pidfilename[0] = 0;
869         }
870
871         if (!persist || (maxfail > 0 && unsuccess >= maxfail))
872             break;
873
874         kill_link = 0;
875         if (demand)
876             demand_discard();
877         t = need_holdoff? holdoff: 0;
878         if (holdoff_hook)
879             t = (*holdoff_hook)();
880         if (t > 0) {
881             new_phase(PHASE_HOLDOFF);
882             TIMEOUT(holdoff_end, NULL, t);
883             do {
884                 if (sigsetjmp(sigjmp, 1) == 0) {
885                     sigprocmask(SIG_BLOCK, &mask, NULL);
886                     if (kill_link || got_sigchld) {
887                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
888                     } else {
889                         waiting = 1;
890                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
891                         wait_input(timeleft(&timo));
892                     }
893                 }
894                 waiting = 0;
895                 calltimeout();
896                 if (kill_link) {
897                     kill_link = 0;
898                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
899                 }
900                 if (got_sigchld)
901                     reap_kids(0);
902             } while (phase == PHASE_HOLDOFF);
903             if (!persist)
904                 break;
905         }
906     }
907
908     /* Wait for scripts to finish */
909     /* XXX should have a timeout here */
910     while (n_children > 0) {
911         if (debug) {
912             struct subprocess *chp;
913             dbglog("Waiting for %d child processes...", n_children);
914             for (chp = children; chp != NULL; chp = chp->next)
915                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
916         }
917         if (reap_kids(1) < 0)
918             break;
919     }
920
921     die(status);
922     return 0;
923 }
924
925 /*
926  * setup_signals - initialize signal handling.
927  */
928 static void
929 setup_signals()
930 {
931     struct sigaction sa;
932     sigset_t mask;
933
934     /*
935      * Compute mask of all interesting signals and install signal handlers
936      * for each.  Only one signal handler may be active at a time.  Therefore,
937      * all other signals should be masked when any handler is executing.
938      */
939     sigemptyset(&mask);
940     sigaddset(&mask, SIGHUP);
941     sigaddset(&mask, SIGINT);
942     sigaddset(&mask, SIGTERM);
943     sigaddset(&mask, SIGCHLD);
944     sigaddset(&mask, SIGUSR2);
945
946 #define SIGNAL(s, handler)      do { \
947         sa.sa_handler = handler; \
948         if (sigaction(s, &sa, NULL) < 0) \
949             fatal("Couldn't establish signal handler (%d): %m", s); \
950     } while (0)
951
952     sa.sa_mask = mask;
953     sa.sa_flags = 0;
954     SIGNAL(SIGHUP, hup);                /* Hangup */
955     SIGNAL(SIGINT, term);               /* Interrupt */
956     SIGNAL(SIGTERM, term);              /* Terminate */
957     SIGNAL(SIGCHLD, chld);
958
959     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
960     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
961
962     /*
963      * Install a handler for other signals which would otherwise
964      * cause pppd to exit without cleaning up.
965      */
966     SIGNAL(SIGABRT, bad_signal);
967     SIGNAL(SIGALRM, bad_signal);
968     SIGNAL(SIGFPE, bad_signal);
969     SIGNAL(SIGILL, bad_signal);
970     SIGNAL(SIGPIPE, bad_signal);
971     SIGNAL(SIGQUIT, bad_signal);
972     SIGNAL(SIGSEGV, bad_signal);
973 #ifdef SIGBUS
974     SIGNAL(SIGBUS, bad_signal);
975 #endif
976 #ifdef SIGEMT
977     SIGNAL(SIGEMT, bad_signal);
978 #endif
979 #ifdef SIGPOLL
980     SIGNAL(SIGPOLL, bad_signal);
981 #endif
982 #ifdef SIGPROF
983     SIGNAL(SIGPROF, bad_signal);
984 #endif
985 #ifdef SIGSYS
986     SIGNAL(SIGSYS, bad_signal);
987 #endif
988 #ifdef SIGTRAP
989     SIGNAL(SIGTRAP, bad_signal);
990 #endif
991 #ifdef SIGVTALRM
992     SIGNAL(SIGVTALRM, bad_signal);
993 #endif
994 #ifdef SIGXCPU
995     SIGNAL(SIGXCPU, bad_signal);
996 #endif
997 #ifdef SIGXFSZ
998     SIGNAL(SIGXFSZ, bad_signal);
999 #endif
1000
1001     /*
1002      * Apparently we can get a SIGPIPE when we call syslog, if
1003      * syslogd has died and been restarted.  Ignoring it seems
1004      * be sufficient.
1005      */
1006     signal(SIGPIPE, SIG_IGN);
1007 }
1008
1009 /*
1010  * set_ifunit - do things we need to do once we know which ppp
1011  * unit we are using.
1012  */
1013 void
1014 set_ifunit(iskey)
1015     int iskey;
1016 {
1017     info("Using interface ppp%d", ifunit);
1018     slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
1019     script_setenv("IFNAME", ifname, iskey);
1020     create_pidfile();   /* write pid to file */
1021     create_linkpidfile();
1022 }
1023
1024 /*
1025  * detach - detach us from the controlling terminal.
1026  */
1027 void
1028 detach()
1029 {
1030     int pid;
1031     char numbuf[16];
1032
1033     if (detached)
1034         return;
1035     if ((pid = fork()) < 0) {
1036         error("Couldn't detach (fork failed: %m)");
1037         die(1);                 /* or just return? */
1038     }
1039     if (pid != 0) {
1040         /* parent */
1041         if (locked)
1042             relock(pid);
1043         exit(0);                /* parent dies */
1044     }
1045     setsid();
1046     chdir("/");
1047     close(0);
1048     close(1);
1049     close(2);
1050     detached = 1;
1051     if (!log_to_file && !log_to_specific_fd)
1052         log_to_fd = -1;
1053     /* update pid files if they have been written already */
1054     if (pidfilename[0])
1055         create_pidfile();
1056     if (linkpidfile[0])
1057         create_linkpidfile();
1058     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1059     script_setenv("PPPD_PID", numbuf, 1);
1060 }
1061
1062 /*
1063  * reopen_log - (re)open our connection to syslog.
1064  */
1065 void
1066 reopen_log()
1067 {
1068 #ifdef ULTRIX
1069     openlog("pppd", LOG_PID);
1070 #else
1071     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1072     setlogmask(LOG_UPTO(LOG_INFO));
1073 #endif
1074 }
1075
1076 /*
1077  * Create a file containing our process ID.
1078  */
1079 static void
1080 create_pidfile()
1081 {
1082     FILE *pidfile;
1083
1084     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1085              _PATH_VARRUN, ifname);
1086     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1087         fprintf(pidfile, "%d\n", getpid());
1088         (void) fclose(pidfile);
1089     } else {
1090         error("Failed to create pid file %s: %m", pidfilename);
1091         pidfilename[0] = 0;
1092     }
1093 }
1094
1095 static void
1096 create_linkpidfile()
1097 {
1098     FILE *pidfile;
1099
1100     if (linkname[0] == 0)
1101         return;
1102     script_setenv("LINKNAME", linkname, 1);
1103     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1104              _PATH_VARRUN, linkname);
1105     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1106         fprintf(pidfile, "%d\n", getpid());
1107         if (ifname[0])
1108             fprintf(pidfile, "%s\n", ifname);
1109         (void) fclose(pidfile);
1110     } else {
1111         error("Failed to create pid file %s: %m", linkpidfile);
1112         linkpidfile[0] = 0;
1113     }
1114 }
1115
1116 /*
1117  * holdoff_end - called via a timeout when the holdoff period ends.
1118  */
1119 static void
1120 holdoff_end(arg)
1121     void *arg;
1122 {
1123     new_phase(PHASE_DORMANT);
1124 }
1125
1126 /* List of protocol names, to make our messages a little more informative. */
1127 struct protocol_list {
1128     u_short     proto;
1129     const char  *name;
1130 } protocol_list[] = {
1131     { 0x21,     "IP" },
1132     { 0x23,     "OSI Network Layer" },
1133     { 0x25,     "Xerox NS IDP" },
1134     { 0x27,     "DECnet Phase IV" },
1135     { 0x29,     "Appletalk" },
1136     { 0x2b,     "Novell IPX" },
1137     { 0x2d,     "VJ compressed TCP/IP" },
1138     { 0x2f,     "VJ uncompressed TCP/IP" },
1139     { 0x31,     "Bridging PDU" },
1140     { 0x33,     "Stream Protocol ST-II" },
1141     { 0x35,     "Banyan Vines" },
1142     { 0x39,     "AppleTalk EDDP" },
1143     { 0x3b,     "AppleTalk SmartBuffered" },
1144     { 0x3d,     "Multi-Link" },
1145     { 0x3f,     "NETBIOS Framing" },
1146     { 0x41,     "Cisco Systems" },
1147     { 0x43,     "Ascom Timeplex" },
1148     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
1149     { 0x47,     "DCA Remote Lan" },
1150     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
1151     { 0x4b,     "SNA over 802.2" },
1152     { 0x4d,     "SNA" },
1153     { 0x4f,     "IP6 Header Compression" },
1154     { 0x6f,     "Stampede Bridging" },
1155     { 0xfb,     "single-link compression" },
1156     { 0xfd,     "1st choice compression" },
1157     { 0x0201,   "802.1d Hello Packets" },
1158     { 0x0203,   "IBM Source Routing BPDU" },
1159     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
1160     { 0x0231,   "Luxcom" },
1161     { 0x0233,   "Sigma Network Systems" },
1162     { 0x8021,   "Internet Protocol Control Protocol" },
1163     { 0x8023,   "OSI Network Layer Control Protocol" },
1164     { 0x8025,   "Xerox NS IDP Control Protocol" },
1165     { 0x8027,   "DECnet Phase IV Control Protocol" },
1166     { 0x8029,   "Appletalk Control Protocol" },
1167     { 0x802b,   "Novell IPX Control Protocol" },
1168     { 0x8031,   "Bridging NCP" },
1169     { 0x8033,   "Stream Protocol Control Protocol" },
1170     { 0x8035,   "Banyan Vines Control Protocol" },
1171     { 0x803d,   "Multi-Link Control Protocol" },
1172     { 0x803f,   "NETBIOS Framing Control Protocol" },
1173     { 0x8041,   "Cisco Systems Control Protocol" },
1174     { 0x8043,   "Ascom Timeplex" },
1175     { 0x8045,   "Fujitsu LBLB Control Protocol" },
1176     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
1177     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
1178     { 0x804b,   "SNA over 802.2 Control Protocol" },
1179     { 0x804d,   "SNA Control Protocol" },
1180     { 0x804f,   "IP6 Header Compression Control Protocol" },
1181     { 0x006f,   "Stampede Bridging Control Protocol" },
1182     { 0x80fb,   "Single Link Compression Control Protocol" },
1183     { 0x80fd,   "Compression Control Protocol" },
1184     { 0xc021,   "Link Control Protocol" },
1185     { 0xc023,   "Password Authentication Protocol" },
1186     { 0xc025,   "Link Quality Report" },
1187     { 0xc027,   "Shiva Password Authentication Protocol" },
1188     { 0xc029,   "CallBack Control Protocol (CBCP)" },
1189     { 0xc081,   "Container Control Protocol" },
1190     { 0xc223,   "Challenge Handshake Authentication Protocol" },
1191     { 0xc281,   "Proprietary Authentication Protocol" },
1192     { 0,        NULL },
1193 };
1194
1195 /*
1196  * protocol_name - find a name for a PPP protocol.
1197  */
1198 const char *
1199 protocol_name(proto)
1200     int proto;
1201 {
1202     struct protocol_list *lp;
1203
1204     for (lp = protocol_list; lp->proto != 0; ++lp)
1205         if (proto == lp->proto)
1206             return lp->name;
1207     return NULL;
1208 }
1209
1210 /*
1211  * get_input - called when incoming data is available.
1212  */
1213 static void
1214 get_input()
1215 {
1216     int len, i;
1217     u_char *p;
1218     u_short protocol;
1219     struct protent *protp;
1220
1221     p = inpacket_buf;   /* point to beginning of packet buffer */
1222
1223     len = read_packet(inpacket_buf);
1224     if (len < 0)
1225         return;
1226
1227     if (len == 0) {
1228         notice("Modem hangup");
1229         hungup = 1;
1230         status = EXIT_HANGUP;
1231         lcp_lowerdown(0);       /* serial link is no longer available */
1232         link_terminated(0);
1233         return;
1234     }
1235
1236     if (debug /*&& (debugflags & DBG_INPACKET)*/)
1237         dbglog("rcvd %P", p, len);
1238
1239     if (len < PPP_HDRLEN) {
1240         MAINDEBUG(("io(): Received short packet."));
1241         return;
1242     }
1243
1244     p += 2;                             /* Skip address and control */
1245     GETSHORT(protocol, p);
1246     len -= PPP_HDRLEN;
1247
1248     /*
1249      * Toss all non-LCP packets unless LCP is OPEN.
1250      */
1251     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1252         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1253         return;
1254     }
1255
1256     /*
1257      * Until we get past the authentication phase, toss all packets
1258      * except LCP, LQR and authentication packets.
1259      */
1260     if (phase <= PHASE_AUTHENTICATE
1261         && !(protocol == PPP_LCP || protocol == PPP_LQR
1262              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1263         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1264                    protocol, phase));
1265         return;
1266     }
1267
1268     /*
1269      * Upcall the proper protocol input routine.
1270      */
1271     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1272         if (protp->protocol == protocol && protp->enabled_flag) {
1273             (*protp->input)(0, p, len);
1274             return;
1275         }
1276         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1277             && protp->datainput != NULL) {
1278             (*protp->datainput)(0, p, len);
1279             return;
1280         }
1281     }
1282
1283     if (debug) {
1284         const char *pname = protocol_name(protocol);
1285         if (pname != NULL)
1286             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1287         else
1288             warn("Unsupported protocol 0x%x received", protocol);
1289     }
1290     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1291 }
1292
1293 /*
1294  * new_phase - signal the start of a new phase of pppd's operation.
1295  */
1296 void
1297 new_phase(p)
1298     int p;
1299 {
1300     phase = p;
1301     if (new_phase_hook)
1302         (*new_phase_hook)(p);
1303 }
1304
1305 /*
1306  * die - clean up state and exit with the specified status.
1307  */
1308 void
1309 die(status)
1310     int status;
1311 {
1312     cleanup();
1313     syslog(LOG_INFO, "Exit.");
1314     exit(status);
1315 }
1316
1317 /*
1318  * cleanup - restore anything which needs to be restored before we exit
1319  */
1320 /* ARGSUSED */
1321 static void
1322 cleanup()
1323 {
1324     sys_cleanup();
1325
1326     if (fd_ppp >= 0)
1327         disestablish_ppp(ttyfd);
1328     if (real_ttyfd >= 0)
1329         close_tty();
1330
1331     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
1332         warn("unable to delete pid file %s: %m", pidfilename);
1333     pidfilename[0] = 0;
1334     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT) 
1335         warn("unable to delete pid file %s: %m", linkpidfile);
1336     linkpidfile[0] = 0;
1337
1338     if (locked)
1339         unlock();
1340
1341     if (pppdb != NULL)
1342         cleanup_db();
1343 }
1344
1345 /*
1346  * close_tty - restore the terminal device and close it.
1347  */
1348 static void
1349 close_tty()
1350 {
1351     /* drop dtr to hang up */
1352     if (!default_device && modem) {
1353         setdtr(real_ttyfd, 0);
1354         /*
1355          * This sleep is in case the serial port has CLOCAL set by default,
1356          * and consequently will reassert DTR when we close the device.
1357          */
1358         sleep(1);
1359     }
1360
1361     restore_tty(real_ttyfd);
1362
1363     if (tty_mode != (mode_t) -1) {
1364         if (fchmod(real_ttyfd, tty_mode) != 0) {
1365             /* XXX if devnam is a symlink, this will change the link */
1366             chmod(devnam, tty_mode);
1367         }
1368     }
1369
1370     close(real_ttyfd);
1371     real_ttyfd = -1;
1372 }
1373
1374 /*
1375  * update_link_stats - get stats at link termination.
1376  */
1377 void
1378 update_link_stats(u)
1379     int u;
1380 {
1381     struct timeval now;
1382     char numbuf[32];
1383
1384     if (!get_ppp_stats(u, &link_stats)
1385         || gettimeofday(&now, NULL) < 0)
1386         return;
1387     link_connect_time = now.tv_sec - start_time.tv_sec;
1388     link_stats_valid = 1;
1389
1390     slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1391     script_setenv("CONNECT_TIME", numbuf, 0);
1392     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1393     script_setenv("BYTES_SENT", numbuf, 0);
1394     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1395     script_setenv("BYTES_RCVD", numbuf, 0);
1396 }
1397
1398
1399 struct  callout {
1400     struct timeval      c_time;         /* time at which to call routine */
1401     void                *c_arg;         /* argument to routine */
1402     void                (*c_func) __P((void *)); /* routine */
1403     struct              callout *c_next;
1404 };
1405
1406 static struct callout *callout = NULL;  /* Callout list */
1407 static struct timeval timenow;          /* Current time */
1408
1409 /*
1410  * timeout - Schedule a timeout.
1411  *
1412  * Note that this timeout takes the number of seconds, NOT hz (as in
1413  * the kernel).
1414  */
1415 void
1416 timeout(func, arg, time)
1417     void (*func) __P((void *));
1418     void *arg;
1419     int time;
1420 {
1421     struct callout *newp, *p, **pp;
1422   
1423     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1424   
1425     /*
1426      * Allocate timeout.
1427      */
1428     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1429         fatal("Out of memory in timeout()!");
1430     newp->c_arg = arg;
1431     newp->c_func = func;
1432     gettimeofday(&timenow, NULL);
1433     newp->c_time.tv_sec = timenow.tv_sec + time;
1434     newp->c_time.tv_usec = timenow.tv_usec;
1435   
1436     /*
1437      * Find correct place and link it in.
1438      */
1439     for (pp = &callout; (p = *pp); pp = &p->c_next)
1440         if (newp->c_time.tv_sec < p->c_time.tv_sec
1441             || (newp->c_time.tv_sec == p->c_time.tv_sec
1442                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1443             break;
1444     newp->c_next = p;
1445     *pp = newp;
1446 }
1447
1448
1449 /*
1450  * untimeout - Unschedule a timeout.
1451  */
1452 void
1453 untimeout(func, arg)
1454     void (*func) __P((void *));
1455     void *arg;
1456 {
1457     struct callout **copp, *freep;
1458   
1459     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1460   
1461     /*
1462      * Find first matching timeout and remove it from the list.
1463      */
1464     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1465         if (freep->c_func == func && freep->c_arg == arg) {
1466             *copp = freep->c_next;
1467             free((char *) freep);
1468             break;
1469         }
1470 }
1471
1472
1473 /*
1474  * calltimeout - Call any timeout routines which are now due.
1475  */
1476 static void
1477 calltimeout()
1478 {
1479     struct callout *p;
1480
1481     while (callout != NULL) {
1482         p = callout;
1483
1484         if (gettimeofday(&timenow, NULL) < 0)
1485             fatal("Failed to get time of day: %m");
1486         if (!(p->c_time.tv_sec < timenow.tv_sec
1487               || (p->c_time.tv_sec == timenow.tv_sec
1488                   && p->c_time.tv_usec <= timenow.tv_usec)))
1489             break;              /* no, it's not time yet */
1490
1491         callout = p->c_next;
1492         (*p->c_func)(p->c_arg);
1493
1494         free((char *) p);
1495     }
1496 }
1497
1498
1499 /*
1500  * timeleft - return the length of time until the next timeout is due.
1501  */
1502 static struct timeval *
1503 timeleft(tvp)
1504     struct timeval *tvp;
1505 {
1506     if (callout == NULL)
1507         return NULL;
1508
1509     gettimeofday(&timenow, NULL);
1510     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1511     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1512     if (tvp->tv_usec < 0) {
1513         tvp->tv_usec += 1000000;
1514         tvp->tv_sec -= 1;
1515     }
1516     if (tvp->tv_sec < 0)
1517         tvp->tv_sec = tvp->tv_usec = 0;
1518
1519     return tvp;
1520 }
1521
1522
1523 /*
1524  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1525  */
1526 static void
1527 kill_my_pg(sig)
1528     int sig;
1529 {
1530     struct sigaction act, oldact;
1531
1532     act.sa_handler = SIG_IGN;
1533     act.sa_flags = 0;
1534     kill(0, sig);
1535     sigaction(sig, &act, &oldact);
1536     sigaction(sig, &oldact, NULL);
1537 }
1538
1539
1540 /*
1541  * hup - Catch SIGHUP signal.
1542  *
1543  * Indicates that the physical layer has been disconnected.
1544  * We don't rely on this indication; if the user has sent this
1545  * signal, we just take the link down.
1546  */
1547 static void
1548 hup(sig)
1549     int sig;
1550 {
1551     info("Hangup (SIGHUP)");
1552     kill_link = 1;
1553     if (status != EXIT_HANGUP)
1554         status = EXIT_USER_REQUEST;
1555     if (conn_running)
1556         /* Send the signal to the [dis]connector process(es) also */
1557         kill_my_pg(sig);
1558     if (charshunt_pid)
1559         kill(charshunt_pid, sig);
1560     if (waiting)
1561         siglongjmp(sigjmp, 1);
1562 }
1563
1564
1565 /*
1566  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1567  *
1568  * Indicates that we should initiate a graceful disconnect and exit.
1569  */
1570 /*ARGSUSED*/
1571 static void
1572 term(sig)
1573     int sig;
1574 {
1575     info("Terminating on signal %d.", sig);
1576     persist = 0;                /* don't try to restart */
1577     kill_link = 1;
1578     status = EXIT_USER_REQUEST;
1579     if (conn_running)
1580         /* Send the signal to the [dis]connector process(es) also */
1581         kill_my_pg(sig);
1582     if (charshunt_pid)
1583         kill(charshunt_pid, sig);
1584     if (waiting)
1585         siglongjmp(sigjmp, 1);
1586 }
1587
1588
1589 /*
1590  * chld - Catch SIGCHLD signal.
1591  * Sets a flag so we will call reap_kids in the mainline.
1592  */
1593 static void
1594 chld(sig)
1595     int sig;
1596 {
1597     got_sigchld = 1;
1598     if (waiting)
1599         siglongjmp(sigjmp, 1);
1600 }
1601
1602
1603 /*
1604  * toggle_debug - Catch SIGUSR1 signal.
1605  *
1606  * Toggle debug flag.
1607  */
1608 /*ARGSUSED*/
1609 static void
1610 toggle_debug(sig)
1611     int sig;
1612 {
1613     debug = !debug;
1614     if (debug) {
1615         setlogmask(LOG_UPTO(LOG_DEBUG));
1616     } else {
1617         setlogmask(LOG_UPTO(LOG_WARNING));
1618     }
1619 }
1620
1621
1622 /*
1623  * open_ccp - Catch SIGUSR2 signal.
1624  *
1625  * Try to (re)negotiate compression.
1626  */
1627 /*ARGSUSED*/
1628 static void
1629 open_ccp(sig)
1630     int sig;
1631 {
1632     open_ccp_flag = 1;
1633     if (waiting)
1634         siglongjmp(sigjmp, 1);
1635 }
1636
1637
1638 /*
1639  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1640  */
1641 static void
1642 bad_signal(sig)
1643     int sig;
1644 {
1645     static int crashed = 0;
1646
1647     if (crashed)
1648         _exit(127);
1649     crashed = 1;
1650     error("Fatal signal %d", sig);
1651     if (conn_running)
1652         kill_my_pg(SIGTERM);
1653     if (charshunt_pid)
1654         kill(charshunt_pid, SIGTERM);
1655     die(127);
1656 }
1657
1658
1659 /*
1660  * device_script - run a program to talk to the serial device
1661  * (e.g. to run the connector or disconnector script).
1662  */
1663 static int
1664 device_script(program, in, out, dont_wait)
1665     char *program;
1666     int in, out;
1667     int dont_wait;
1668 {
1669     int pid;
1670     int status = -1;
1671     int errfd;
1672
1673     ++conn_running;
1674     pid = fork();
1675
1676     if (pid < 0) {
1677         --conn_running;
1678         error("Failed to create child process: %m");
1679         return -1;
1680     }
1681
1682     if (pid == 0) {
1683         sys_close();
1684         closelog();
1685         if (in == 2) {
1686             /* aargh!!! */
1687             int newin = dup(in);
1688             if (in == out)
1689                 out = newin;
1690             in = newin;
1691         } else if (out == 2) {
1692             out = dup(out);
1693         }
1694         if (log_to_fd >= 0) {
1695             if (log_to_fd != 2)
1696                 dup2(log_to_fd, 2);
1697         } else {
1698             close(2);
1699             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1700             if (errfd >= 0 && errfd != 2) {
1701                 dup2(errfd, 2);
1702                 close(errfd);
1703             }
1704         }
1705         if (in != 0) {
1706             if (out == 0)
1707                 out = dup(out);
1708             dup2(in, 0);
1709         }
1710         if (out != 1) {
1711             dup2(out, 1);
1712         }
1713         if (real_ttyfd > 2)
1714             close(real_ttyfd);
1715         if (pty_master > 2)
1716             close(pty_master);
1717         if (pty_slave > 2)
1718             close(pty_slave);
1719         setuid(uid);
1720         if (getuid() != uid) {
1721             error("setuid failed");
1722             exit(1);
1723         }
1724         setgid(getgid());
1725         execl("/bin/sh", "sh", "-c", program, (char *)0);
1726         error("could not exec /bin/sh: %m");
1727         exit(99);
1728         /* NOTREACHED */
1729     }
1730
1731     if (dont_wait) {
1732         record_child(pid, program, NULL, NULL);
1733         status = 0;
1734     } else {
1735         while (waitpid(pid, &status, 0) < 0) {
1736             if (errno == EINTR)
1737                 continue;
1738             fatal("error waiting for (dis)connection process: %m");
1739         }
1740         --conn_running;
1741     }
1742
1743     return (status == 0 ? 0 : -1);
1744 }
1745
1746
1747 /*
1748  * run-program - execute a program with given arguments,
1749  * but don't wait for it.
1750  * If the program can't be executed, logs an error unless
1751  * must_exist is 0 and the program file doesn't exist.
1752  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1753  * or isn't an executable plain file, or the process ID of the child.
1754  * If done != NULL, (*done)(arg) will be called later (within
1755  * reap_kids) iff the return value is > 0.
1756  */
1757 pid_t
1758 run_program(prog, args, must_exist, done, arg)
1759     char *prog;
1760     char **args;
1761     int must_exist;
1762     void (*done) __P((void *));
1763     void *arg;
1764 {
1765     int pid;
1766     struct stat sbuf;
1767
1768     /*
1769      * First check if the file exists and is executable.
1770      * We don't use access() because that would use the
1771      * real user-id, which might not be root, and the script
1772      * might be accessible only to root.
1773      */
1774     errno = EINVAL;
1775     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1776         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1777         if (must_exist || errno != ENOENT)
1778             warn("Can't execute %s: %m", prog);
1779         return 0;
1780     }
1781
1782     pid = fork();
1783     if (pid == -1) {
1784         error("Failed to create child process for %s: %m", prog);
1785         return -1;
1786     }
1787     if (pid == 0) {
1788         int new_fd;
1789
1790         /* Leave the current location */
1791         (void) setsid();        /* No controlling tty. */
1792         (void) umask (S_IRWXG|S_IRWXO);
1793         (void) chdir ("/");     /* no current directory. */
1794         setuid(0);              /* set real UID = root */
1795         setgid(getegid());
1796
1797         /* Ensure that nothing of our device environment is inherited. */
1798         sys_close();
1799         closelog();
1800         close (0);
1801         close (1);
1802         close (2);
1803         close (ttyfd);  /* tty interface to the ppp device */
1804         if (real_ttyfd >= 0)
1805             close(real_ttyfd);
1806
1807         /* Don't pass handles to the PPP device, even by accident. */
1808         new_fd = open (_PATH_DEVNULL, O_RDWR);
1809         if (new_fd >= 0) {
1810             if (new_fd != 0) {
1811                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1812                 close (new_fd);
1813             }
1814             dup2 (0, 1); /* stdout -> /dev/null */
1815             dup2 (0, 2); /* stderr -> /dev/null */
1816         }
1817
1818 #ifdef BSD
1819         /* Force the priority back to zero if pppd is running higher. */
1820         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1821             warn("can't reset priority to 0: %m"); 
1822 #endif
1823
1824         /* SysV recommends a second fork at this point. */
1825
1826         /* run the program */
1827         execve(prog, args, script_env);
1828         if (must_exist || errno != ENOENT) {
1829             /* have to reopen the log, there's nowhere else
1830                for the message to go. */
1831             reopen_log();
1832             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1833             closelog();
1834         }
1835         _exit(-1);
1836     }
1837
1838     if (debug)
1839         dbglog("Script %s started (pid %d)", prog, pid);
1840     record_child(pid, prog, done, arg);
1841
1842     return pid;
1843 }
1844
1845
1846 /*
1847  * record_child - add a child process to the list for reap_kids
1848  * to use.
1849  */
1850 static void
1851 record_child(pid, prog, done, arg)
1852     int pid;
1853     char *prog;
1854     void (*done) __P((void *));
1855     void *arg;
1856 {
1857     struct subprocess *chp;
1858
1859     ++n_children;
1860
1861     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1862     if (chp == NULL) {
1863         warn("losing track of %s process", prog);
1864     } else {
1865         chp->pid = pid;
1866         chp->prog = prog;
1867         chp->done = done;
1868         chp->arg = arg;
1869         chp->next = children;
1870         children = chp;
1871     }
1872 }
1873
1874
1875 /*
1876  * reap_kids - get status from any dead child processes,
1877  * and log a message for abnormal terminations.
1878  */
1879 static int
1880 reap_kids(waitfor)
1881     int waitfor;
1882 {
1883     int pid, status;
1884     struct subprocess *chp, **prevp;
1885
1886     got_sigchld = 0;
1887     if (n_children == 0)
1888         return 0;
1889     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1890            && pid != 0) {
1891         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1892             if (chp->pid == pid) {
1893                 --n_children;
1894                 *prevp = chp->next;
1895                 break;
1896             }
1897         }
1898         if (WIFSIGNALED(status)) {
1899             warn("Child process %s (pid %d) terminated with signal %d",
1900                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1901         } else if (debug)
1902             dbglog("Script %s finished (pid %d), status = 0x%x",
1903                    (chp? chp->prog: "??"), pid, status);
1904         if (chp && chp->done)
1905             (*chp->done)(chp->arg);
1906         if (chp)
1907             free(chp);
1908     }
1909     if (pid == -1) {
1910         if (errno == ECHILD)
1911             return -1;
1912         if (errno != EINTR)
1913             error("Error waiting for child process: %m");
1914     }
1915     return 0;
1916 }
1917
1918
1919 /*
1920  * novm - log an error message saying we ran out of memory, and die.
1921  */
1922 void
1923 novm(msg)
1924     char *msg;
1925 {
1926     fatal("Virtual memory exhausted allocating %s\n", msg);
1927 }
1928
1929 /*
1930  * script_setenv - set an environment variable value to be used
1931  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1932  */
1933 void
1934 script_setenv(var, value, iskey)
1935     char *var, *value;
1936     int iskey;
1937 {
1938     size_t varl = strlen(var);
1939     size_t vl = varl + strlen(value) + 2;
1940     int i;
1941     char *p, *newstring;
1942
1943     newstring = (char *) malloc(vl+1);
1944     if (newstring == 0)
1945         return;
1946     *newstring++ = iskey;
1947     slprintf(newstring, vl, "%s=%s", var, value);
1948
1949     /* check if this variable is already set */
1950     if (script_env != 0) {
1951         for (i = 0; (p = script_env[i]) != 0; ++i) {
1952             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1953                 if (p[-1] && pppdb != NULL)
1954                     delete_db_key(p);
1955                 free(p-1);
1956                 script_env[i] = newstring;
1957                 if (iskey && pppdb != NULL)
1958                     add_db_key(newstring);
1959                 update_db_entry();
1960                 return;
1961             }
1962         }
1963     } else {
1964         /* no space allocated for script env. ptrs. yet */
1965         i = 0;
1966         script_env = (char **) malloc(16 * sizeof(char *));
1967         if (script_env == 0)
1968             return;
1969         s_env_nalloc = 16;
1970     }
1971
1972     /* reallocate script_env with more space if needed */
1973     if (i + 1 >= s_env_nalloc) {
1974         int new_n = i + 17;
1975         char **newenv = (char **) realloc((void *)script_env,
1976                                           new_n * sizeof(char *));
1977         if (newenv == 0)
1978             return;
1979         script_env = newenv;
1980         s_env_nalloc = new_n;
1981     }
1982
1983     script_env[i] = newstring;
1984     script_env[i+1] = 0;
1985
1986     if (pppdb != NULL) {
1987         if (iskey)
1988             add_db_key(newstring);
1989         update_db_entry();
1990     }
1991 }
1992
1993 /*
1994  * script_unsetenv - remove a variable from the environment
1995  * for scripts.
1996  */
1997 void
1998 script_unsetenv(var)
1999     char *var;
2000 {
2001     int vl = strlen(var);
2002     int i;
2003     char *p;
2004
2005     if (script_env == 0)
2006         return;
2007     for (i = 0; (p = script_env[i]) != 0; ++i) {
2008         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2009             if (p[-1] && pppdb != NULL)
2010                 delete_db_key(p);
2011             free(p-1);
2012             while ((script_env[i] = script_env[i+1]) != 0)
2013                 ++i;
2014             break;
2015         }
2016     }
2017     if (pppdb != NULL)
2018         update_db_entry();
2019 }
2020
2021 /*
2022  * update_db_entry - update our entry in the database.
2023  */
2024 static void
2025 update_db_entry()
2026 {
2027     TDB_DATA key, dbuf;
2028     int vlen, i;
2029     char *p, *q, *vbuf;
2030
2031     if (script_env == NULL)
2032         return;
2033     vlen = 0;
2034     for (i = 0; (p = script_env[i]) != 0; ++i)
2035         vlen += strlen(p) + 1;
2036     vbuf = malloc(vlen);
2037     if (vbuf == 0)
2038         novm("database entry");
2039     q = vbuf;
2040     for (i = 0; (p = script_env[i]) != 0; ++i)
2041         q += slprintf(q, vbuf + vlen - q, "%s;", p);
2042
2043     key.dptr = db_key;
2044     key.dsize = strlen(db_key);
2045     dbuf.dptr = vbuf;
2046     dbuf.dsize = vlen;
2047     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2048         error("tdb_store failed: %s", tdb_error(pppdb));
2049
2050 }
2051
2052 /*
2053  * add_db_key - add a key that we can use to look up our database entry.
2054  */
2055 static void
2056 add_db_key(str)
2057     const char *str;
2058 {
2059     TDB_DATA key, dbuf;
2060
2061     key.dptr = (char *) str;
2062     key.dsize = strlen(str);
2063     dbuf.dptr = db_key;
2064     dbuf.dsize = strlen(db_key);
2065     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2066         error("tdb_store key failed: %s", tdb_error(pppdb));
2067 }
2068
2069 /*
2070  * delete_db_key - delete a key for looking up our database entry.
2071  */
2072 static void
2073 delete_db_key(str)
2074     const char *str;
2075 {
2076     TDB_DATA key;
2077
2078     key.dptr = (char *) str;
2079     key.dsize = strlen(str);
2080     tdb_delete(pppdb, key);
2081 }
2082
2083 /*
2084  * cleanup_db - delete all the entries we put in the database.
2085  */
2086 static void
2087 cleanup_db()
2088 {
2089     TDB_DATA key;
2090     int i;
2091     char *p;
2092
2093     key.dptr = db_key;
2094     key.dsize = strlen(db_key);
2095     tdb_delete(pppdb, key);
2096     for (i = 0; (p = script_env[i]) != 0; ++i)
2097         if (p[-1])
2098             delete_db_key(p);
2099 }
2100
2101 /*
2102  * open_socket - establish a stream socket connection to the nominated
2103  * host and port.
2104  */
2105 static int
2106 open_socket(dest)
2107     char *dest;
2108 {
2109     char *sep, *endp = NULL;
2110     int sock, port = -1;
2111     u_int32_t host;
2112     struct hostent *hent;
2113     struct sockaddr_in sad;
2114
2115     /* parse host:port and resolve host to an IP address */
2116     sep = strchr(dest, ':');
2117     if (sep != NULL)
2118         port = strtol(sep+1, &endp, 10);
2119     if (port < 0 || endp == sep+1 || sep == dest) {
2120         error("Can't parse host:port for socket destination");
2121         return -1;
2122     }
2123     *sep = 0;
2124     host = inet_addr(dest);
2125     if (host == (u_int32_t) -1) {
2126         hent = gethostbyname(dest);
2127         if (hent == NULL) {
2128             error("%s: unknown host in socket option", dest);
2129             *sep = ':';
2130             return -1;
2131         }
2132         host = *(u_int32_t *)(hent->h_addr_list[0]);
2133     }
2134     *sep = ':';
2135
2136     /* get a socket and connect it to the other end */
2137     sock = socket(PF_INET, SOCK_STREAM, 0);
2138     if (sock < 0) {
2139         error("Can't create socket: %m");
2140         return -1;
2141     }
2142     memset(&sad, 0, sizeof(sad));
2143     sad.sin_family = AF_INET;
2144     sad.sin_port = htons(port);
2145     sad.sin_addr.s_addr = host;
2146     if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
2147         error("Can't connect to %s: %m", dest);
2148         close(sock);
2149         return -1;
2150     }
2151
2152     return sock;
2153 }
2154
2155 /*
2156  * start_charshunt - create a child process to run the character shunt.
2157  */
2158 static int
2159 start_charshunt(ifd, ofd)
2160     int ifd, ofd;
2161 {
2162     int cpid;
2163
2164     cpid = fork();
2165     if (cpid == -1) {
2166         error("Can't fork process for character shunt: %m");
2167         return 0;
2168     }
2169     if (cpid == 0) {
2170         /* child */
2171         close(pty_slave);
2172         setuid(uid);
2173         if (getuid() != uid)
2174             fatal("setuid failed");
2175         setgid(getgid());
2176         if (!nodetach)
2177             log_to_fd = -1;
2178         charshunt(ifd, ofd, record_file);
2179         exit(0);
2180     }
2181     charshunt_pid = cpid;
2182     close(pty_master);
2183     pty_master = -1;
2184     ttyfd = pty_slave;
2185     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2186     return 1;
2187 }
2188
2189 static void
2190 charshunt_done(arg)
2191     void *arg;
2192 {
2193     charshunt_pid = 0;
2194 }
2195
2196 /*
2197  * charshunt - the character shunt, which passes characters between
2198  * the pty master side and the serial port (or stdin/stdout).
2199  * This runs as the user (not as root).
2200  * (We assume ofd >= ifd which is true the way this gets called. :-).
2201  */
2202 static void
2203 charshunt(ifd, ofd, record_file)
2204     int ifd, ofd;
2205     char *record_file;
2206 {
2207     int n, nfds;
2208     fd_set ready, writey;
2209     u_char *ibufp, *obufp;
2210     int nibuf, nobuf;
2211     int flags;
2212     int pty_readable, stdin_readable;
2213     struct timeval lasttime;
2214     FILE *recordf = NULL;
2215     int ilevel, olevel, max_level;
2216     struct timeval levelt, tout, *top;
2217
2218     /*
2219      * Reset signal handlers.
2220      */
2221     signal(SIGHUP, SIG_IGN);            /* Hangup */
2222     signal(SIGINT, SIG_DFL);            /* Interrupt */
2223     signal(SIGTERM, SIG_DFL);           /* Terminate */
2224     signal(SIGCHLD, SIG_DFL);
2225     signal(SIGUSR1, SIG_DFL);
2226     signal(SIGUSR2, SIG_DFL);
2227     signal(SIGABRT, SIG_DFL);
2228     signal(SIGALRM, SIG_DFL);
2229     signal(SIGFPE, SIG_DFL);
2230     signal(SIGILL, SIG_DFL);
2231     signal(SIGPIPE, SIG_DFL);
2232     signal(SIGQUIT, SIG_DFL);
2233     signal(SIGSEGV, SIG_DFL);
2234 #ifdef SIGBUS
2235     signal(SIGBUS, SIG_DFL);
2236 #endif
2237 #ifdef SIGEMT
2238     signal(SIGEMT, SIG_DFL);
2239 #endif
2240 #ifdef SIGPOLL
2241     signal(SIGPOLL, SIG_DFL);
2242 #endif
2243 #ifdef SIGPROF
2244     signal(SIGPROF, SIG_DFL);
2245 #endif
2246 #ifdef SIGSYS
2247     signal(SIGSYS, SIG_DFL);
2248 #endif
2249 #ifdef SIGTRAP
2250     signal(SIGTRAP, SIG_DFL);
2251 #endif
2252 #ifdef SIGVTALRM
2253     signal(SIGVTALRM, SIG_DFL);
2254 #endif
2255 #ifdef SIGXCPU
2256     signal(SIGXCPU, SIG_DFL);
2257 #endif
2258 #ifdef SIGXFSZ
2259     signal(SIGXFSZ, SIG_DFL);
2260 #endif
2261
2262     /*
2263      * Open the record file if required.
2264      */
2265     if (record_file != NULL) {
2266         recordf = fopen(record_file, "a");
2267         if (recordf == NULL)
2268             error("Couldn't create record file %s: %m", record_file);
2269     }
2270
2271     /* set all the fds to non-blocking mode */
2272     flags = fcntl(pty_master, F_GETFL);
2273     if (flags == -1
2274         || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2275         warn("couldn't set pty master to nonblock: %m");
2276     flags = fcntl(ifd, F_GETFL);
2277     if (flags == -1
2278         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2279         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2280     if (ofd != ifd) {
2281         flags = fcntl(ofd, F_GETFL);
2282         if (flags == -1
2283             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2284             warn("couldn't set stdout to nonblock: %m");
2285     }
2286
2287     nibuf = nobuf = 0;
2288     ibufp = obufp = NULL;
2289     pty_readable = stdin_readable = 1;
2290
2291     ilevel = olevel = 0;
2292     gettimeofday(&levelt, NULL);
2293     if (max_data_rate) {
2294         max_level = max_data_rate / 10;
2295         if (max_level < 100)
2296             max_level = 100;
2297     } else
2298         max_level = sizeof(inpacket_buf) + 1;
2299
2300     nfds = (ofd > pty_master? ofd: pty_master) + 1;
2301     if (recordf != NULL) {
2302         gettimeofday(&lasttime, NULL);
2303         putc(7, recordf);       /* put start marker */
2304         putc(lasttime.tv_sec >> 24, recordf);
2305         putc(lasttime.tv_sec >> 16, recordf);
2306         putc(lasttime.tv_sec >> 8, recordf);
2307         putc(lasttime.tv_sec, recordf);
2308         lasttime.tv_usec = 0;
2309     }
2310
2311     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2312         top = 0;
2313         tout.tv_sec = 0;
2314         tout.tv_usec = 10000;
2315         FD_ZERO(&ready);
2316         FD_ZERO(&writey);
2317         if (nibuf != 0) {
2318             if (ilevel >= max_level)
2319                 top = &tout;
2320             else
2321                 FD_SET(pty_master, &writey);
2322         } else if (stdin_readable)
2323             FD_SET(ifd, &ready);
2324         if (nobuf != 0) {
2325             if (olevel >= max_level)
2326                 top = &tout;
2327             else
2328                 FD_SET(ofd, &writey);
2329         } else if (pty_readable)
2330             FD_SET(pty_master, &ready);
2331         if (select(nfds, &ready, &writey, NULL, top) < 0) {
2332             if (errno != EINTR)
2333                 fatal("select");
2334             continue;
2335         }
2336         if (max_data_rate) {
2337             double dt;
2338             int nbt;
2339             struct timeval now;
2340
2341             gettimeofday(&now, NULL);
2342             dt = (now.tv_sec - levelt.tv_sec
2343                   + (now.tv_usec - levelt.tv_usec) / 1e6);
2344             nbt = (int)(dt * max_data_rate);
2345             ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2346             olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2347             levelt = now;
2348         } else
2349             ilevel = olevel = 0;
2350         if (FD_ISSET(ifd, &ready)) {
2351             ibufp = inpacket_buf;
2352             nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2353             if (nibuf < 0 && errno == EIO)
2354                 nibuf = 0;
2355             if (nibuf < 0) {
2356                 if (!(errno == EINTR || errno == EAGAIN)) {
2357                     error("Error reading standard input: %m");
2358                     break;
2359                 }
2360                 nibuf = 0;
2361             } else if (nibuf == 0) {
2362                 /* end of file from stdin */
2363                 stdin_readable = 0;
2364                 /* do a 0-length write, hopefully this will generate
2365                    an EOF (hangup) on the slave side. */
2366                 write(pty_master, inpacket_buf, 0);
2367                 if (recordf)
2368                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
2369                         recordf = NULL;
2370             } else {
2371                 FD_SET(pty_master, &writey);
2372                 if (recordf)
2373                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2374                         recordf = NULL;
2375             }
2376         }
2377         if (FD_ISSET(pty_master, &ready)) {
2378             obufp = outpacket_buf;
2379             nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2380             if (nobuf < 0 && errno == EIO)
2381                 nobuf = 0;
2382             if (nobuf < 0) {
2383                 if (!(errno == EINTR || errno == EAGAIN)) {
2384                     error("Error reading pseudo-tty master: %m");
2385                     break;
2386                 }
2387                 nobuf = 0;
2388             } else if (nobuf == 0) {
2389                 /* end of file from the pty - slave side has closed */
2390                 pty_readable = 0;
2391                 stdin_readable = 0;     /* pty is not writable now */
2392                 nibuf = 0;
2393                 close(ofd);
2394                 if (recordf)
2395                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
2396                         recordf = NULL;
2397             } else {
2398                 FD_SET(ofd, &writey);
2399                 if (recordf)
2400                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2401                         recordf = NULL;
2402             }
2403         }
2404         if (FD_ISSET(ofd, &writey)) {
2405             n = nobuf;
2406             if (olevel + n > max_level)
2407                 n = max_level - olevel;
2408             n = write(ofd, obufp, n);
2409             if (n < 0) {
2410                 if (errno != EIO) {
2411                     error("Error writing standard output: %m");
2412                     break;
2413                 }
2414                 pty_readable = 0;
2415                 nobuf = 0;
2416             } else {
2417                 obufp += n;
2418                 nobuf -= n;
2419                 olevel += n;
2420             }
2421         }
2422         if (FD_ISSET(pty_master, &writey)) {
2423             n = nibuf;
2424             if (ilevel + n > max_level)
2425                 n = max_level - ilevel;
2426             n = write(pty_master, ibufp, n);
2427             if (n < 0) {
2428                 if (errno != EIO) {
2429                     error("Error writing pseudo-tty master: %m");
2430                     break;
2431                 }
2432                 stdin_readable = 0;
2433                 nibuf = 0;
2434             } else {
2435                 ibufp += n;
2436                 nibuf -= n;
2437                 ilevel += n;
2438             }
2439         }
2440     }
2441     exit(0);
2442 }
2443
2444 static int
2445 record_write(f, code, buf, nb, tp)
2446     FILE *f;
2447     int code;
2448     u_char *buf;
2449     int nb;
2450     struct timeval *tp;
2451 {
2452     struct timeval now;
2453     int diff;
2454
2455     gettimeofday(&now, NULL);
2456     now.tv_usec /= 100000;      /* actually 1/10 s, not usec now */
2457     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2458     if (diff > 0) {
2459         if (diff > 255) {
2460             putc(5, f);
2461             putc(diff >> 24, f);
2462             putc(diff >> 16, f);
2463             putc(diff >> 8, f);
2464             putc(diff, f);
2465         } else {
2466             putc(6, f);
2467             putc(diff, f);
2468         }
2469         *tp = now;
2470     }
2471     putc(code, f);
2472     if (buf != NULL) {
2473         putc(nb >> 8, f);
2474         putc(nb, f);
2475         fwrite(buf, nb, 1, f);
2476     }
2477     fflush(f);
2478     if (ferror(f)) {
2479         error("Error writing record file: %m");
2480         return 0;
2481     }
2482     return 1;
2483 }