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