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