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