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