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