]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
46863829fdb4bb2a2b874e41ba72e1eecc0d1465
[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.95 2000/04/15 10:10:24 paulus 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     if (iskey) {
1021         create_pidfile();       /* write pid to file */
1022         create_linkpidfile();
1023     }
1024 }
1025
1026 /*
1027  * detach - detach us from the controlling terminal.
1028  */
1029 void
1030 detach()
1031 {
1032     int pid;
1033     char numbuf[16];
1034
1035     if (detached)
1036         return;
1037     if ((pid = fork()) < 0) {
1038         error("Couldn't detach (fork failed: %m)");
1039         die(1);                 /* or just return? */
1040     }
1041     if (pid != 0) {
1042         /* parent */
1043         if (locked)
1044             relock(pid);
1045         exit(0);                /* parent dies */
1046     }
1047     setsid();
1048     chdir("/");
1049     close(0);
1050     close(1);
1051     close(2);
1052     detached = 1;
1053     if (!log_to_file && !log_to_specific_fd)
1054         log_to_fd = -1;
1055     /* update pid files if they have been written already */
1056     if (pidfilename[0])
1057         create_pidfile();
1058     if (linkpidfile[0])
1059         create_linkpidfile();
1060     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1061     script_setenv("PPPD_PID", numbuf, 1);
1062 }
1063
1064 /*
1065  * reopen_log - (re)open our connection to syslog.
1066  */
1067 void
1068 reopen_log()
1069 {
1070 #ifdef ULTRIX
1071     openlog("pppd", LOG_PID);
1072 #else
1073     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1074     setlogmask(LOG_UPTO(LOG_INFO));
1075 #endif
1076 }
1077
1078 /*
1079  * Create a file containing our process ID.
1080  */
1081 static void
1082 create_pidfile()
1083 {
1084     FILE *pidfile;
1085
1086     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1087              _PATH_VARRUN, ifname);
1088     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1089         fprintf(pidfile, "%d\n", getpid());
1090         (void) fclose(pidfile);
1091     } else {
1092         error("Failed to create pid file %s: %m", pidfilename);
1093         pidfilename[0] = 0;
1094     }
1095 }
1096
1097 static void
1098 create_linkpidfile()
1099 {
1100     FILE *pidfile;
1101
1102     if (linkname[0] == 0)
1103         return;
1104     script_setenv("LINKNAME", linkname, 1);
1105     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1106              _PATH_VARRUN, linkname);
1107     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1108         fprintf(pidfile, "%d\n", getpid());
1109         if (ifname[0])
1110             fprintf(pidfile, "%s\n", ifname);
1111         (void) fclose(pidfile);
1112     } else {
1113         error("Failed to create pid file %s: %m", linkpidfile);
1114         linkpidfile[0] = 0;
1115     }
1116 }
1117
1118 /*
1119  * holdoff_end - called via a timeout when the holdoff period ends.
1120  */
1121 static void
1122 holdoff_end(arg)
1123     void *arg;
1124 {
1125     new_phase(PHASE_DORMANT);
1126 }
1127
1128 /* List of protocol names, to make our messages a little more informative. */
1129 struct protocol_list {
1130     u_short     proto;
1131     const char  *name;
1132 } protocol_list[] = {
1133     { 0x21,     "IP" },
1134     { 0x23,     "OSI Network Layer" },
1135     { 0x25,     "Xerox NS IDP" },
1136     { 0x27,     "DECnet Phase IV" },
1137     { 0x29,     "Appletalk" },
1138     { 0x2b,     "Novell IPX" },
1139     { 0x2d,     "VJ compressed TCP/IP" },
1140     { 0x2f,     "VJ uncompressed TCP/IP" },
1141     { 0x31,     "Bridging PDU" },
1142     { 0x33,     "Stream Protocol ST-II" },
1143     { 0x35,     "Banyan Vines" },
1144     { 0x39,     "AppleTalk EDDP" },
1145     { 0x3b,     "AppleTalk SmartBuffered" },
1146     { 0x3d,     "Multi-Link" },
1147     { 0x3f,     "NETBIOS Framing" },
1148     { 0x41,     "Cisco Systems" },
1149     { 0x43,     "Ascom Timeplex" },
1150     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
1151     { 0x47,     "DCA Remote Lan" },
1152     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
1153     { 0x4b,     "SNA over 802.2" },
1154     { 0x4d,     "SNA" },
1155     { 0x4f,     "IP6 Header Compression" },
1156     { 0x6f,     "Stampede Bridging" },
1157     { 0xfb,     "single-link compression" },
1158     { 0xfd,     "1st choice compression" },
1159     { 0x0201,   "802.1d Hello Packets" },
1160     { 0x0203,   "IBM Source Routing BPDU" },
1161     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
1162     { 0x0231,   "Luxcom" },
1163     { 0x0233,   "Sigma Network Systems" },
1164     { 0x8021,   "Internet Protocol Control Protocol" },
1165     { 0x8023,   "OSI Network Layer Control Protocol" },
1166     { 0x8025,   "Xerox NS IDP Control Protocol" },
1167     { 0x8027,   "DECnet Phase IV Control Protocol" },
1168     { 0x8029,   "Appletalk Control Protocol" },
1169     { 0x802b,   "Novell IPX Control Protocol" },
1170     { 0x8031,   "Bridging NCP" },
1171     { 0x8033,   "Stream Protocol Control Protocol" },
1172     { 0x8035,   "Banyan Vines Control Protocol" },
1173     { 0x803d,   "Multi-Link Control Protocol" },
1174     { 0x803f,   "NETBIOS Framing Control Protocol" },
1175     { 0x8041,   "Cisco Systems Control Protocol" },
1176     { 0x8043,   "Ascom Timeplex" },
1177     { 0x8045,   "Fujitsu LBLB Control Protocol" },
1178     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
1179     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
1180     { 0x804b,   "SNA over 802.2 Control Protocol" },
1181     { 0x804d,   "SNA Control Protocol" },
1182     { 0x804f,   "IP6 Header Compression Control Protocol" },
1183     { 0x006f,   "Stampede Bridging Control Protocol" },
1184     { 0x80fb,   "Single Link Compression Control Protocol" },
1185     { 0x80fd,   "Compression Control Protocol" },
1186     { 0xc021,   "Link Control Protocol" },
1187     { 0xc023,   "Password Authentication Protocol" },
1188     { 0xc025,   "Link Quality Report" },
1189     { 0xc027,   "Shiva Password Authentication Protocol" },
1190     { 0xc029,   "CallBack Control Protocol (CBCP)" },
1191     { 0xc081,   "Container Control Protocol" },
1192     { 0xc223,   "Challenge Handshake Authentication Protocol" },
1193     { 0xc281,   "Proprietary Authentication Protocol" },
1194     { 0,        NULL },
1195 };
1196
1197 /*
1198  * protocol_name - find a name for a PPP protocol.
1199  */
1200 const char *
1201 protocol_name(proto)
1202     int proto;
1203 {
1204     struct protocol_list *lp;
1205
1206     for (lp = protocol_list; lp->proto != 0; ++lp)
1207         if (proto == lp->proto)
1208             return lp->name;
1209     return NULL;
1210 }
1211
1212 /*
1213  * get_input - called when incoming data is available.
1214  */
1215 static void
1216 get_input()
1217 {
1218     int len, i;
1219     u_char *p;
1220     u_short protocol;
1221     struct protent *protp;
1222
1223     p = inpacket_buf;   /* point to beginning of packet buffer */
1224
1225     len = read_packet(inpacket_buf);
1226     if (len < 0)
1227         return;
1228
1229     if (len == 0) {
1230         notice("Modem hangup");
1231         hungup = 1;
1232         status = EXIT_HANGUP;
1233         lcp_lowerdown(0);       /* serial link is no longer available */
1234         link_terminated(0);
1235         return;
1236     }
1237
1238     if (debug /*&& (debugflags & DBG_INPACKET)*/)
1239         dbglog("rcvd %P", p, len);
1240
1241     if (len < PPP_HDRLEN) {
1242         MAINDEBUG(("io(): Received short packet."));
1243         return;
1244     }
1245
1246     p += 2;                             /* Skip address and control */
1247     GETSHORT(protocol, p);
1248     len -= PPP_HDRLEN;
1249
1250     /*
1251      * Toss all non-LCP packets unless LCP is OPEN.
1252      */
1253     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1254         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1255         return;
1256     }
1257
1258     /*
1259      * Until we get past the authentication phase, toss all packets
1260      * except LCP, LQR and authentication packets.
1261      */
1262     if (phase <= PHASE_AUTHENTICATE
1263         && !(protocol == PPP_LCP || protocol == PPP_LQR
1264              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1265         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1266                    protocol, phase));
1267         return;
1268     }
1269
1270     /*
1271      * Upcall the proper protocol input routine.
1272      */
1273     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1274         if (protp->protocol == protocol && protp->enabled_flag) {
1275             (*protp->input)(0, p, len);
1276             return;
1277         }
1278         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1279             && protp->datainput != NULL) {
1280             (*protp->datainput)(0, p, len);
1281             return;
1282         }
1283     }
1284
1285     if (debug) {
1286         const char *pname = protocol_name(protocol);
1287         if (pname != NULL)
1288             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1289         else
1290             warn("Unsupported protocol 0x%x received", protocol);
1291     }
1292     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1293 }
1294
1295 /*
1296  * new_phase - signal the start of a new phase of pppd's operation.
1297  */
1298 void
1299 new_phase(p)
1300     int p;
1301 {
1302     phase = p;
1303     if (new_phase_hook)
1304         (*new_phase_hook)(p);
1305 }
1306
1307 /*
1308  * die - clean up state and exit with the specified status.
1309  */
1310 void
1311 die(status)
1312     int status;
1313 {
1314     cleanup();
1315     syslog(LOG_INFO, "Exit.");
1316     exit(status);
1317 }
1318
1319 /*
1320  * cleanup - restore anything which needs to be restored before we exit
1321  */
1322 /* ARGSUSED */
1323 static void
1324 cleanup()
1325 {
1326     sys_cleanup();
1327
1328     if (fd_ppp >= 0)
1329         disestablish_ppp(ttyfd);
1330     if (real_ttyfd >= 0)
1331         close_tty();
1332
1333     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
1334         warn("unable to delete pid file %s: %m", pidfilename);
1335     pidfilename[0] = 0;
1336     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT) 
1337         warn("unable to delete pid file %s: %m", linkpidfile);
1338     linkpidfile[0] = 0;
1339
1340     if (locked)
1341         unlock();
1342
1343     if (pppdb != NULL)
1344         cleanup_db();
1345 }
1346
1347 /*
1348  * close_tty - restore the terminal device and close it.
1349  */
1350 static void
1351 close_tty()
1352 {
1353     /* drop dtr to hang up */
1354     if (!default_device && modem) {
1355         setdtr(real_ttyfd, 0);
1356         /*
1357          * This sleep is in case the serial port has CLOCAL set by default,
1358          * and consequently will reassert DTR when we close the device.
1359          */
1360         sleep(1);
1361     }
1362
1363     restore_tty(real_ttyfd);
1364
1365     if (tty_mode != (mode_t) -1) {
1366         if (fchmod(real_ttyfd, tty_mode) != 0) {
1367             /* XXX if devnam is a symlink, this will change the link */
1368             chmod(devnam, tty_mode);
1369         }
1370     }
1371
1372     close(real_ttyfd);
1373     real_ttyfd = -1;
1374 }
1375
1376 /*
1377  * update_link_stats - get stats at link termination.
1378  */
1379 void
1380 update_link_stats(u)
1381     int u;
1382 {
1383     struct timeval now;
1384     char numbuf[32];
1385
1386     if (!get_ppp_stats(u, &link_stats)
1387         || gettimeofday(&now, NULL) < 0)
1388         return;
1389     link_connect_time = now.tv_sec - start_time.tv_sec;
1390     link_stats_valid = 1;
1391
1392     slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1393     script_setenv("CONNECT_TIME", numbuf, 0);
1394     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1395     script_setenv("BYTES_SENT", numbuf, 0);
1396     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1397     script_setenv("BYTES_RCVD", numbuf, 0);
1398 }
1399
1400
1401 struct  callout {
1402     struct timeval      c_time;         /* time at which to call routine */
1403     void                *c_arg;         /* argument to routine */
1404     void                (*c_func) __P((void *)); /* routine */
1405     struct              callout *c_next;
1406 };
1407
1408 static struct callout *callout = NULL;  /* Callout list */
1409 static struct timeval timenow;          /* Current time */
1410
1411 /*
1412  * timeout - Schedule a timeout.
1413  *
1414  * Note that this timeout takes the number of seconds, NOT hz (as in
1415  * the kernel).
1416  */
1417 void
1418 timeout(func, arg, time)
1419     void (*func) __P((void *));
1420     void *arg;
1421     int time;
1422 {
1423     struct callout *newp, *p, **pp;
1424   
1425     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1426   
1427     /*
1428      * Allocate timeout.
1429      */
1430     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1431         fatal("Out of memory in timeout()!");
1432     newp->c_arg = arg;
1433     newp->c_func = func;
1434     gettimeofday(&timenow, NULL);
1435     newp->c_time.tv_sec = timenow.tv_sec + time;
1436     newp->c_time.tv_usec = timenow.tv_usec;
1437   
1438     /*
1439      * Find correct place and link it in.
1440      */
1441     for (pp = &callout; (p = *pp); pp = &p->c_next)
1442         if (newp->c_time.tv_sec < p->c_time.tv_sec
1443             || (newp->c_time.tv_sec == p->c_time.tv_sec
1444                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1445             break;
1446     newp->c_next = p;
1447     *pp = newp;
1448 }
1449
1450
1451 /*
1452  * untimeout - Unschedule a timeout.
1453  */
1454 void
1455 untimeout(func, arg)
1456     void (*func) __P((void *));
1457     void *arg;
1458 {
1459     struct callout **copp, *freep;
1460   
1461     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1462   
1463     /*
1464      * Find first matching timeout and remove it from the list.
1465      */
1466     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1467         if (freep->c_func == func && freep->c_arg == arg) {
1468             *copp = freep->c_next;
1469             free((char *) freep);
1470             break;
1471         }
1472 }
1473
1474
1475 /*
1476  * calltimeout - Call any timeout routines which are now due.
1477  */
1478 static void
1479 calltimeout()
1480 {
1481     struct callout *p;
1482
1483     while (callout != NULL) {
1484         p = callout;
1485
1486         if (gettimeofday(&timenow, NULL) < 0)
1487             fatal("Failed to get time of day: %m");
1488         if (!(p->c_time.tv_sec < timenow.tv_sec
1489               || (p->c_time.tv_sec == timenow.tv_sec
1490                   && p->c_time.tv_usec <= timenow.tv_usec)))
1491             break;              /* no, it's not time yet */
1492
1493         callout = p->c_next;
1494         (*p->c_func)(p->c_arg);
1495
1496         free((char *) p);
1497     }
1498 }
1499
1500
1501 /*
1502  * timeleft - return the length of time until the next timeout is due.
1503  */
1504 static struct timeval *
1505 timeleft(tvp)
1506     struct timeval *tvp;
1507 {
1508     if (callout == NULL)
1509         return NULL;
1510
1511     gettimeofday(&timenow, NULL);
1512     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1513     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1514     if (tvp->tv_usec < 0) {
1515         tvp->tv_usec += 1000000;
1516         tvp->tv_sec -= 1;
1517     }
1518     if (tvp->tv_sec < 0)
1519         tvp->tv_sec = tvp->tv_usec = 0;
1520
1521     return tvp;
1522 }
1523
1524
1525 /*
1526  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1527  */
1528 static void
1529 kill_my_pg(sig)
1530     int sig;
1531 {
1532     struct sigaction act, oldact;
1533
1534     act.sa_handler = SIG_IGN;
1535     act.sa_flags = 0;
1536     kill(0, sig);
1537     sigaction(sig, &act, &oldact);
1538     sigaction(sig, &oldact, NULL);
1539 }
1540
1541
1542 /*
1543  * hup - Catch SIGHUP signal.
1544  *
1545  * Indicates that the physical layer has been disconnected.
1546  * We don't rely on this indication; if the user has sent this
1547  * signal, we just take the link down.
1548  */
1549 static void
1550 hup(sig)
1551     int sig;
1552 {
1553     info("Hangup (SIGHUP)");
1554     kill_link = 1;
1555     if (status != EXIT_HANGUP)
1556         status = EXIT_USER_REQUEST;
1557     if (conn_running)
1558         /* Send the signal to the [dis]connector process(es) also */
1559         kill_my_pg(sig);
1560     if (charshunt_pid)
1561         kill(charshunt_pid, sig);
1562     if (waiting)
1563         siglongjmp(sigjmp, 1);
1564 }
1565
1566
1567 /*
1568  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1569  *
1570  * Indicates that we should initiate a graceful disconnect and exit.
1571  */
1572 /*ARGSUSED*/
1573 static void
1574 term(sig)
1575     int sig;
1576 {
1577     info("Terminating on signal %d.", sig);
1578     persist = 0;                /* don't try to restart */
1579     kill_link = 1;
1580     status = EXIT_USER_REQUEST;
1581     if (conn_running)
1582         /* Send the signal to the [dis]connector process(es) also */
1583         kill_my_pg(sig);
1584     if (charshunt_pid)
1585         kill(charshunt_pid, sig);
1586     if (waiting)
1587         siglongjmp(sigjmp, 1);
1588 }
1589
1590
1591 /*
1592  * chld - Catch SIGCHLD signal.
1593  * Sets a flag so we will call reap_kids in the mainline.
1594  */
1595 static void
1596 chld(sig)
1597     int sig;
1598 {
1599     got_sigchld = 1;
1600     if (waiting)
1601         siglongjmp(sigjmp, 1);
1602 }
1603
1604
1605 /*
1606  * toggle_debug - Catch SIGUSR1 signal.
1607  *
1608  * Toggle debug flag.
1609  */
1610 /*ARGSUSED*/
1611 static void
1612 toggle_debug(sig)
1613     int sig;
1614 {
1615     debug = !debug;
1616     if (debug) {
1617         setlogmask(LOG_UPTO(LOG_DEBUG));
1618     } else {
1619         setlogmask(LOG_UPTO(LOG_WARNING));
1620     }
1621 }
1622
1623
1624 /*
1625  * open_ccp - Catch SIGUSR2 signal.
1626  *
1627  * Try to (re)negotiate compression.
1628  */
1629 /*ARGSUSED*/
1630 static void
1631 open_ccp(sig)
1632     int sig;
1633 {
1634     open_ccp_flag = 1;
1635     if (waiting)
1636         siglongjmp(sigjmp, 1);
1637 }
1638
1639
1640 /*
1641  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1642  */
1643 static void
1644 bad_signal(sig)
1645     int sig;
1646 {
1647     static int crashed = 0;
1648
1649     if (crashed)
1650         _exit(127);
1651     crashed = 1;
1652     error("Fatal signal %d", sig);
1653     if (conn_running)
1654         kill_my_pg(SIGTERM);
1655     if (charshunt_pid)
1656         kill(charshunt_pid, SIGTERM);
1657     die(127);
1658 }
1659
1660
1661 /*
1662  * device_script - run a program to talk to the serial device
1663  * (e.g. to run the connector or disconnector script).
1664  */
1665 static int
1666 device_script(program, in, out, dont_wait)
1667     char *program;
1668     int in, out;
1669     int dont_wait;
1670 {
1671     int pid;
1672     int status = -1;
1673     int errfd;
1674
1675     ++conn_running;
1676     pid = fork();
1677
1678     if (pid < 0) {
1679         --conn_running;
1680         error("Failed to create child process: %m");
1681         return -1;
1682     }
1683
1684     if (pid == 0) {
1685         sys_close();
1686         closelog();
1687         if (in == 2) {
1688             /* aargh!!! */
1689             int newin = dup(in);
1690             if (in == out)
1691                 out = newin;
1692             in = newin;
1693         } else if (out == 2) {
1694             out = dup(out);
1695         }
1696         if (log_to_fd >= 0) {
1697             if (log_to_fd != 2)
1698                 dup2(log_to_fd, 2);
1699         } else {
1700             close(2);
1701             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1702             if (errfd >= 0 && errfd != 2) {
1703                 dup2(errfd, 2);
1704                 close(errfd);
1705             }
1706         }
1707         if (in != 0) {
1708             if (out == 0)
1709                 out = dup(out);
1710             dup2(in, 0);
1711         }
1712         if (out != 1) {
1713             dup2(out, 1);
1714         }
1715         if (real_ttyfd > 2)
1716             close(real_ttyfd);
1717         if (pty_master > 2)
1718             close(pty_master);
1719         if (pty_slave > 2)
1720             close(pty_slave);
1721         setuid(uid);
1722         if (getuid() != uid) {
1723             error("setuid failed");
1724             exit(1);
1725         }
1726         setgid(getgid());
1727         execl("/bin/sh", "sh", "-c", program, (char *)0);
1728         error("could not exec /bin/sh: %m");
1729         exit(99);
1730         /* NOTREACHED */
1731     }
1732
1733     if (dont_wait) {
1734         record_child(pid, program, NULL, NULL);
1735         status = 0;
1736     } else {
1737         while (waitpid(pid, &status, 0) < 0) {
1738             if (errno == EINTR)
1739                 continue;
1740             fatal("error waiting for (dis)connection process: %m");
1741         }
1742         --conn_running;
1743     }
1744
1745     return (status == 0 ? 0 : -1);
1746 }
1747
1748
1749 /*
1750  * run-program - execute a program with given arguments,
1751  * but don't wait for it.
1752  * If the program can't be executed, logs an error unless
1753  * must_exist is 0 and the program file doesn't exist.
1754  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1755  * or isn't an executable plain file, or the process ID of the child.
1756  * If done != NULL, (*done)(arg) will be called later (within
1757  * reap_kids) iff the return value is > 0.
1758  */
1759 pid_t
1760 run_program(prog, args, must_exist, done, arg)
1761     char *prog;
1762     char **args;
1763     int must_exist;
1764     void (*done) __P((void *));
1765     void *arg;
1766 {
1767     int pid;
1768     struct stat sbuf;
1769
1770     /*
1771      * First check if the file exists and is executable.
1772      * We don't use access() because that would use the
1773      * real user-id, which might not be root, and the script
1774      * might be accessible only to root.
1775      */
1776     errno = EINVAL;
1777     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1778         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1779         if (must_exist || errno != ENOENT)
1780             warn("Can't execute %s: %m", prog);
1781         return 0;
1782     }
1783
1784     pid = fork();
1785     if (pid == -1) {
1786         error("Failed to create child process for %s: %m", prog);
1787         return -1;
1788     }
1789     if (pid == 0) {
1790         int new_fd;
1791
1792         /* Leave the current location */
1793         (void) setsid();        /* No controlling tty. */
1794         (void) umask (S_IRWXG|S_IRWXO);
1795         (void) chdir ("/");     /* no current directory. */
1796         setuid(0);              /* set real UID = root */
1797         setgid(getegid());
1798
1799         /* Ensure that nothing of our device environment is inherited. */
1800         sys_close();
1801         closelog();
1802         close (0);
1803         close (1);
1804         close (2);
1805         close (ttyfd);  /* tty interface to the ppp device */
1806         if (real_ttyfd >= 0)
1807             close(real_ttyfd);
1808
1809         /* Don't pass handles to the PPP device, even by accident. */
1810         new_fd = open (_PATH_DEVNULL, O_RDWR);
1811         if (new_fd >= 0) {
1812             if (new_fd != 0) {
1813                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1814                 close (new_fd);
1815             }
1816             dup2 (0, 1); /* stdout -> /dev/null */
1817             dup2 (0, 2); /* stderr -> /dev/null */
1818         }
1819
1820 #ifdef BSD
1821         /* Force the priority back to zero if pppd is running higher. */
1822         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1823             warn("can't reset priority to 0: %m"); 
1824 #endif
1825
1826         /* SysV recommends a second fork at this point. */
1827
1828         /* run the program */
1829         execve(prog, args, script_env);
1830         if (must_exist || errno != ENOENT) {
1831             /* have to reopen the log, there's nowhere else
1832                for the message to go. */
1833             reopen_log();
1834             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1835             closelog();
1836         }
1837         _exit(-1);
1838     }
1839
1840     if (debug)
1841         dbglog("Script %s started (pid %d)", prog, pid);
1842     record_child(pid, prog, done, arg);
1843
1844     return pid;
1845 }
1846
1847
1848 /*
1849  * record_child - add a child process to the list for reap_kids
1850  * to use.
1851  */
1852 static void
1853 record_child(pid, prog, done, arg)
1854     int pid;
1855     char *prog;
1856     void (*done) __P((void *));
1857     void *arg;
1858 {
1859     struct subprocess *chp;
1860
1861     ++n_children;
1862
1863     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1864     if (chp == NULL) {
1865         warn("losing track of %s process", prog);
1866     } else {
1867         chp->pid = pid;
1868         chp->prog = prog;
1869         chp->done = done;
1870         chp->arg = arg;
1871         chp->next = children;
1872         children = chp;
1873     }
1874 }
1875
1876
1877 /*
1878  * reap_kids - get status from any dead child processes,
1879  * and log a message for abnormal terminations.
1880  */
1881 static int
1882 reap_kids(waitfor)
1883     int waitfor;
1884 {
1885     int pid, status;
1886     struct subprocess *chp, **prevp;
1887
1888     got_sigchld = 0;
1889     if (n_children == 0)
1890         return 0;
1891     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1892            && pid != 0) {
1893         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1894             if (chp->pid == pid) {
1895                 --n_children;
1896                 *prevp = chp->next;
1897                 break;
1898             }
1899         }
1900         if (WIFSIGNALED(status)) {
1901             warn("Child process %s (pid %d) terminated with signal %d",
1902                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1903         } else if (debug)
1904             dbglog("Script %s finished (pid %d), status = 0x%x",
1905                    (chp? chp->prog: "??"), pid, status);
1906         if (chp && chp->done)
1907             (*chp->done)(chp->arg);
1908         if (chp)
1909             free(chp);
1910     }
1911     if (pid == -1) {
1912         if (errno == ECHILD)
1913             return -1;
1914         if (errno != EINTR)
1915             error("Error waiting for child process: %m");
1916     }
1917     return 0;
1918 }
1919
1920
1921 /*
1922  * novm - log an error message saying we ran out of memory, and die.
1923  */
1924 void
1925 novm(msg)
1926     char *msg;
1927 {
1928     fatal("Virtual memory exhausted allocating %s\n", msg);
1929 }
1930
1931 /*
1932  * script_setenv - set an environment variable value to be used
1933  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1934  */
1935 void
1936 script_setenv(var, value, iskey)
1937     char *var, *value;
1938     int iskey;
1939 {
1940     size_t varl = strlen(var);
1941     size_t vl = varl + strlen(value) + 2;
1942     int i;
1943     char *p, *newstring;
1944
1945     newstring = (char *) malloc(vl+1);
1946     if (newstring == 0)
1947         return;
1948     *newstring++ = iskey;
1949     slprintf(newstring, vl, "%s=%s", var, value);
1950
1951     /* check if this variable is already set */
1952     if (script_env != 0) {
1953         for (i = 0; (p = script_env[i]) != 0; ++i) {
1954             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1955                 if (p[-1] && pppdb != NULL)
1956                     delete_db_key(p);
1957                 free(p-1);
1958                 script_env[i] = newstring;
1959                 if (iskey && pppdb != NULL)
1960                     add_db_key(newstring);
1961                 update_db_entry();
1962                 return;
1963             }
1964         }
1965     } else {
1966         /* no space allocated for script env. ptrs. yet */
1967         i = 0;
1968         script_env = (char **) malloc(16 * sizeof(char *));
1969         if (script_env == 0)
1970             return;
1971         s_env_nalloc = 16;
1972     }
1973
1974     /* reallocate script_env with more space if needed */
1975     if (i + 1 >= s_env_nalloc) {
1976         int new_n = i + 17;
1977         char **newenv = (char **) realloc((void *)script_env,
1978                                           new_n * sizeof(char *));
1979         if (newenv == 0)
1980             return;
1981         script_env = newenv;
1982         s_env_nalloc = new_n;
1983     }
1984
1985     script_env[i] = newstring;
1986     script_env[i+1] = 0;
1987
1988     if (pppdb != NULL) {
1989         if (iskey)
1990             add_db_key(newstring);
1991         update_db_entry();
1992     }
1993 }
1994
1995 /*
1996  * script_unsetenv - remove a variable from the environment
1997  * for scripts.
1998  */
1999 void
2000 script_unsetenv(var)
2001     char *var;
2002 {
2003     int vl = strlen(var);
2004     int i;
2005     char *p;
2006
2007     if (script_env == 0)
2008         return;
2009     for (i = 0; (p = script_env[i]) != 0; ++i) {
2010         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2011             if (p[-1] && pppdb != NULL)
2012                 delete_db_key(p);
2013             free(p-1);
2014             while ((script_env[i] = script_env[i+1]) != 0)
2015                 ++i;
2016             break;
2017         }
2018     }
2019     if (pppdb != NULL)
2020         update_db_entry();
2021 }
2022
2023 /*
2024  * update_db_entry - update our entry in the database.
2025  */
2026 static void
2027 update_db_entry()
2028 {
2029     TDB_DATA key, dbuf;
2030     int vlen, i;
2031     char *p, *q, *vbuf;
2032
2033     if (script_env == NULL)
2034         return;
2035     vlen = 0;
2036     for (i = 0; (p = script_env[i]) != 0; ++i)
2037         vlen += strlen(p) + 1;
2038     vbuf = malloc(vlen);
2039     if (vbuf == 0)
2040         novm("database entry");
2041     q = vbuf;
2042     for (i = 0; (p = script_env[i]) != 0; ++i)
2043         q += slprintf(q, vbuf + vlen - q, "%s;", p);
2044
2045     key.dptr = db_key;
2046     key.dsize = strlen(db_key);
2047     dbuf.dptr = vbuf;
2048     dbuf.dsize = vlen;
2049     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2050         error("tdb_store failed: %s", tdb_error(pppdb));
2051
2052 }
2053
2054 /*
2055  * add_db_key - add a key that we can use to look up our database entry.
2056  */
2057 static void
2058 add_db_key(str)
2059     const char *str;
2060 {
2061     TDB_DATA key, dbuf;
2062
2063     key.dptr = (char *) str;
2064     key.dsize = strlen(str);
2065     dbuf.dptr = db_key;
2066     dbuf.dsize = strlen(db_key);
2067     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2068         error("tdb_store key failed: %s", tdb_error(pppdb));
2069 }
2070
2071 /*
2072  * delete_db_key - delete a key for looking up our database entry.
2073  */
2074 static void
2075 delete_db_key(str)
2076     const char *str;
2077 {
2078     TDB_DATA key;
2079
2080     key.dptr = (char *) str;
2081     key.dsize = strlen(str);
2082     tdb_delete(pppdb, key);
2083 }
2084
2085 /*
2086  * cleanup_db - delete all the entries we put in the database.
2087  */
2088 static void
2089 cleanup_db()
2090 {
2091     TDB_DATA key;
2092     int i;
2093     char *p;
2094
2095     key.dptr = db_key;
2096     key.dsize = strlen(db_key);
2097     tdb_delete(pppdb, key);
2098     for (i = 0; (p = script_env[i]) != 0; ++i)
2099         if (p[-1])
2100             delete_db_key(p);
2101 }
2102
2103 /*
2104  * open_socket - establish a stream socket connection to the nominated
2105  * host and port.
2106  */
2107 static int
2108 open_socket(dest)
2109     char *dest;
2110 {
2111     char *sep, *endp = NULL;
2112     int sock, port = -1;
2113     u_int32_t host;
2114     struct hostent *hent;
2115     struct sockaddr_in sad;
2116
2117     /* parse host:port and resolve host to an IP address */
2118     sep = strchr(dest, ':');
2119     if (sep != NULL)
2120         port = strtol(sep+1, &endp, 10);
2121     if (port < 0 || endp == sep+1 || sep == dest) {
2122         error("Can't parse host:port for socket destination");
2123         return -1;
2124     }
2125     *sep = 0;
2126     host = inet_addr(dest);
2127     if (host == (u_int32_t) -1) {
2128         hent = gethostbyname(dest);
2129         if (hent == NULL) {
2130             error("%s: unknown host in socket option", dest);
2131             *sep = ':';
2132             return -1;
2133         }
2134         host = *(u_int32_t *)(hent->h_addr_list[0]);
2135     }
2136     *sep = ':';
2137
2138     /* get a socket and connect it to the other end */
2139     sock = socket(PF_INET, SOCK_STREAM, 0);
2140     if (sock < 0) {
2141         error("Can't create socket: %m");
2142         return -1;
2143     }
2144     memset(&sad, 0, sizeof(sad));
2145     sad.sin_family = AF_INET;
2146     sad.sin_port = htons(port);
2147     sad.sin_addr.s_addr = host;
2148     if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
2149         error("Can't connect to %s: %m", dest);
2150         close(sock);
2151         return -1;
2152     }
2153
2154     return sock;
2155 }
2156
2157 /*
2158  * start_charshunt - create a child process to run the character shunt.
2159  */
2160 static int
2161 start_charshunt(ifd, ofd)
2162     int ifd, ofd;
2163 {
2164     int cpid;
2165
2166     cpid = fork();
2167     if (cpid == -1) {
2168         error("Can't fork process for character shunt: %m");
2169         return 0;
2170     }
2171     if (cpid == 0) {
2172         /* child */
2173         close(pty_slave);
2174         setuid(uid);
2175         if (getuid() != uid)
2176             fatal("setuid failed");
2177         setgid(getgid());
2178         if (!nodetach)
2179             log_to_fd = -1;
2180         charshunt(ifd, ofd, record_file);
2181         exit(0);
2182     }
2183     charshunt_pid = cpid;
2184     close(pty_master);
2185     pty_master = -1;
2186     ttyfd = pty_slave;
2187     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2188     return 1;
2189 }
2190
2191 static void
2192 charshunt_done(arg)
2193     void *arg;
2194 {
2195     charshunt_pid = 0;
2196 }
2197
2198 /*
2199  * charshunt - the character shunt, which passes characters between
2200  * the pty master side and the serial port (or stdin/stdout).
2201  * This runs as the user (not as root).
2202  * (We assume ofd >= ifd which is true the way this gets called. :-).
2203  */
2204 static void
2205 charshunt(ifd, ofd, record_file)
2206     int ifd, ofd;
2207     char *record_file;
2208 {
2209     int n, nfds;
2210     fd_set ready, writey;
2211     u_char *ibufp, *obufp;
2212     int nibuf, nobuf;
2213     int flags;
2214     int pty_readable, stdin_readable;
2215     struct timeval lasttime;
2216     FILE *recordf = NULL;
2217     int ilevel, olevel, max_level;
2218     struct timeval levelt, tout, *top;
2219
2220     /*
2221      * Reset signal handlers.
2222      */
2223     signal(SIGHUP, SIG_IGN);            /* Hangup */
2224     signal(SIGINT, SIG_DFL);            /* Interrupt */
2225     signal(SIGTERM, SIG_DFL);           /* Terminate */
2226     signal(SIGCHLD, SIG_DFL);
2227     signal(SIGUSR1, SIG_DFL);
2228     signal(SIGUSR2, SIG_DFL);
2229     signal(SIGABRT, SIG_DFL);
2230     signal(SIGALRM, SIG_DFL);
2231     signal(SIGFPE, SIG_DFL);
2232     signal(SIGILL, SIG_DFL);
2233     signal(SIGPIPE, SIG_DFL);
2234     signal(SIGQUIT, SIG_DFL);
2235     signal(SIGSEGV, SIG_DFL);
2236 #ifdef SIGBUS
2237     signal(SIGBUS, SIG_DFL);
2238 #endif
2239 #ifdef SIGEMT
2240     signal(SIGEMT, SIG_DFL);
2241 #endif
2242 #ifdef SIGPOLL
2243     signal(SIGPOLL, SIG_DFL);
2244 #endif
2245 #ifdef SIGPROF
2246     signal(SIGPROF, SIG_DFL);
2247 #endif
2248 #ifdef SIGSYS
2249     signal(SIGSYS, SIG_DFL);
2250 #endif
2251 #ifdef SIGTRAP
2252     signal(SIGTRAP, SIG_DFL);
2253 #endif
2254 #ifdef SIGVTALRM
2255     signal(SIGVTALRM, SIG_DFL);
2256 #endif
2257 #ifdef SIGXCPU
2258     signal(SIGXCPU, SIG_DFL);
2259 #endif
2260 #ifdef SIGXFSZ
2261     signal(SIGXFSZ, SIG_DFL);
2262 #endif
2263
2264     /*
2265      * Open the record file if required.
2266      */
2267     if (record_file != NULL) {
2268         recordf = fopen(record_file, "a");
2269         if (recordf == NULL)
2270             error("Couldn't create record file %s: %m", record_file);
2271     }
2272
2273     /* set all the fds to non-blocking mode */
2274     flags = fcntl(pty_master, F_GETFL);
2275     if (flags == -1
2276         || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2277         warn("couldn't set pty master to nonblock: %m");
2278     flags = fcntl(ifd, F_GETFL);
2279     if (flags == -1
2280         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2281         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2282     if (ofd != ifd) {
2283         flags = fcntl(ofd, F_GETFL);
2284         if (flags == -1
2285             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2286             warn("couldn't set stdout to nonblock: %m");
2287     }
2288
2289     nibuf = nobuf = 0;
2290     ibufp = obufp = NULL;
2291     pty_readable = stdin_readable = 1;
2292
2293     ilevel = olevel = 0;
2294     gettimeofday(&levelt, NULL);
2295     if (max_data_rate) {
2296         max_level = max_data_rate / 10;
2297         if (max_level < 100)
2298             max_level = 100;
2299     } else
2300         max_level = sizeof(inpacket_buf) + 1;
2301
2302     nfds = (ofd > pty_master? ofd: pty_master) + 1;
2303     if (recordf != NULL) {
2304         gettimeofday(&lasttime, NULL);
2305         putc(7, recordf);       /* put start marker */
2306         putc(lasttime.tv_sec >> 24, recordf);
2307         putc(lasttime.tv_sec >> 16, recordf);
2308         putc(lasttime.tv_sec >> 8, recordf);
2309         putc(lasttime.tv_sec, recordf);
2310         lasttime.tv_usec = 0;
2311     }
2312
2313     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2314         top = 0;
2315         tout.tv_sec = 0;
2316         tout.tv_usec = 10000;
2317         FD_ZERO(&ready);
2318         FD_ZERO(&writey);
2319         if (nibuf != 0) {
2320             if (ilevel >= max_level)
2321                 top = &tout;
2322             else
2323                 FD_SET(pty_master, &writey);
2324         } else if (stdin_readable)
2325             FD_SET(ifd, &ready);
2326         if (nobuf != 0) {
2327             if (olevel >= max_level)
2328                 top = &tout;
2329             else
2330                 FD_SET(ofd, &writey);
2331         } else if (pty_readable)
2332             FD_SET(pty_master, &ready);
2333         if (select(nfds, &ready, &writey, NULL, top) < 0) {
2334             if (errno != EINTR)
2335                 fatal("select");
2336             continue;
2337         }
2338         if (max_data_rate) {
2339             double dt;
2340             int nbt;
2341             struct timeval now;
2342
2343             gettimeofday(&now, NULL);
2344             dt = (now.tv_sec - levelt.tv_sec
2345                   + (now.tv_usec - levelt.tv_usec) / 1e6);
2346             nbt = (int)(dt * max_data_rate);
2347             ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2348             olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2349             levelt = now;
2350         } else
2351             ilevel = olevel = 0;
2352         if (FD_ISSET(ifd, &ready)) {
2353             ibufp = inpacket_buf;
2354             nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2355             if (nibuf < 0 && errno == EIO)
2356                 nibuf = 0;
2357             if (nibuf < 0) {
2358                 if (!(errno == EINTR || errno == EAGAIN)) {
2359                     error("Error reading standard input: %m");
2360                     break;
2361                 }
2362                 nibuf = 0;
2363             } else if (nibuf == 0) {
2364                 /* end of file from stdin */
2365                 stdin_readable = 0;
2366                 /* do a 0-length write, hopefully this will generate
2367                    an EOF (hangup) on the slave side. */
2368                 write(pty_master, inpacket_buf, 0);
2369                 if (recordf)
2370                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
2371                         recordf = NULL;
2372             } else {
2373                 FD_SET(pty_master, &writey);
2374                 if (recordf)
2375                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2376                         recordf = NULL;
2377             }
2378         }
2379         if (FD_ISSET(pty_master, &ready)) {
2380             obufp = outpacket_buf;
2381             nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2382             if (nobuf < 0 && errno == EIO)
2383                 nobuf = 0;
2384             if (nobuf < 0) {
2385                 if (!(errno == EINTR || errno == EAGAIN)) {
2386                     error("Error reading pseudo-tty master: %m");
2387                     break;
2388                 }
2389                 nobuf = 0;
2390             } else if (nobuf == 0) {
2391                 /* end of file from the pty - slave side has closed */
2392                 pty_readable = 0;
2393                 stdin_readable = 0;     /* pty is not writable now */
2394                 nibuf = 0;
2395                 close(ofd);
2396                 if (recordf)
2397                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
2398                         recordf = NULL;
2399             } else {
2400                 FD_SET(ofd, &writey);
2401                 if (recordf)
2402                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2403                         recordf = NULL;
2404             }
2405         }
2406         if (FD_ISSET(ofd, &writey)) {
2407             n = nobuf;
2408             if (olevel + n > max_level)
2409                 n = max_level - olevel;
2410             n = write(ofd, obufp, n);
2411             if (n < 0) {
2412                 if (errno != EIO) {
2413                     error("Error writing standard output: %m");
2414                     break;
2415                 }
2416                 pty_readable = 0;
2417                 nobuf = 0;
2418             } else {
2419                 obufp += n;
2420                 nobuf -= n;
2421                 olevel += n;
2422             }
2423         }
2424         if (FD_ISSET(pty_master, &writey)) {
2425             n = nibuf;
2426             if (ilevel + n > max_level)
2427                 n = max_level - ilevel;
2428             n = write(pty_master, ibufp, n);
2429             if (n < 0) {
2430                 if (errno != EIO) {
2431                     error("Error writing pseudo-tty master: %m");
2432                     break;
2433                 }
2434                 stdin_readable = 0;
2435                 nibuf = 0;
2436             } else {
2437                 ibufp += n;
2438                 nibuf -= n;
2439                 ilevel += n;
2440             }
2441         }
2442     }
2443     exit(0);
2444 }
2445
2446 static int
2447 record_write(f, code, buf, nb, tp)
2448     FILE *f;
2449     int code;
2450     u_char *buf;
2451     int nb;
2452     struct timeval *tp;
2453 {
2454     struct timeval now;
2455     int diff;
2456
2457     gettimeofday(&now, NULL);
2458     now.tv_usec /= 100000;      /* actually 1/10 s, not usec now */
2459     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2460     if (diff > 0) {
2461         if (diff > 255) {
2462             putc(5, f);
2463             putc(diff >> 24, f);
2464             putc(diff >> 16, f);
2465             putc(diff >> 8, f);
2466             putc(diff, f);
2467         } else {
2468             putc(6, f);
2469             putc(diff, f);
2470         }
2471         *tp = now;
2472     }
2473     putc(code, f);
2474     if (buf != NULL) {
2475         putc(nb >> 8, f);
2476         putc(nb, f);
2477         fwrite(buf, nb, 1, f);
2478     }
2479     fflush(f);
2480     if (ferror(f)) {
2481         error("Error writing record file: %m");
2482         return 0;
2483     }
2484     return 1;
2485 }