]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
fix pid handling
[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.76 1999/04/16 11:35:06 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 uid_t uid;               /* Our real user-id */
81 static int conn_running;        /* we have a [dis]connector running */
82
83 int ttyfd;                      /* Serial port file descriptor */
84 mode_t tty_mode = -1;           /* Original access permissions to tty */
85 int baud_rate;                  /* Actual bits/second for serial device */
86 int hungup;                     /* terminal has been hung up */
87 int privileged;                 /* we're running as real uid root */
88 int need_holdoff;               /* need holdoff period before restarting */
89 int detached;                   /* have detached from terminal */
90 int log_to_fd;                  /* send log messages to this fd too */
91
92 static int fd_ppp = -1;         /* fd for talking PPP */
93 static int fd_loop;             /* fd for getting demand-dial packets */
94 static int pty_master;          /* fd for master side of pty */
95 static int pty_slave;           /* fd for slave side of pty */
96 static int real_ttyfd;          /* fd for actual serial port (not pty) */
97
98 int phase;                      /* where the link is at */
99 int kill_link;
100 int open_ccp_flag;
101
102 static int waiting;
103 static sigjmp_buf sigjmp;
104
105 char **script_env;              /* Env. variable values for scripts */
106 int s_env_nalloc;               /* # words avail at script_env */
107
108 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
109 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
110
111 static int n_children;          /* # child processes still running */
112 static int got_sigchld;         /* set if we have received a SIGCHLD */
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 /*
129  * We maintain a list of child process pids and
130  * functions to call when they exit.
131  */
132 struct subprocess {
133     pid_t       pid;
134     char        *prog;
135     void        (*done) __P((void *));
136     void        *arg;
137     struct subprocess *next;
138 };
139
140 static struct subprocess *children;
141
142 /* Prototypes for procedures local to this file. */
143
144 static void create_pidfile __P((void));
145 static void cleanup __P((void));
146 static void close_tty __P((void));
147 static void get_input __P((void));
148 static void calltimeout __P((void));
149 static struct timeval *timeleft __P((struct timeval *));
150 static void kill_my_pg __P((int));
151 static void hup __P((int));
152 static void term __P((int));
153 static void chld __P((int));
154 static void toggle_debug __P((int));
155 static void open_ccp __P((int));
156 static void bad_signal __P((int));
157 static void holdoff_end __P((void *));
158 static int device_script __P((char *, int, int, int));
159 static void reap_kids __P((int waitfor));
160 static void record_child __P((int, char *, void (*) (void *), void *));
161 static int start_charshunt __P((int, int));
162 static void charshunt_done __P((void *));
163 static void charshunt __P((int, int, char *));
164 static int record_write __P((FILE *, int code, u_char *buf, int nb,
165                              struct timeval *));
166
167 extern  char    *ttyname __P((int));
168 extern  char    *getlogin __P((void));
169 int main __P((int, char *[]));
170
171 #ifdef ultrix
172 #undef  O_NONBLOCK
173 #define O_NONBLOCK      O_NDELAY
174 #endif
175
176 #ifdef ULTRIX
177 #define setlogmask(x)
178 #endif
179
180 /*
181  * PPP Data Link Layer "protocol" table.
182  * One entry per supported protocol.
183  * The last entry must be NULL.
184  */
185 struct protent *protocols[] = {
186     &lcp_protent,
187     &pap_protent,
188     &chap_protent,
189 #ifdef CBCP_SUPPORT
190     &cbcp_protent,
191 #endif
192     &ipcp_protent,
193     &ccp_protent,
194 #ifdef IPX_CHANGE
195     &ipxcp_protent,
196 #endif
197 #ifdef AT_CHANGE
198     &atcp_protent,
199 #endif
200     NULL
201 };
202
203 int
204 main(argc, argv)
205     int argc;
206     char *argv[];
207 {
208     int i, fdflags;
209     struct sigaction sa;
210     char *p;
211     struct passwd *pw;
212     struct timeval timo;
213     sigset_t mask;
214     struct protent *protp;
215     struct stat statbuf;
216     char numbuf[16];
217     struct timeval now;
218
219     phase = PHASE_INITIALIZE;
220     log_to_fd = -1;
221
222     /*
223      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
224      * This way we can close 0, 1, 2 in detach() without clobbering
225      * a fd that we are using.
226      */
227     if ((i = open("/dev/null", O_RDWR)) >= 0) {
228         while (0 <= i && i <= 2)
229             i = dup(i);
230         if (i >= 0)
231             close(i);
232     }
233
234     script_env = NULL;
235
236     /* Initialize syslog facilities */
237     reopen_log();
238
239     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
240         option_error("Couldn't get hostname: %m");
241         exit(1);
242     }
243     hostname[MAXNAMELEN-1] = 0;
244
245     uid = getuid();
246     privileged = uid == 0;
247     slprintf(numbuf, sizeof(numbuf), "%d", uid);
248     script_setenv("ORIG_UID", numbuf);
249
250     ngroups = getgroups(NGROUPS_MAX, groups);
251
252     /*
253      * Initialize to the standard option set, then parse, in order,
254      * the system options file, the user's options file,
255      * the tty's options file, and the command line arguments.
256      */
257     for (i = 0; (protp = protocols[i]) != NULL; ++i)
258         (*protp->init)(0);
259
260     progname = *argv;
261
262     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
263         || !options_from_user())
264         exit(1);
265     using_pty = notty || ptycommand != NULL;
266     scan_args(argc-1, argv+1);  /* look for tty name on command line */
267
268     /*
269      * Work out the device name, if it hasn't already been specified.
270      */
271     if (!using_pty) {
272         p = isatty(0)? ttyname(0): NULL;
273         if (p != NULL) {
274             if (default_device)
275                 strlcpy(devnam, p, sizeof(devnam));
276             else if (strcmp(devnam, p) == 0)
277                 default_device = 1;
278         }
279     }
280
281     /*
282      * Parse the tty options file and the command line.
283      */
284     if (!options_for_tty()
285         || !parse_args(argc-1, argv+1))
286         exit(1);
287
288     /*
289      * Check that we are running as root.
290      */
291     if (geteuid() != 0) {
292         option_error("must be root to run %s, since it is not setuid-root",
293                      argv[0]);
294         exit(1);
295     }
296
297     if (!ppp_available()) {
298         option_error(no_ppp_msg);
299         exit(1);
300     }
301
302     /*
303      * Check that the options given are valid and consistent.
304      */
305     if (!sys_check_options())
306         exit(1);
307     auth_check_options();
308     for (i = 0; (protp = protocols[i]) != NULL; ++i)
309         if (protp->check_options != NULL)
310             (*protp->check_options)();
311     if (demand && connector == 0) {
312         option_error("connect script is required for demand-dialling\n");
313         exit(1);
314     }
315
316     if (using_pty) {
317         if (!default_device) {
318             option_error("%s option precludes specifying device name",
319                          notty? "notty": "pty");
320             exit(1);
321         }
322         if (ptycommand != NULL && notty) {
323             option_error("pty option is incompatible with notty option");
324             exit(1);
325         }
326         default_device = notty;
327         lockflag = 0;
328         modem = 0;
329     } else {
330         if (devnam[0] == 0) {
331             option_error("no device specified and stdin is not a tty");
332             exit(1);
333         }
334     }
335     if (default_device)
336         nodetach = 1;
337     else
338         log_to_fd = 1;          /* default to stdout */
339
340     script_setenv("DEVICE", devnam);
341
342     /*
343      * Initialize system-dependent stuff and magic number package.
344      */
345     sys_init();
346     magic_init();
347     if (debug)
348         setlogmask(LOG_UPTO(LOG_DEBUG));
349
350     /*
351      * Detach ourselves from the terminal, if required,
352      * and identify who is running us.
353      */
354     if (!nodetach && !updetach)
355         detach();
356     p = getlogin();
357     if (p == NULL) {
358         pw = getpwuid(uid);
359         if (pw != NULL && pw->pw_name != NULL)
360             p = pw->pw_name;
361         else
362             p = "(unknown)";
363     }
364     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
365            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
366     script_setenv("PPPLOGNAME", p);
367
368     /*
369      * Compute mask of all interesting signals and install signal handlers
370      * for each.  Only one signal handler may be active at a time.  Therefore,
371      * all other signals should be masked when any handler is executing.
372      */
373     sigemptyset(&mask);
374     sigaddset(&mask, SIGHUP);
375     sigaddset(&mask, SIGINT);
376     sigaddset(&mask, SIGTERM);
377     sigaddset(&mask, SIGCHLD);
378     sigaddset(&mask, SIGUSR2);
379
380 #define SIGNAL(s, handler)      do { \
381         sa.sa_handler = handler; \
382         if (sigaction(s, &sa, NULL) < 0) \
383             fatal("Couldn't establish signal handler (%d): %m", s); \
384     } while (0)
385
386     sa.sa_mask = mask;
387     sa.sa_flags = 0;
388     SIGNAL(SIGHUP, hup);                /* Hangup */
389     SIGNAL(SIGINT, term);               /* Interrupt */
390     SIGNAL(SIGTERM, term);              /* Terminate */
391     SIGNAL(SIGCHLD, chld);
392
393     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
394     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
395
396     /*
397      * Install a handler for other signals which would otherwise
398      * cause pppd to exit without cleaning up.
399      */
400     SIGNAL(SIGABRT, bad_signal);
401     SIGNAL(SIGALRM, bad_signal);
402     SIGNAL(SIGFPE, bad_signal);
403     SIGNAL(SIGILL, bad_signal);
404     SIGNAL(SIGPIPE, bad_signal);
405     SIGNAL(SIGQUIT, bad_signal);
406     SIGNAL(SIGSEGV, bad_signal);
407 #ifdef SIGBUS
408     SIGNAL(SIGBUS, bad_signal);
409 #endif
410 #ifdef SIGEMT
411     SIGNAL(SIGEMT, bad_signal);
412 #endif
413 #ifdef SIGPOLL
414     SIGNAL(SIGPOLL, bad_signal);
415 #endif
416 #ifdef SIGPROF
417     SIGNAL(SIGPROF, bad_signal);
418 #endif
419 #ifdef SIGSYS
420     SIGNAL(SIGSYS, bad_signal);
421 #endif
422 #ifdef SIGTRAP
423     SIGNAL(SIGTRAP, bad_signal);
424 #endif
425 #ifdef SIGVTALRM
426     SIGNAL(SIGVTALRM, bad_signal);
427 #endif
428 #ifdef SIGXCPU
429     SIGNAL(SIGXCPU, bad_signal);
430 #endif
431 #ifdef SIGXFSZ
432     SIGNAL(SIGXFSZ, bad_signal);
433 #endif
434
435     /*
436      * Apparently we can get a SIGPIPE when we call syslog, if
437      * syslogd has died and been restarted.  Ignoring it seems
438      * be sufficient.
439      */
440     signal(SIGPIPE, SIG_IGN);
441
442     waiting = 0;
443
444     /*
445      * If we're doing dial-on-demand, set up the interface now.
446      */
447     if (demand) {
448         /*
449          * Open the loopback channel and set it up to be the ppp interface.
450          */
451         fd_loop = open_ppp_loopback();
452
453         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
454         slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
455         script_setenv("IFNAME", ifname);
456
457         create_pidfile();       /* write pid to file */
458
459         /*
460          * Configure the interface and mark it up, etc.
461          */
462         demand_conf();
463     }
464
465     for (;;) {
466
467         need_holdoff = 1;
468         ttyfd = -1;
469         real_ttyfd = -1;
470
471         if (demand) {
472             /*
473              * Don't do anything until we see some activity.
474              */
475             kill_link = 0;
476             phase = PHASE_DORMANT;
477             demand_unblock();
478             add_fd(fd_loop);
479             for (;;) {
480                 if (sigsetjmp(sigjmp, 1) == 0) {
481                     sigprocmask(SIG_BLOCK, &mask, NULL);
482                     if (kill_link || got_sigchld) {
483                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
484                     } else {
485                         waiting = 1;
486                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
487                         wait_input(timeleft(&timo));
488                     }
489                 }
490                 waiting = 0;
491                 calltimeout();
492                 if (kill_link) {
493                     if (!persist)
494                         break;
495                     kill_link = 0;
496                 }
497                 if (get_loop_output())
498                     break;
499                 if (got_sigchld)
500                     reap_kids(0);
501             }
502             remove_fd(fd_loop);
503             if (kill_link && !persist)
504                 break;
505
506             /*
507              * Now we want to bring up the link.
508              */
509             demand_block();
510             info("Starting link");
511         }
512
513         /*
514          * Get a pty master/slave pair if the pty, notty, or record
515          * options were specified.
516          */
517         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
518         pty_master = -1;
519         pty_slave = -1;
520         if (ptycommand != NULL || notty || record_file != NULL) {
521             if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
522                 error("Couldn't allocate pseudo-tty");
523                 goto fail;
524             }
525             set_up_tty(pty_slave, 1);
526         }
527
528         /*
529          * Lock the device if we've been asked to.
530          */
531         if (lockflag && !default_device) {
532             if (lock(devnam) < 0)
533                 goto fail;
534             locked = 1;
535         }
536
537         /*
538          * Open the serial device and set it up to be the ppp interface.
539          * First we open it in non-blocking mode so we can set the
540          * various termios flags appropriately.  If we aren't dialling
541          * out and we want to use the modem lines, we reopen it later
542          * in order to wait for the carrier detect signal from the modem.
543          */
544         hungup = 0;
545         kill_link = 0;
546         if (devnam[0] != 0) {
547             for (;;) {
548                 /* If the user specified the device name, become the
549                    user before opening it. */
550                 int err;
551                 if (!devnam_info.priv && !default_device)
552                     seteuid(uid);
553                 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
554                 err = errno;
555                 if (!devnam_info.priv && !default_device)
556                     seteuid(0);
557                 if (ttyfd >= 0)
558                     break;
559                 errno = err;
560                 if (err != EINTR)
561                     error("Failed to open %s: %m", devnam);
562                 if (!persist || err != EINTR)
563                     goto fail;
564             }
565             if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
566                 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
567                 warn("Couldn't reset non-blocking mode on device: %m");
568
569             /*
570              * Do the equivalent of `mesg n' to stop broadcast messages.
571              */
572             if (fstat(ttyfd, &statbuf) < 0
573                 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
574                 warn("Couldn't restrict write permissions to %s: %m", devnam);
575             } else
576                 tty_mode = statbuf.st_mode;
577
578             /*
579              * Set line speed, flow control, etc.
580              * If we have a non-null connection script,
581              * on most systems we set CLOCAL for now so that we can talk
582              * to the modem before carrier comes up.  But this has the
583              * side effect that we might miss it if CD drops before we
584              * get to clear CLOCAL below.  On systems where we can talk
585              * successfully to the modem with CLOCAL clear and CD down,
586              * we could clear CLOCAL at this point.
587              */
588             set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
589             real_ttyfd = ttyfd;
590         }
591
592         /*
593          * If the notty and/or record option was specified,
594          * start up the character shunt now.
595          */
596         if (ptycommand != NULL) {
597             if (record_file != NULL) {
598                 int ipipe[2], opipe[2], ok;
599
600                 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
601                     fatal("Couldn't create pipes for record option: %m");
602                 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
603                     && start_charshunt(ipipe[0], opipe[1]);
604                 close(ipipe[0]);
605                 close(ipipe[1]);
606                 close(opipe[0]);
607                 close(opipe[1]);
608                 if (!ok)
609                     goto fail;
610             } else {
611                 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
612                     goto fail;
613                 ttyfd = pty_slave;
614                 close(pty_master);
615                 pty_master = -1;
616             }
617         } else if (notty) {
618             if (!start_charshunt(0, 1))
619                 goto fail;
620         } else if (record_file != NULL) {
621             if (!start_charshunt(ttyfd, ttyfd))
622                 goto fail;
623         }
624
625         /* run connection script */
626         if (connector && connector[0]) {
627             MAINDEBUG(("Connecting with <%s>", connector));
628
629             if (real_ttyfd != -1) {
630                 if (!default_device && modem) {
631                     setdtr(real_ttyfd, 0);      /* in case modem is off hook */
632                     sleep(1);
633                     setdtr(real_ttyfd, 1);
634                 }
635             }
636
637             if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
638                 error("Connect script failed");
639                 goto fail;
640             }
641             if (kill_link)
642                 goto disconnect;
643
644             info("Serial connection established.");
645
646             /* set line speed, flow control, etc.;
647                clear CLOCAL if modem option */
648             if (real_ttyfd != -1)
649                 set_up_tty(real_ttyfd, 0);
650         }
651
652         /* reopen tty if necessary to wait for carrier */
653         if (connector == NULL && modem && devnam[0] != 0) {
654             for (;;) {
655                 if ((i = open(devnam, O_RDWR)) >= 0)
656                     break;
657                 if (errno != EINTR)
658                     error("Failed to reopen %s: %m", devnam);
659                 if (!persist || errno != EINTR || hungup || kill_link)
660                     goto fail;
661             }
662             close(i);
663         }
664
665         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
666         script_setenv("SPEED", numbuf);
667
668         /* run welcome script, if any */
669         if (welcomer && welcomer[0]) {
670             if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
671                 warn("Welcome script failed");
672         }
673
674         /* set up the serial device as a ppp interface */
675         fd_ppp = establish_ppp(ttyfd);
676         if (fd_ppp < 0)
677             goto disconnect;
678
679         if (!demand) {
680             
681             info("Using interface ppp%d", ifunit);
682             slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
683             script_setenv("IFNAME", ifname);
684
685             create_pidfile();   /* write pid to file */
686         }
687
688         /*
689          * Start opening the connection and wait for
690          * incoming events (reply, timeout, etc.).
691          */
692         notice("Connect: %s <--> %s", ifname, ppp_devnam);
693         gettimeofday(&start_time, NULL);
694         lcp_lowerup(0);
695
696         /*
697          * If we are initiating this connection, wait for a short
698          * time for something from the peer.  This can avoid bouncing
699          * our packets off his tty before he has it set up.
700          */
701         if (connector != NULL || ptycommand != NULL) {
702             struct timeval t;
703             t.tv_sec = 1;
704             t.tv_usec = 0;
705             wait_input(&t);
706         }
707
708         lcp_open(0);            /* Start protocol */
709         open_ccp_flag = 0;
710         add_fd(fd_ppp);
711         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
712             if (sigsetjmp(sigjmp, 1) == 0) {
713                 sigprocmask(SIG_BLOCK, &mask, NULL);
714                 if (kill_link || open_ccp_flag || got_sigchld) {
715                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
716                 } else {
717                     waiting = 1;
718                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
719                     wait_input(timeleft(&timo));
720                 }
721             }
722             waiting = 0;
723             calltimeout();
724             get_input();
725             if (kill_link) {
726                 lcp_close(0, "User request");
727                 kill_link = 0;
728             }
729             if (open_ccp_flag) {
730                 if (phase == PHASE_NETWORK) {
731                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
732                     (*ccp_protent.open)(0);
733                 }
734                 open_ccp_flag = 0;
735             }
736             if (got_sigchld)
737                 reap_kids(0);   /* Don't leave dead kids lying around */
738         }
739
740         /*
741          * Print connect time and statistics.
742          */
743         if (gettimeofday(&now, NULL) >= 0) {
744             int t = now.tv_sec - start_time.tv_sec;
745             t = (t + 5) / 6;    /* now in 1/10ths of minutes */
746             info("Connect time %d.%d minutes.", t/10, t%10);
747         }
748         if (link_stats_valid) {
749             info("Sent %d bytes, received %d bytes.",
750                  link_stats.bytes_out, link_stats.bytes_in);
751         }
752
753         /*
754          * If we may want to bring the link up again, transfer
755          * the ppp unit back to the loopback.  Set the
756          * real serial device back to its normal mode of operation.
757          */
758         remove_fd(fd_ppp);
759         clean_check();
760         if (demand)
761             restore_loop();
762         disestablish_ppp(ttyfd);
763         fd_ppp = -1;
764         if (!hungup)
765             lcp_lowerdown(0);
766
767         /*
768          * Run disconnector script, if requested.
769          * XXX we may not be able to do this if the line has hung up!
770          */
771     disconnect:
772         if (disconnector && !hungup) {
773             if (real_ttyfd >= 0)
774                 set_up_tty(real_ttyfd, 1);
775             if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
776                 warn("disconnect script failed");
777             } else {
778                 info("Serial link disconnected.");
779             }
780         }
781
782     fail:
783         if (pty_master >= 0)
784             close(pty_master);
785         if (pty_slave >= 0)
786             close(pty_slave);
787         if (real_ttyfd >= 0)
788             close_tty();
789         if (locked) {
790             unlock();
791             locked = 0;
792         }
793
794         if (!demand) {
795             if (pidfilename[0] != 0
796                 && unlink(pidfilename) < 0 && errno != ENOENT) 
797                 warn("unable to delete pid file: %m");
798             pidfilename[0] = 0;
799         }
800
801         if (!persist)
802             break;
803
804         kill_link = 0;
805         if (demand)
806             demand_discard();
807         if (holdoff > 0 && need_holdoff) {
808             phase = PHASE_HOLDOFF;
809             TIMEOUT(holdoff_end, NULL, holdoff);
810             do {
811                 if (sigsetjmp(sigjmp, 1) == 0) {
812                     sigprocmask(SIG_BLOCK, &mask, NULL);
813                     if (kill_link || got_sigchld) {
814                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
815                     } else {
816                         waiting = 1;
817                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
818                         wait_input(timeleft(&timo));
819                     }
820                 }
821                 waiting = 0;
822                 calltimeout();
823                 if (kill_link) {
824                     kill_link = 0;
825                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
826                 }
827                 if (got_sigchld)
828                     reap_kids(0);
829             } while (phase == PHASE_HOLDOFF);
830             if (!persist)
831                 break;
832         }
833     }
834
835     /* Wait for scripts to finish */
836     while (n_children > 0) {
837         if (debug) {
838             struct subprocess *chp;
839             dbglog("Waiting for %d child processes...", n_children);
840             for (chp = children; chp != NULL; chp = chp->next)
841                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
842         }
843         reap_kids(1);
844     }
845
846     die(0);
847     return 0;
848 }
849
850 /*
851  * detach - detach us from the controlling terminal.
852  */
853 void
854 detach()
855 {
856     int pid;
857
858     if (detached)
859         return;
860     if ((pid = fork()) < 0) {
861         error("Couldn't detach (fork failed: %m)");
862         die(1);                 /* or just return? */
863     }
864     if (pid != 0) {
865         /* parent */
866         if (locked)
867             relock(pid);
868         exit(0);                /* parent dies */
869     }
870     setsid();
871     chdir("/");
872     close(0);
873     close(1);
874     close(2);
875     detached = 1;
876     log_to_fd = -1;
877     /* update pid file if it has been written already */
878     if (pidfilename[0])
879         create_pidfile();
880 }
881
882 /*
883  * reopen_log - (re)open our connection to syslog.
884  */
885 void
886 reopen_log()
887 {
888 #ifdef ULTRIX
889     openlog("pppd", LOG_PID);
890 #else
891     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
892     setlogmask(LOG_UPTO(LOG_INFO));
893 #endif
894 }
895
896 /*
897  * Create a file containing our process ID.
898  */
899 static void
900 create_pidfile()
901 {
902     FILE *pidfile;
903     char numbuf[16];
904
905     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
906              _PATH_VARRUN, ifname);
907     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
908         fprintf(pidfile, "%d\n", getpid());
909         (void) fclose(pidfile);
910     } else {
911         error("Failed to create pid file %s: %m", pidfilename);
912         pidfilename[0] = 0;
913     }
914     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
915     script_setenv("PPPD_PID", numbuf);
916 }
917
918 /*
919  * holdoff_end - called via a timeout when the holdoff period ends.
920  */
921 static void
922 holdoff_end(arg)
923     void *arg;
924 {
925     phase = PHASE_DORMANT;
926 }
927
928 /*
929  * get_input - called when incoming data is available.
930  */
931 static void
932 get_input()
933 {
934     int len, i;
935     u_char *p;
936     u_short protocol;
937     struct protent *protp;
938
939     p = inpacket_buf;   /* point to beginning of packet buffer */
940
941     len = read_packet(inpacket_buf);
942     if (len < 0)
943         return;
944
945     if (len == 0) {
946         notice("Modem hangup");
947         hungup = 1;
948         lcp_lowerdown(0);       /* serial link is no longer available */
949         link_terminated(0);
950         return;
951     }
952
953     if (debug /*&& (debugflags & DBG_INPACKET)*/)
954         dbglog("rcvd %P", p, len);
955
956     if (len < PPP_HDRLEN) {
957         MAINDEBUG(("io(): Received short packet."));
958         return;
959     }
960
961     p += 2;                             /* Skip address and control */
962     GETSHORT(protocol, p);
963     len -= PPP_HDRLEN;
964
965     /*
966      * Toss all non-LCP packets unless LCP is OPEN.
967      */
968     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
969         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
970         return;
971     }
972
973     /*
974      * Until we get past the authentication phase, toss all packets
975      * except LCP, LQR and authentication packets.
976      */
977     if (phase <= PHASE_AUTHENTICATE
978         && !(protocol == PPP_LCP || protocol == PPP_LQR
979              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
980         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
981                    protocol, phase));
982         return;
983     }
984
985     /*
986      * Upcall the proper protocol input routine.
987      */
988     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
989         if (protp->protocol == protocol && protp->enabled_flag) {
990             (*protp->input)(0, p, len);
991             return;
992         }
993         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
994             && protp->datainput != NULL) {
995             (*protp->datainput)(0, p, len);
996             return;
997         }
998     }
999
1000     if (debug)
1001         warn("Unsupported protocol (0x%x) received", protocol);
1002     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1003 }
1004
1005
1006 /*
1007  * die - clean up state and exit with the specified status.
1008  */
1009 void
1010 die(status)
1011     int status;
1012 {
1013     cleanup();
1014     syslog(LOG_INFO, "Exit.");
1015     exit(status);
1016 }
1017
1018 /*
1019  * cleanup - restore anything which needs to be restored before we exit
1020  */
1021 /* ARGSUSED */
1022 static void
1023 cleanup()
1024 {
1025     sys_cleanup();
1026
1027     if (fd_ppp >= 0)
1028         disestablish_ppp(ttyfd);
1029     if (real_ttyfd >= 0)
1030         close_tty();
1031
1032     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
1033         warn("unable to delete pid file: %m");
1034     pidfilename[0] = 0;
1035
1036     if (locked)
1037         unlock();
1038 }
1039
1040 /*
1041  * close_tty - restore the terminal device and close it.
1042  */
1043 static void
1044 close_tty()
1045 {
1046     /* drop dtr to hang up */
1047     if (!default_device && modem) {
1048         setdtr(real_ttyfd, 0);
1049         /*
1050          * This sleep is in case the serial port has CLOCAL set by default,
1051          * and consequently will reassert DTR when we close the device.
1052          */
1053         sleep(1);
1054     }
1055
1056     restore_tty(real_ttyfd);
1057
1058     if (tty_mode != (mode_t) -1) {
1059         if (fchmod(real_ttyfd, tty_mode) != 0) {
1060             /* XXX if devnam is a symlink, this will change the link */
1061             chmod(devnam, tty_mode);
1062         }
1063     }
1064
1065     close(real_ttyfd);
1066     real_ttyfd = -1;
1067 }
1068
1069
1070 struct  callout {
1071     struct timeval      c_time;         /* time at which to call routine */
1072     void                *c_arg;         /* argument to routine */
1073     void                (*c_func) __P((void *)); /* routine */
1074     struct              callout *c_next;
1075 };
1076
1077 static struct callout *callout = NULL;  /* Callout list */
1078 static struct timeval timenow;          /* Current time */
1079
1080 /*
1081  * timeout - Schedule a timeout.
1082  *
1083  * Note that this timeout takes the number of seconds, NOT hz (as in
1084  * the kernel).
1085  */
1086 void
1087 timeout(func, arg, time)
1088     void (*func) __P((void *));
1089     void *arg;
1090     int time;
1091 {
1092     struct callout *newp, *p, **pp;
1093   
1094     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1095   
1096     /*
1097      * Allocate timeout.
1098      */
1099     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1100         fatal("Out of memory in timeout()!");
1101     newp->c_arg = arg;
1102     newp->c_func = func;
1103     gettimeofday(&timenow, NULL);
1104     newp->c_time.tv_sec = timenow.tv_sec + time;
1105     newp->c_time.tv_usec = timenow.tv_usec;
1106   
1107     /*
1108      * Find correct place and link it in.
1109      */
1110     for (pp = &callout; (p = *pp); pp = &p->c_next)
1111         if (newp->c_time.tv_sec < p->c_time.tv_sec
1112             || (newp->c_time.tv_sec == p->c_time.tv_sec
1113                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1114             break;
1115     newp->c_next = p;
1116     *pp = newp;
1117 }
1118
1119
1120 /*
1121  * untimeout - Unschedule a timeout.
1122  */
1123 void
1124 untimeout(func, arg)
1125     void (*func) __P((void *));
1126     void *arg;
1127 {
1128     struct callout **copp, *freep;
1129   
1130     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1131   
1132     /*
1133      * Find first matching timeout and remove it from the list.
1134      */
1135     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1136         if (freep->c_func == func && freep->c_arg == arg) {
1137             *copp = freep->c_next;
1138             (void) free((char *) freep);
1139             break;
1140         }
1141 }
1142
1143
1144 /*
1145  * calltimeout - Call any timeout routines which are now due.
1146  */
1147 static void
1148 calltimeout()
1149 {
1150     struct callout *p;
1151
1152     while (callout != NULL) {
1153         p = callout;
1154
1155         if (gettimeofday(&timenow, NULL) < 0)
1156             fatal("Failed to get time of day: %m");
1157         if (!(p->c_time.tv_sec < timenow.tv_sec
1158               || (p->c_time.tv_sec == timenow.tv_sec
1159                   && p->c_time.tv_usec <= timenow.tv_usec)))
1160             break;              /* no, it's not time yet */
1161
1162         callout = p->c_next;
1163         (*p->c_func)(p->c_arg);
1164
1165         free((char *) p);
1166     }
1167 }
1168
1169
1170 /*
1171  * timeleft - return the length of time until the next timeout is due.
1172  */
1173 static struct timeval *
1174 timeleft(tvp)
1175     struct timeval *tvp;
1176 {
1177     if (callout == NULL)
1178         return NULL;
1179
1180     gettimeofday(&timenow, NULL);
1181     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1182     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1183     if (tvp->tv_usec < 0) {
1184         tvp->tv_usec += 1000000;
1185         tvp->tv_sec -= 1;
1186     }
1187     if (tvp->tv_sec < 0)
1188         tvp->tv_sec = tvp->tv_usec = 0;
1189
1190     return tvp;
1191 }
1192
1193
1194 /*
1195  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1196  */
1197 static void
1198 kill_my_pg(sig)
1199     int sig;
1200 {
1201     struct sigaction act, oldact;
1202
1203     act.sa_handler = SIG_IGN;
1204     act.sa_flags = 0;
1205     kill(0, sig);
1206     sigaction(sig, &act, &oldact);
1207     sigaction(sig, &oldact, NULL);
1208 }
1209
1210
1211 /*
1212  * hup - Catch SIGHUP signal.
1213  *
1214  * Indicates that the physical layer has been disconnected.
1215  * We don't rely on this indication; if the user has sent this
1216  * signal, we just take the link down.
1217  */
1218 static void
1219 hup(sig)
1220     int sig;
1221 {
1222     info("Hangup (SIGHUP)");
1223     kill_link = 1;
1224     if (conn_running)
1225         /* Send the signal to the [dis]connector process(es) also */
1226         kill_my_pg(sig);
1227     if (charshunt_pid)
1228         kill(charshunt_pid, sig);
1229     if (waiting)
1230         siglongjmp(sigjmp, 1);
1231 }
1232
1233
1234 /*
1235  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1236  *
1237  * Indicates that we should initiate a graceful disconnect and exit.
1238  */
1239 /*ARGSUSED*/
1240 static void
1241 term(sig)
1242     int sig;
1243 {
1244     info("Terminating on signal %d.", sig);
1245     persist = 0;                /* don't try to restart */
1246     kill_link = 1;
1247     if (conn_running)
1248         /* Send the signal to the [dis]connector process(es) also */
1249         kill_my_pg(sig);
1250     if (charshunt_pid)
1251         kill(charshunt_pid, sig);
1252     if (waiting)
1253         siglongjmp(sigjmp, 1);
1254 }
1255
1256
1257 /*
1258  * chld - Catch SIGCHLD signal.
1259  * Sets a flag so we will call reap_kids in the mainline.
1260  */
1261 static void
1262 chld(sig)
1263     int sig;
1264 {
1265     got_sigchld = 1;
1266     if (waiting)
1267         siglongjmp(sigjmp, 1);
1268 }
1269
1270
1271 /*
1272  * toggle_debug - Catch SIGUSR1 signal.
1273  *
1274  * Toggle debug flag.
1275  */
1276 /*ARGSUSED*/
1277 static void
1278 toggle_debug(sig)
1279     int sig;
1280 {
1281     debug = !debug;
1282     if (debug) {
1283         setlogmask(LOG_UPTO(LOG_DEBUG));
1284     } else {
1285         setlogmask(LOG_UPTO(LOG_WARNING));
1286     }
1287 }
1288
1289
1290 /*
1291  * open_ccp - Catch SIGUSR2 signal.
1292  *
1293  * Try to (re)negotiate compression.
1294  */
1295 /*ARGSUSED*/
1296 static void
1297 open_ccp(sig)
1298     int sig;
1299 {
1300     open_ccp_flag = 1;
1301     if (waiting)
1302         siglongjmp(sigjmp, 1);
1303 }
1304
1305
1306 /*
1307  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1308  */
1309 static void
1310 bad_signal(sig)
1311     int sig;
1312 {
1313     static int crashed = 0;
1314
1315     if (crashed)
1316         _exit(127);
1317     crashed = 1;
1318     error("Fatal signal %d", sig);
1319     if (conn_running)
1320         kill_my_pg(SIGTERM);
1321     if (charshunt_pid)
1322         kill(charshunt_pid, SIGTERM);
1323     die(1);
1324 }
1325
1326
1327 /*
1328  * device_script - run a program to talk to the serial device
1329  * (e.g. to run the connector or disconnector script).
1330  */
1331 static int
1332 device_script(program, in, out, dont_wait)
1333     char *program;
1334     int in, out;
1335     int dont_wait;
1336 {
1337     int pid;
1338     int status = -1;
1339     int errfd;
1340
1341     ++conn_running;
1342     pid = fork();
1343
1344     if (pid < 0) {
1345         --conn_running;
1346         error("Failed to create child process: %m");
1347         return -1;
1348     }
1349
1350     if (pid == 0) {
1351         sys_close();
1352         closelog();
1353         if (in == 2) {
1354             /* aargh!!! */
1355             int newin = dup(in);
1356             if (in == out)
1357                 out = newin;
1358             in = newin;
1359         } else if (out == 2) {
1360             out = dup(out);
1361         }
1362         if (log_to_fd >= 0) {
1363             if (log_to_fd != 2)
1364                 dup2(log_to_fd, 2);
1365         } else {
1366             close(2);
1367             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1368             if (errfd >= 0 && errfd != 2) {
1369                 dup2(errfd, 2);
1370                 close(errfd);
1371             }
1372         }
1373         if (in != 0) {
1374             if (out == 0)
1375                 out = dup(out);
1376             dup2(in, 0);
1377         }
1378         if (out != 1) {
1379             dup2(out, 1);
1380         }
1381         if (real_ttyfd > 2)
1382             close(real_ttyfd);
1383         if (pty_master > 2)
1384             close(pty_master);
1385         if (pty_slave > 2)
1386             close(pty_slave);
1387         setuid(uid);
1388         if (getuid() != uid) {
1389             error("setuid failed");
1390             exit(1);
1391         }
1392         setgid(getgid());
1393         execl("/bin/sh", "sh", "-c", program, (char *)0);
1394         error("could not exec /bin/sh: %m");
1395         exit(99);
1396         /* NOTREACHED */
1397     }
1398
1399     if (dont_wait) {
1400         record_child(pid, program, NULL, NULL);
1401         status = 0;
1402     } else {
1403         while (waitpid(pid, &status, 0) < 0) {
1404             if (errno == EINTR)
1405                 continue;
1406             fatal("error waiting for (dis)connection process: %m");
1407         }
1408         --conn_running;
1409     }
1410
1411     return (status == 0 ? 0 : -1);
1412 }
1413
1414
1415 /*
1416  * run-program - execute a program with given arguments,
1417  * but don't wait for it.
1418  * If the program can't be executed, logs an error unless
1419  * must_exist is 0 and the program file doesn't exist.
1420  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1421  * or isn't an executable plain file, or the process ID of the child.
1422  * If done != NULL, (*done)(arg) will be called later (within
1423  * reap_kids) iff the return value is > 0.
1424  */
1425 pid_t
1426 run_program(prog, args, must_exist, done, arg)
1427     char *prog;
1428     char **args;
1429     int must_exist;
1430     void (*done) __P((void *));
1431     void *arg;
1432 {
1433     int pid;
1434     struct stat sbuf;
1435
1436     /*
1437      * First check if the file exists and is executable.
1438      * We don't use access() because that would use the
1439      * real user-id, which might not be root, and the script
1440      * might be accessible only to root.
1441      */
1442     errno = EINVAL;
1443     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1444         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1445         if (must_exist || errno != ENOENT)
1446             warn("Can't execute %s: %m", prog);
1447         return 0;
1448     }
1449
1450     pid = fork();
1451     if (pid == -1) {
1452         error("Failed to create child process for %s: %m", prog);
1453         return -1;
1454     }
1455     if (pid == 0) {
1456         int new_fd;
1457
1458         /* Leave the current location */
1459         (void) setsid();        /* No controlling tty. */
1460         (void) umask (S_IRWXG|S_IRWXO);
1461         (void) chdir ("/");     /* no current directory. */
1462         setuid(0);              /* set real UID = root */
1463         setgid(getegid());
1464
1465         /* Ensure that nothing of our device environment is inherited. */
1466         sys_close();
1467         closelog();
1468         close (0);
1469         close (1);
1470         close (2);
1471         close (ttyfd);  /* tty interface to the ppp device */
1472         if (real_ttyfd >= 0)
1473             close(real_ttyfd);
1474
1475         /* Don't pass handles to the PPP device, even by accident. */
1476         new_fd = open (_PATH_DEVNULL, O_RDWR);
1477         if (new_fd >= 0) {
1478             if (new_fd != 0) {
1479                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1480                 close (new_fd);
1481             }
1482             dup2 (0, 1); /* stdout -> /dev/null */
1483             dup2 (0, 2); /* stderr -> /dev/null */
1484         }
1485
1486 #ifdef BSD
1487         /* Force the priority back to zero if pppd is running higher. */
1488         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1489             warn("can't reset priority to 0: %m"); 
1490 #endif
1491
1492         /* SysV recommends a second fork at this point. */
1493
1494         /* run the program */
1495         execve(prog, args, script_env);
1496         if (must_exist || errno != ENOENT) {
1497             /* have to reopen the log, there's nowhere else
1498                for the message to go. */
1499             reopen_log();
1500             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1501             closelog();
1502         }
1503         _exit(-1);
1504     }
1505
1506     if (debug)
1507         dbglog("Script %s started (pid %d)", prog, pid);
1508     record_child(pid, prog, done, arg);
1509
1510     return pid;
1511 }
1512
1513
1514 /*
1515  * record_child - add a child process to the list for reap_kids
1516  * to use.
1517  */
1518 static void
1519 record_child(pid, prog, done, arg)
1520     int pid;
1521     char *prog;
1522     void (*done) __P((void *));
1523     void *arg;
1524 {
1525     struct subprocess *chp;
1526
1527     ++n_children;
1528
1529     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1530     if (chp == NULL) {
1531         warn("losing track of %s process", prog);
1532     } else {
1533         chp->pid = pid;
1534         chp->prog = prog;
1535         chp->done = done;
1536         chp->arg = arg;
1537         chp->next = children;
1538         children = chp;
1539     }
1540 }
1541
1542
1543 /*
1544  * reap_kids - get status from any dead child processes,
1545  * and log a message for abnormal terminations.
1546  */
1547 static void
1548 reap_kids(waitfor)
1549     int waitfor;
1550 {
1551     int pid, status;
1552     struct subprocess *chp, **prevp;
1553
1554     got_sigchld = 0;
1555     if (n_children == 0)
1556         return;
1557     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1558            && pid != 0) {
1559         --n_children;
1560         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1561             if (chp->pid == pid)
1562                 break;
1563         if (WIFSIGNALED(status)) {
1564             warn("Child process %s (pid %d) terminated with signal %d",
1565                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1566         } else if (debug)
1567             dbglog("Script %s finished (pid %d), status = 0x%x",
1568                    (chp? chp->prog: "??"), pid, status);
1569         if (chp && chp->done)
1570             (*chp->done)(chp->arg);
1571     }
1572     if (pid == -1 && errno != ECHILD && errno != EINTR)
1573         error("Error waiting for child process: %m");
1574 }
1575
1576
1577 /*
1578  * novm - log an error message saying we ran out of memory, and die.
1579  */
1580 void
1581 novm(msg)
1582     char *msg;
1583 {
1584     fatal("Virtual memory exhausted allocating %s\n", msg);
1585 }
1586
1587 /*
1588  * script_setenv - set an environment variable value to be used
1589  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1590  */
1591 void
1592 script_setenv(var, value)
1593     char *var, *value;
1594 {
1595     size_t vl = strlen(var) + strlen(value) + 2;
1596     int i;
1597     char *p, *newstring;
1598
1599     newstring = (char *) malloc(vl);
1600     if (newstring == 0)
1601         return;
1602     slprintf(newstring, vl, "%s=%s", var, value);
1603
1604     /* check if this variable is already set */
1605     if (script_env != 0) {
1606         for (i = 0; (p = script_env[i]) != 0; ++i) {
1607             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1608                 free(p);
1609                 script_env[i] = newstring;
1610                 return;
1611             }
1612         }
1613     } else {
1614         i = 0;
1615         script_env = (char **) malloc(16 * sizeof(char *));
1616         if (script_env == 0)
1617             return;
1618         s_env_nalloc = 16;
1619     }
1620
1621     /* reallocate script_env with more space if needed */
1622     if (i + 1 >= s_env_nalloc) {
1623         int new_n = i + 17;
1624         char **newenv = (char **) realloc((void *)script_env,
1625                                           new_n * sizeof(char *));
1626         if (newenv == 0)
1627             return;
1628         script_env = newenv;
1629         s_env_nalloc = new_n;
1630     }
1631
1632     script_env[i] = newstring;
1633     script_env[i+1] = 0;
1634 }
1635
1636 /*
1637  * script_unsetenv - remove a variable from the environment
1638  * for scripts.
1639  */
1640 void
1641 script_unsetenv(var)
1642     char *var;
1643 {
1644     int vl = strlen(var);
1645     int i;
1646     char *p;
1647
1648     if (script_env == 0)
1649         return;
1650     for (i = 0; (p = script_env[i]) != 0; ++i) {
1651         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1652             free(p);
1653             while ((script_env[i] = script_env[i+1]) != 0)
1654                 ++i;
1655             break;
1656         }
1657     }
1658 }
1659
1660 /*
1661  * start_charshunt - create a child process to run the character shunt.
1662  */
1663 static int
1664 start_charshunt(ifd, ofd)
1665     int ifd, ofd;
1666 {
1667     int cpid;
1668
1669     cpid = fork();
1670     if (cpid == -1) {
1671         error("Can't fork process for character shunt: %m");
1672         return 0;
1673     }
1674     if (cpid == 0) {
1675         /* child */
1676         close(pty_slave);
1677         setuid(uid);
1678         if (getuid() != uid)
1679             fatal("setuid failed");
1680         setgid(getgid());
1681         if (!nodetach)
1682             log_to_fd = -1;
1683         charshunt(ifd, ofd, record_file);
1684         exit(0);
1685     }
1686     charshunt_pid = cpid;
1687     close(pty_master);
1688     pty_master = -1;
1689     ttyfd = pty_slave;
1690     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1691     return 1;
1692 }
1693
1694 static void
1695 charshunt_done(arg)
1696     void *arg;
1697 {
1698     charshunt_pid = 0;
1699 }
1700
1701 /*
1702  * charshunt - the character shunt, which passes characters between
1703  * the pty master side and the serial port (or stdin/stdout).
1704  * This runs as the user (not as root).
1705  * (We assume ofd >= ifd which is true the way this gets called. :-).
1706  */
1707 static void
1708 charshunt(ifd, ofd, record_file)
1709     int ifd, ofd;
1710     char *record_file;
1711 {
1712     int n, nfds;
1713     fd_set ready, writey;
1714     u_char *ibufp, *obufp;
1715     int nibuf, nobuf;
1716     int flags;
1717     int pty_readable, stdin_readable;
1718     struct timeval lasttime;
1719     FILE *recordf = NULL;
1720
1721     /*
1722      * Reset signal handlers.
1723      */
1724     signal(SIGHUP, SIG_IGN);            /* Hangup */
1725     signal(SIGINT, SIG_DFL);            /* Interrupt */
1726     signal(SIGTERM, SIG_DFL);           /* Terminate */
1727     signal(SIGCHLD, SIG_DFL);
1728     signal(SIGUSR1, SIG_DFL);
1729     signal(SIGUSR2, SIG_DFL);
1730     signal(SIGABRT, SIG_DFL);
1731     signal(SIGALRM, SIG_DFL);
1732     signal(SIGFPE, SIG_DFL);
1733     signal(SIGILL, SIG_DFL);
1734     signal(SIGPIPE, SIG_DFL);
1735     signal(SIGQUIT, SIG_DFL);
1736     signal(SIGSEGV, SIG_DFL);
1737 #ifdef SIGBUS
1738     signal(SIGBUS, SIG_DFL);
1739 #endif
1740 #ifdef SIGEMT
1741     signal(SIGEMT, SIG_DFL);
1742 #endif
1743 #ifdef SIGPOLL
1744     signal(SIGPOLL, SIG_DFL);
1745 #endif
1746 #ifdef SIGPROF
1747     signal(SIGPROF, SIG_DFL);
1748 #endif
1749 #ifdef SIGSYS
1750     signal(SIGSYS, SIG_DFL);
1751 #endif
1752 #ifdef SIGTRAP
1753     signal(SIGTRAP, SIG_DFL);
1754 #endif
1755 #ifdef SIGVTALRM
1756     signal(SIGVTALRM, SIG_DFL);
1757 #endif
1758 #ifdef SIGXCPU
1759     signal(SIGXCPU, SIG_DFL);
1760 #endif
1761 #ifdef SIGXFSZ
1762     signal(SIGXFSZ, SIG_DFL);
1763 #endif
1764
1765     /*
1766      * Open the record file if required.
1767      */
1768     if (record_file != NULL) {
1769         recordf = fopen(record_file, "a");
1770         if (recordf == NULL)
1771             error("Couldn't create record file %s: %m", record_file);
1772     }
1773
1774     /* set all the fds to non-blocking mode */
1775     flags = fcntl(pty_master, F_GETFL);
1776     if (flags == -1
1777         || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1778         warn("couldn't set pty master to nonblock: %m");
1779     flags = fcntl(ifd, F_GETFL);
1780     if (flags == -1
1781         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1782         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1783     if (ofd != ifd) {
1784         flags = fcntl(ofd, F_GETFL);
1785         if (flags == -1
1786             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1787             warn("couldn't set stdout to nonblock: %m");
1788     }
1789
1790     nibuf = nobuf = 0;
1791     ibufp = obufp = NULL;
1792     pty_readable = stdin_readable = 1;
1793     nfds = (ofd > pty_master? ofd: pty_master) + 1;
1794     if (recordf != NULL) {
1795         gettimeofday(&lasttime, NULL);
1796         putc(7, recordf);       /* put start marker */
1797         putc(lasttime.tv_sec >> 24, recordf);
1798         putc(lasttime.tv_sec >> 16, recordf);
1799         putc(lasttime.tv_sec >> 8, recordf);
1800         putc(lasttime.tv_sec, recordf);
1801         lasttime.tv_usec = 0;
1802     }
1803
1804     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1805         FD_ZERO(&ready);
1806         FD_ZERO(&writey);
1807         if (nibuf != 0)
1808             FD_SET(pty_master, &writey);
1809         else if (stdin_readable)
1810             FD_SET(ifd, &ready);
1811         if (nobuf != 0)
1812             FD_SET(ofd, &writey);
1813         else if (pty_readable)
1814             FD_SET(pty_master, &ready);
1815         if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1816             if (errno != EINTR)
1817                 fatal("select");
1818             continue;
1819         }
1820         if (FD_ISSET(ifd, &ready)) {
1821             ibufp = inpacket_buf;
1822             nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1823             if (nibuf < 0 && errno == EIO)
1824                 nibuf = 0;
1825             if (nibuf < 0) {
1826                 if (!(errno == EINTR || errno == EAGAIN)) {
1827                     error("Error reading standard input: %m");
1828                     break;
1829                 }
1830                 nibuf = 0;
1831             } else if (nibuf == 0) {
1832                 /* end of file from stdin */
1833                 stdin_readable = 0;
1834                 /* do a 0-length write, hopefully this will generate
1835                    an EOF (hangup) on the slave side. */
1836                 write(pty_master, inpacket_buf, 0);
1837                 if (recordf)
1838                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
1839                         recordf = NULL;
1840             } else {
1841                 FD_SET(pty_master, &writey);
1842                 if (recordf)
1843                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1844                         recordf = NULL;
1845             }
1846         }
1847         if (FD_ISSET(pty_master, &ready)) {
1848             obufp = outpacket_buf;
1849             nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1850             if (nobuf < 0 && errno == EIO)
1851                 nobuf = 0;
1852             if (nobuf < 0) {
1853                 if (!(errno == EINTR || errno == EAGAIN)) {
1854                     error("Error reading pseudo-tty master: %m");
1855                     break;
1856                 }
1857                 nobuf = 0;
1858             } else if (nobuf == 0) {
1859                 /* end of file from the pty - slave side has closed */
1860                 pty_readable = 0;
1861                 stdin_readable = 0;     /* pty is not writable now */
1862                 nibuf = 0;
1863                 close(ofd);
1864                 if (recordf)
1865                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
1866                         recordf = NULL;
1867             } else {
1868                 FD_SET(ofd, &writey);
1869                 if (recordf)
1870                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1871                         recordf = NULL;
1872             }
1873         }
1874         if (FD_ISSET(ofd, &writey)) {
1875             n = write(ofd, obufp, nobuf);
1876             if (n < 0) {
1877                 if (errno != EIO) {
1878                     error("Error writing standard output: %m");
1879                     break;
1880                 }
1881                 pty_readable = 0;
1882                 nobuf = 0;
1883             } else {
1884                 obufp += n;
1885                 nobuf -= n;
1886             }
1887         }
1888         if (FD_ISSET(pty_master, &writey)) {
1889             n = write(pty_master, ibufp, nibuf);
1890             if (n < 0) {
1891                 if (errno != EIO) {
1892                     error("Error writing pseudo-tty master: %m");
1893                     break;
1894                 }
1895                 stdin_readable = 0;
1896                 nibuf = 0;
1897             } else {
1898                 ibufp += n;
1899                 nibuf -= n;
1900             }
1901         }
1902     }
1903     exit(0);
1904 }
1905
1906 static int
1907 record_write(f, code, buf, nb, tp)
1908     FILE *f;
1909     int code;
1910     u_char *buf;
1911     int nb;
1912     struct timeval *tp;
1913 {
1914     struct timeval now;
1915     int diff;
1916
1917     gettimeofday(&now, NULL);
1918     now.tv_usec /= 100000;      /* actually 1/10 s, not usec now */
1919     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1920     if (diff > 0) {
1921         if (diff > 255) {
1922             putc(5, f);
1923             putc(diff >> 24, f);
1924             putc(diff >> 16, f);
1925             putc(diff >> 8, f);
1926             putc(diff, f);
1927         } else {
1928             putc(6, f);
1929             putc(diff, f);
1930         }
1931         *tp = now;
1932     }
1933     putc(code, f);
1934     if (buf != NULL) {
1935         putc(nb >> 8, f);
1936         putc(nb, f);
1937         fwrite(buf, nb, 1, f);
1938     }
1939     fflush(f);
1940     if (ferror(f)) {
1941         error("Error writing record file: %m");
1942         return 0;
1943     }
1944     return 1;
1945 }