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