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