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