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