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