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