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