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