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