]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
a01b852cc26c1dad05dabd37dcdecb5694694aa3
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  *
18  * 3. The name "Carnegie Mellon University" must not be used to
19  *    endorse or promote products derived from this software without
20  *    prior written permission. For permission or any legal
21  *    details, please contact
22  *      Office of Technology Transfer
23  *      Carnegie Mellon University
24  *      5000 Forbes Avenue
25  *      Pittsburgh, PA  15213-3890
26  *      (412) 268-4387, fax: (412) 268-7395
27  *      tech-transfer@andrew.cmu.edu
28  *
29  * 4. Redistributions of any form whatsoever must retain the following
30  *    acknowledgment:
31  *    "This product includes software developed by Computing Services
32  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
33  *
34  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
35  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
36  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
37  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
39  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
40  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41  */
42
43 #define RCSID   "$Id: main.c,v 1.123 2003/03/03 05:11:46 paulus Exp $"
44
45 #include <stdio.h>
46 #include <ctype.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <signal.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <syslog.h>
54 #include <netdb.h>
55 #include <utmp.h>
56 #include <pwd.h>
57 #include <setjmp.h>
58 #include <sys/param.h>
59 #include <sys/types.h>
60 #include <sys/wait.h>
61 #include <sys/time.h>
62 #include <sys/resource.h>
63 #include <sys/stat.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <arpa/inet.h>
67
68 #include "pppd.h"
69 #include "magic.h"
70 #include "fsm.h"
71 #include "lcp.h"
72 #include "ipcp.h"
73 #ifdef INET6
74 #include "ipv6cp.h"
75 #endif
76 #include "upap.h"
77 #include "chap.h"
78 #include "eap.h"
79 #include "ccp.h"
80 #include "ecp.h"
81 #include "pathnames.h"
82
83 #ifdef USE_TDB
84 #include "tdb.h"
85 #endif
86
87 #ifdef CBCP_SUPPORT
88 #include "cbcp.h"
89 #endif
90
91 #ifdef IPX_CHANGE
92 #include "ipxcp.h"
93 #endif /* IPX_CHANGE */
94 #ifdef AT_CHANGE
95 #include "atcp.h"
96 #endif
97
98 static const char rcsid[] = RCSID;
99
100 /* interface vars */
101 char ifname[32];                /* Interface name */
102 int ifunit;                     /* Interface unit number */
103
104 struct channel *the_channel;
105
106 char *progname;                 /* Name of this program */
107 char hostname[MAXNAMELEN];      /* Our hostname */
108 static char pidfilename[MAXPATHLEN];    /* name of pid file */
109 static char linkpidfile[MAXPATHLEN];    /* name of linkname pid file */
110 char ppp_devnam[MAXPATHLEN];    /* name of PPP tty (maybe ttypx) */
111 uid_t uid;                      /* Our real user-id */
112 struct notifier *pidchange = NULL;
113 struct notifier *phasechange = NULL;
114 struct notifier *exitnotify = NULL;
115 struct notifier *sigreceived = NULL;
116 struct notifier *fork_notifier = NULL;
117
118 int hungup;                     /* terminal has been hung up */
119 int privileged;                 /* we're running as real uid root */
120 int need_holdoff;               /* need holdoff period before restarting */
121 int detached;                   /* have detached from terminal */
122 volatile int status;            /* exit status for pppd */
123 int unsuccess;                  /* # unsuccessful connection attempts */
124 int do_callback;                /* != 0 if we should do callback next */
125 int doing_callback;             /* != 0 if we are doing callback */
126 int ppp_session_number;         /* Session number, for channels with such a
127                                    concept (eg PPPoE) */
128 #ifdef USE_TDB
129 TDB_CONTEXT *pppdb;             /* database for storing status etc. */
130 #endif
131
132 char db_key[32];
133
134 int (*holdoff_hook) __P((void)) = NULL;
135 int (*new_phase_hook) __P((int)) = NULL;
136 void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
137 void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
138
139 static int conn_running;        /* we have a [dis]connector running */
140 static int devfd;               /* fd of underlying device */
141 static int fd_ppp = -1;         /* fd for talking PPP */
142 static int fd_loop;             /* fd for getting demand-dial packets */
143 static int fd_devnull;          /* fd for /dev/null */
144
145 int phase;                      /* where the link is at */
146 int kill_link;
147 int open_ccp_flag;
148 int listen_time;
149 int got_sigusr2;
150 int got_sigterm;
151 int got_sighup;
152
153 static int waiting;
154 static sigjmp_buf sigjmp;
155
156 char **script_env;              /* Env. variable values for scripts */
157 int s_env_nalloc;               /* # words avail at script_env */
158
159 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
160 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
161
162 static int n_children;          /* # child processes still running */
163 static int got_sigchld;         /* set if we have received a SIGCHLD */
164
165 int privopen;                   /* don't lock, open device as root */
166
167 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
168
169 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
170 int ngroups;                    /* How many groups valid in groups */
171
172 static struct timeval start_time;       /* Time when link was started. */
173
174 struct pppd_stats link_stats;
175 unsigned link_connect_time;
176 int link_stats_valid;
177
178 /*
179  * We maintain a list of child process pids and
180  * functions to call when they exit.
181  */
182 struct subprocess {
183     pid_t       pid;
184     char        *prog;
185     void        (*done) __P((void *));
186     void        *arg;
187     struct subprocess *next;
188 };
189
190 static struct subprocess *children;
191
192 /* Prototypes for procedures local to this file. */
193
194 static void setup_signals __P((void));
195 static void create_pidfile __P((int pid));
196 static void create_linkpidfile __P((int pid));
197 static void cleanup __P((void));
198 static void get_input __P((void));
199 static void calltimeout __P((void));
200 static struct timeval *timeleft __P((struct timeval *));
201 static void kill_my_pg __P((int));
202 static void hup __P((int));
203 static void term __P((int));
204 static void chld __P((int));
205 static void toggle_debug __P((int));
206 static void open_ccp __P((int));
207 static void bad_signal __P((int));
208 static void holdoff_end __P((void *));
209 static int reap_kids __P((int waitfor));
210
211 #ifdef USE_TDB
212 static void update_db_entry __P((void));
213 static void add_db_key __P((const char *));
214 static void delete_db_key __P((const char *));
215 static void cleanup_db __P((void));
216 #endif
217
218 static void handle_events __P((void));
219 static void print_link_stats __P((void));
220
221 extern  char    *ttyname __P((int));
222 extern  char    *getlogin __P((void));
223 int main __P((int, char *[]));
224
225 #ifdef ultrix
226 #undef  O_NONBLOCK
227 #define O_NONBLOCK      O_NDELAY
228 #endif
229
230 #ifdef ULTRIX
231 #define setlogmask(x)
232 #endif
233
234 /*
235  * PPP Data Link Layer "protocol" table.
236  * One entry per supported protocol.
237  * The last entry must be NULL.
238  */
239 struct protent *protocols[] = {
240     &lcp_protent,
241     &pap_protent,
242     &chap_protent,
243 #ifdef CBCP_SUPPORT
244     &cbcp_protent,
245 #endif
246     &ipcp_protent,
247 #ifdef INET6
248     &ipv6cp_protent,
249 #endif
250     &ccp_protent,
251     &ecp_protent,
252 #ifdef IPX_CHANGE
253     &ipxcp_protent,
254 #endif
255 #ifdef AT_CHANGE
256     &atcp_protent,
257 #endif
258     &eap_protent,
259     NULL
260 };
261
262 /*
263  * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
264  */
265 #if !defined(PPP_DRV_NAME)
266 #define PPP_DRV_NAME    "ppp"
267 #endif /* !defined(PPP_DRV_NAME) */
268
269 int
270 main(argc, argv)
271     int argc;
272     char *argv[];
273 {
274     int i, t;
275     char *p;
276     struct passwd *pw;
277     struct protent *protp;
278     char numbuf[16];
279
280     link_stats_valid = 0;
281     new_phase(PHASE_INITIALIZE);
282
283     script_env = NULL;
284
285     /* Initialize syslog facilities */
286     reopen_log();
287
288     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
289         option_error("Couldn't get hostname: %m");
290         exit(1);
291     }
292     hostname[MAXNAMELEN-1] = 0;
293
294     /* make sure we don't create world or group writable files. */
295     umask(umask(0777) | 022);
296
297     uid = getuid();
298     privileged = uid == 0;
299     slprintf(numbuf, sizeof(numbuf), "%d", uid);
300     script_setenv("ORIG_UID", numbuf, 0);
301
302     ngroups = getgroups(NGROUPS_MAX, groups);
303
304     /*
305      * Initialize magic number generator now so that protocols may
306      * use magic numbers in initialization.
307      */
308     magic_init();
309
310     /*
311      * Initialize each protocol.
312      */
313     for (i = 0; (protp = protocols[i]) != NULL; ++i)
314         (*protp->init)(0);
315
316     /*
317      * Initialize the default channel.
318      */
319     tty_init();
320
321     progname = *argv;
322
323     /*
324      * Parse, in order, the system options file, the user's options file,
325      * and the command line arguments.
326      */
327     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
328         || !options_from_user()
329         || !parse_args(argc-1, argv+1))
330         exit(EXIT_OPTION_ERROR);
331     devnam_fixed = 1;           /* can no longer change device name */
332
333     /*
334      * Work out the device name, if it hasn't already been specified,
335      * and parse the tty's options file.
336      */
337     if (the_channel->process_extra_options)
338         (*the_channel->process_extra_options)();
339
340     if (debug)
341         setlogmask(LOG_UPTO(LOG_DEBUG));
342
343     /*
344      * Check that we are running as root.
345      */
346     if (geteuid() != 0) {
347         option_error("must be root to run %s, since it is not setuid-root",
348                      argv[0]);
349         exit(EXIT_NOT_ROOT);
350     }
351
352     if (!ppp_available()) {
353         option_error("%s", no_ppp_msg);
354         exit(EXIT_NO_KERNEL_SUPPORT);
355     }
356
357     /*
358      * Check that the options given are valid and consistent.
359      */
360     check_options();
361     if (!sys_check_options())
362         exit(EXIT_OPTION_ERROR);
363     auth_check_options();
364 #ifdef HAVE_MULTILINK
365     mp_check_options();
366 #endif
367     for (i = 0; (protp = protocols[i]) != NULL; ++i)
368         if (protp->check_options != NULL)
369             (*protp->check_options)();
370     if (the_channel->check_options)
371         (*the_channel->check_options)();
372
373
374     if (dump_options || dryrun) {
375         init_pr_log(NULL, LOG_INFO);
376         print_options(pr_log, NULL);
377         end_pr_log();
378     }
379
380     if (dryrun)
381         die(0);
382
383     /*
384      * Initialize system-dependent stuff.
385      */
386     sys_init();
387
388     /* Make sure fds 0, 1, 2 are open to somewhere. */
389     fd_devnull = open(_PATH_DEVNULL, O_RDWR);
390     if (fd_devnull < 0)
391         fatal("Couldn't open %s: %m", _PATH_DEVNULL);
392     while (fd_devnull <= 2) {
393         i = dup(fd_devnull);
394         if (i < 0)
395             fatal("Critical shortage of file descriptors: dup failed: %m");
396         fd_devnull = i;
397     }
398
399 #ifdef USE_TDB
400     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
401     if (pppdb != NULL) {
402         slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
403         update_db_entry();
404     } else {
405         warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
406         if (multilink) {
407             warn("Warning: disabling multilink");
408             multilink = 0;
409         }
410     }
411 #endif
412
413     /*
414      * Detach ourselves from the terminal, if required,
415      * and identify who is running us.
416      */
417     if (!nodetach && !updetach)
418         detach();
419     p = getlogin();
420     if (p == NULL) {
421         pw = getpwuid(uid);
422         if (pw != NULL && pw->pw_name != NULL)
423             p = pw->pw_name;
424         else
425             p = "(unknown)";
426     }
427     syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
428     script_setenv("PPPLOGNAME", p, 0);
429
430     if (devnam[0])
431         script_setenv("DEVICE", devnam, 1);
432     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
433     script_setenv("PPPD_PID", numbuf, 1);
434
435     setup_signals();
436
437     waiting = 0;
438
439     create_linkpidfile(getpid());
440
441     /*
442      * If we're doing dial-on-demand, set up the interface now.
443      */
444     if (demand) {
445         /*
446          * Open the loopback channel and set it up to be the ppp interface.
447          */
448 #ifdef USE_TDB
449         tdb_writelock(pppdb);
450 #endif
451         fd_loop = open_ppp_loopback();
452         set_ifunit(1);
453 #ifdef USE_TDB
454         tdb_writeunlock(pppdb);
455 #endif
456         /*
457          * Configure the interface and mark it up, etc.
458          */
459         demand_conf();
460     }
461
462     do_callback = 0;
463     for (;;) {
464
465         listen_time = 0;
466         need_holdoff = 1;
467         devfd = -1;
468         status = EXIT_OK;
469         ++unsuccess;
470         doing_callback = do_callback;
471         do_callback = 0;
472
473         if (demand && !doing_callback) {
474             /*
475              * Don't do anything until we see some activity.
476              */
477             new_phase(PHASE_DORMANT);
478             demand_unblock();
479             add_fd(fd_loop);
480             for (;;) {
481                 handle_events();
482                 if (kill_link && !persist)
483                     break;
484                 if (get_loop_output())
485                     break;
486             }
487             remove_fd(fd_loop);
488             if (kill_link && !persist)
489                 break;
490
491             /*
492              * Now we want to bring up the link.
493              */
494             demand_block();
495             info("Starting link");
496         }
497
498         new_phase(PHASE_SERIALCONN);
499
500         devfd = the_channel->connect();
501         if (devfd < 0)
502             goto fail;
503
504         /* set up the serial device as a ppp interface */
505 #ifdef USE_TDB
506         tdb_writelock(pppdb);
507 #endif
508         fd_ppp = the_channel->establish_ppp(devfd);
509         if (fd_ppp < 0) {
510 #ifdef USE_TDB
511             tdb_writeunlock(pppdb);
512 #endif
513             status = EXIT_FATAL_ERROR;
514             goto disconnect;
515         }
516
517         if (!demand && ifunit >= 0)
518             set_ifunit(1);
519 #ifdef USE_TDB
520         tdb_writeunlock(pppdb);
521 #endif
522
523         /*
524          * Start opening the connection and wait for
525          * incoming events (reply, timeout, etc.).
526          */
527         if (ifunit >= 0)
528                 notice("Connect: %s <--> %s", ifname, ppp_devnam);
529         else
530                 notice("Starting negotiation on %s", ppp_devnam);
531         gettimeofday(&start_time, NULL);
532         script_unsetenv("CONNECT_TIME");
533         script_unsetenv("BYTES_SENT");
534         script_unsetenv("BYTES_RCVD");
535         lcp_lowerup(0);
536
537         add_fd(fd_ppp);
538         lcp_open(0);            /* Start protocol */
539         status = EXIT_NEGOTIATION_FAILED;
540         new_phase(PHASE_ESTABLISH);
541         while (phase != PHASE_DEAD) {
542             handle_events();
543             get_input();
544             if (kill_link)
545                 lcp_close(0, "User request");
546             if (open_ccp_flag) {
547                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
548                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
549                     (*ccp_protent.open)(0);
550                 }
551             }
552         }
553
554         print_link_stats();
555
556         /*
557          * Delete pid file before disestablishing ppp.  Otherwise it
558          * can happen that another pppd gets the same unit and then
559          * we delete its pid file.
560          */
561         if (!demand) {
562             if (pidfilename[0] != 0
563                 && unlink(pidfilename) < 0 && errno != ENOENT)
564                 warn("unable to delete pid file %s: %m", pidfilename);
565             pidfilename[0] = 0;
566         }
567
568         /*
569          * If we may want to bring the link up again, transfer
570          * the ppp unit back to the loopback.  Set the
571          * real serial device back to its normal mode of operation.
572          */
573         remove_fd(fd_ppp);
574         clean_check();
575         the_channel->disestablish_ppp(devfd);
576         fd_ppp = -1;
577         if (!hungup)
578             lcp_lowerdown(0);
579         if (!demand)
580             script_unsetenv("IFNAME");
581
582         /*
583          * Run disconnector script, if requested.
584          * XXX we may not be able to do this if the line has hung up!
585          */
586     disconnect:
587         new_phase(PHASE_DISCONNECT);
588         the_channel->disconnect();
589
590     fail:
591         if (the_channel->cleanup)
592             (*the_channel->cleanup)();
593
594         if (!demand) {
595             if (pidfilename[0] != 0
596                 && unlink(pidfilename) < 0 && errno != ENOENT)
597                 warn("unable to delete pid file %s: %m", pidfilename);
598             pidfilename[0] = 0;
599         }
600
601         if (!persist || (maxfail > 0 && unsuccess >= maxfail))
602             break;
603
604         if (demand)
605             demand_discard();
606         t = need_holdoff? holdoff: 0;
607         if (holdoff_hook)
608             t = (*holdoff_hook)();
609         if (t > 0) {
610             new_phase(PHASE_HOLDOFF);
611             TIMEOUT(holdoff_end, NULL, t);
612             do {
613                 handle_events();
614                 if (kill_link)
615                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
616             } while (phase == PHASE_HOLDOFF);
617             if (!persist)
618                 break;
619         }
620     }
621
622     /* Wait for scripts to finish */
623     /* XXX should have a timeout here */
624     while (n_children > 0) {
625         if (debug) {
626             struct subprocess *chp;
627             dbglog("Waiting for %d child processes...", n_children);
628             for (chp = children; chp != NULL; chp = chp->next)
629                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
630         }
631         if (reap_kids(1) < 0)
632             break;
633     }
634
635     die(status);
636     return 0;
637 }
638
639 /*
640  * handle_events - wait for something to happen and respond to it.
641  */
642 static void
643 handle_events()
644 {
645     struct timeval timo;
646     sigset_t mask;
647
648     kill_link = open_ccp_flag = 0;
649     if (sigsetjmp(sigjmp, 1) == 0) {
650         sigprocmask(SIG_BLOCK, &mask, NULL);
651         if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
652             sigprocmask(SIG_UNBLOCK, &mask, NULL);
653         } else {
654             waiting = 1;
655             sigprocmask(SIG_UNBLOCK, &mask, NULL);
656             wait_input(timeleft(&timo));
657         }
658     }
659     waiting = 0;
660     calltimeout();
661     if (got_sighup) {
662         kill_link = 1;
663         got_sighup = 0;
664         if (status != EXIT_HANGUP)
665             status = EXIT_USER_REQUEST;
666     }
667     if (got_sigterm) {
668         kill_link = 1;
669         persist = 0;
670         status = EXIT_USER_REQUEST;
671         got_sigterm = 0;
672     }
673     if (got_sigchld) {
674         reap_kids(0);   /* Don't leave dead kids lying around */
675         got_sigchld = 0;
676     }
677     if (got_sigusr2) {
678         open_ccp_flag = 1;
679         got_sigusr2 = 0;
680     }
681 }
682
683 /*
684  * setup_signals - initialize signal handling.
685  */
686 static void
687 setup_signals()
688 {
689     struct sigaction sa;
690     sigset_t mask;
691
692     /*
693      * Compute mask of all interesting signals and install signal handlers
694      * for each.  Only one signal handler may be active at a time.  Therefore,
695      * all other signals should be masked when any handler is executing.
696      */
697     sigemptyset(&mask);
698     sigaddset(&mask, SIGHUP);
699     sigaddset(&mask, SIGINT);
700     sigaddset(&mask, SIGTERM);
701     sigaddset(&mask, SIGCHLD);
702     sigaddset(&mask, SIGUSR2);
703
704 #define SIGNAL(s, handler)      do { \
705         sa.sa_handler = handler; \
706         if (sigaction(s, &sa, NULL) < 0) \
707             fatal("Couldn't establish signal handler (%d): %m", s); \
708     } while (0)
709
710     sa.sa_mask = mask;
711     sa.sa_flags = 0;
712     SIGNAL(SIGHUP, hup);                /* Hangup */
713     SIGNAL(SIGINT, term);               /* Interrupt */
714     SIGNAL(SIGTERM, term);              /* Terminate */
715     SIGNAL(SIGCHLD, chld);
716
717     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
718     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
719
720     /*
721      * Install a handler for other signals which would otherwise
722      * cause pppd to exit without cleaning up.
723      */
724     SIGNAL(SIGABRT, bad_signal);
725     SIGNAL(SIGALRM, bad_signal);
726     SIGNAL(SIGFPE, bad_signal);
727     SIGNAL(SIGILL, bad_signal);
728     SIGNAL(SIGPIPE, bad_signal);
729     SIGNAL(SIGQUIT, bad_signal);
730     SIGNAL(SIGSEGV, bad_signal);
731 #ifdef SIGBUS
732     SIGNAL(SIGBUS, bad_signal);
733 #endif
734 #ifdef SIGEMT
735     SIGNAL(SIGEMT, bad_signal);
736 #endif
737 #ifdef SIGPOLL
738     SIGNAL(SIGPOLL, bad_signal);
739 #endif
740 #ifdef SIGPROF
741     SIGNAL(SIGPROF, bad_signal);
742 #endif
743 #ifdef SIGSYS
744     SIGNAL(SIGSYS, bad_signal);
745 #endif
746 #ifdef SIGTRAP
747     SIGNAL(SIGTRAP, bad_signal);
748 #endif
749 #ifdef SIGVTALRM
750     SIGNAL(SIGVTALRM, bad_signal);
751 #endif
752 #ifdef SIGXCPU
753     SIGNAL(SIGXCPU, bad_signal);
754 #endif
755 #ifdef SIGXFSZ
756     SIGNAL(SIGXFSZ, bad_signal);
757 #endif
758
759     /*
760      * Apparently we can get a SIGPIPE when we call syslog, if
761      * syslogd has died and been restarted.  Ignoring it seems
762      * be sufficient.
763      */
764     signal(SIGPIPE, SIG_IGN);
765 }
766
767 /*
768  * set_ifunit - do things we need to do once we know which ppp
769  * unit we are using.
770  */
771 void
772 set_ifunit(iskey)
773     int iskey;
774 {
775     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
776     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
777     script_setenv("IFNAME", ifname, iskey);
778     if (iskey) {
779         create_pidfile(getpid());       /* write pid to file */
780         create_linkpidfile(getpid());
781     }
782 }
783
784 /*
785  * detach - detach us from the controlling terminal.
786  */
787 void
788 detach()
789 {
790     int pid;
791     char numbuf[16];
792     int pipefd[2];
793
794     if (detached)
795         return;
796     if (pipe(pipefd) == -1)
797         pipefd[0] = pipefd[1] = -1;
798     if ((pid = fork()) < 0) {
799         error("Couldn't detach (fork failed: %m)");
800         die(1);                 /* or just return? */
801     }
802     if (pid != 0) {
803         /* parent */
804         notify(pidchange, pid);
805         /* update pid files if they have been written already */
806         if (pidfilename[0])
807             create_pidfile(pid);
808         if (linkpidfile[0])
809             create_linkpidfile(pid);
810         exit(0);                /* parent dies */
811     }
812     setsid();
813     chdir("/");
814     dup2(fd_devnull, 0);
815     dup2(fd_devnull, 1);
816     dup2(fd_devnull, 2);
817     detached = 1;
818     if (log_default)
819         log_to_fd = -1;
820     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
821     script_setenv("PPPD_PID", numbuf, 1);
822
823     /* wait for parent to finish updating pid & lock files and die */
824     close(pipefd[1]);
825     read(pipefd[0], numbuf, 1);
826     close(pipefd[0]);
827 }
828
829 /*
830  * reopen_log - (re)open our connection to syslog.
831  */
832 void
833 reopen_log()
834 {
835 #ifdef ULTRIX
836     openlog("pppd", LOG_PID);
837 #else
838     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
839     setlogmask(LOG_UPTO(LOG_INFO));
840 #endif
841 }
842
843 /*
844  * Create a file containing our process ID.
845  */
846 static void
847 create_pidfile(pid)
848     int pid;
849 {
850     FILE *pidfile;
851
852     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
853              _PATH_VARRUN, ifname);
854     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
855         fprintf(pidfile, "%d\n", getpid());
856         (void) fclose(pidfile);
857     } else {
858         error("Failed to create pid file %s: %m", pidfilename);
859         pidfilename[0] = 0;
860     }
861 }
862
863 static void
864 create_linkpidfile(pid)
865     int pid;
866 {
867     FILE *pidfile;
868
869     if (linkname[0] == 0)
870         return;
871     script_setenv("LINKNAME", linkname, 1);
872     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
873              _PATH_VARRUN, linkname);
874     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
875         fprintf(pidfile, "%d\n", getpid());
876         if (ifname[0])
877             fprintf(pidfile, "%s\n", ifname);
878         (void) fclose(pidfile);
879     } else {
880         error("Failed to create pid file %s: %m", linkpidfile);
881         linkpidfile[0] = 0;
882     }
883 }
884
885 /*
886  * holdoff_end - called via a timeout when the holdoff period ends.
887  */
888 static void
889 holdoff_end(arg)
890     void *arg;
891 {
892     new_phase(PHASE_DORMANT);
893 }
894
895 /* List of protocol names, to make our messages a little more informative. */
896 struct protocol_list {
897     u_short     proto;
898     const char  *name;
899 } protocol_list[] = {
900     { 0x21,     "IP" },
901     { 0x23,     "OSI Network Layer" },
902     { 0x25,     "Xerox NS IDP" },
903     { 0x27,     "DECnet Phase IV" },
904     { 0x29,     "Appletalk" },
905     { 0x2b,     "Novell IPX" },
906     { 0x2d,     "VJ compressed TCP/IP" },
907     { 0x2f,     "VJ uncompressed TCP/IP" },
908     { 0x31,     "Bridging PDU" },
909     { 0x33,     "Stream Protocol ST-II" },
910     { 0x35,     "Banyan Vines" },
911     { 0x39,     "AppleTalk EDDP" },
912     { 0x3b,     "AppleTalk SmartBuffered" },
913     { 0x3d,     "Multi-Link" },
914     { 0x3f,     "NETBIOS Framing" },
915     { 0x41,     "Cisco Systems" },
916     { 0x43,     "Ascom Timeplex" },
917     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
918     { 0x47,     "DCA Remote Lan" },
919     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
920     { 0x4b,     "SNA over 802.2" },
921     { 0x4d,     "SNA" },
922     { 0x4f,     "IP6 Header Compression" },
923     { 0x6f,     "Stampede Bridging" },
924     { 0xfb,     "single-link compression" },
925     { 0xfd,     "1st choice compression" },
926     { 0x0201,   "802.1d Hello Packets" },
927     { 0x0203,   "IBM Source Routing BPDU" },
928     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
929     { 0x0231,   "Luxcom" },
930     { 0x0233,   "Sigma Network Systems" },
931     { 0x8021,   "Internet Protocol Control Protocol" },
932     { 0x8023,   "OSI Network Layer Control Protocol" },
933     { 0x8025,   "Xerox NS IDP Control Protocol" },
934     { 0x8027,   "DECnet Phase IV Control Protocol" },
935     { 0x8029,   "Appletalk Control Protocol" },
936     { 0x802b,   "Novell IPX Control Protocol" },
937     { 0x8031,   "Bridging NCP" },
938     { 0x8033,   "Stream Protocol Control Protocol" },
939     { 0x8035,   "Banyan Vines Control Protocol" },
940     { 0x803d,   "Multi-Link Control Protocol" },
941     { 0x803f,   "NETBIOS Framing Control Protocol" },
942     { 0x8041,   "Cisco Systems Control Protocol" },
943     { 0x8043,   "Ascom Timeplex" },
944     { 0x8045,   "Fujitsu LBLB Control Protocol" },
945     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
946     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
947     { 0x804b,   "SNA over 802.2 Control Protocol" },
948     { 0x804d,   "SNA Control Protocol" },
949     { 0x804f,   "IP6 Header Compression Control Protocol" },
950     { 0x006f,   "Stampede Bridging Control Protocol" },
951     { 0x80fb,   "Single Link Compression Control Protocol" },
952     { 0x80fd,   "Compression Control Protocol" },
953     { 0xc021,   "Link Control Protocol" },
954     { 0xc023,   "Password Authentication Protocol" },
955     { 0xc025,   "Link Quality Report" },
956     { 0xc027,   "Shiva Password Authentication Protocol" },
957     { 0xc029,   "CallBack Control Protocol (CBCP)" },
958     { 0xc081,   "Container Control Protocol" },
959     { 0xc223,   "Challenge Handshake Authentication Protocol" },
960     { 0xc281,   "Proprietary Authentication Protocol" },
961     { 0,        NULL },
962 };
963
964 /*
965  * protocol_name - find a name for a PPP protocol.
966  */
967 const char *
968 protocol_name(proto)
969     int proto;
970 {
971     struct protocol_list *lp;
972
973     for (lp = protocol_list; lp->proto != 0; ++lp)
974         if (proto == lp->proto)
975             return lp->name;
976     return NULL;
977 }
978
979 /*
980  * get_input - called when incoming data is available.
981  */
982 static void
983 get_input()
984 {
985     int len, i;
986     u_char *p;
987     u_short protocol;
988     struct protent *protp;
989
990     p = inpacket_buf;   /* point to beginning of packet buffer */
991
992     len = read_packet(inpacket_buf);
993     if (len < 0)
994         return;
995
996     if (len == 0) {
997         notice("Modem hangup");
998         hungup = 1;
999         status = EXIT_HANGUP;
1000         lcp_lowerdown(0);       /* serial link is no longer available */
1001         link_terminated(0);
1002         return;
1003     }
1004
1005     if (len < PPP_HDRLEN) {
1006         dbglog("received short packet:%.*B", len, p);
1007         return;
1008     }
1009
1010     dump_packet("rcvd", p, len);
1011     if (snoop_recv_hook) snoop_recv_hook(p, len);
1012
1013     p += 2;                             /* Skip address and control */
1014     GETSHORT(protocol, p);
1015     len -= PPP_HDRLEN;
1016
1017     /*
1018      * Toss all non-LCP packets unless LCP is OPEN.
1019      */
1020     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1021         dbglog("Discarded non-LCP packet when LCP not open");
1022         return;
1023     }
1024
1025     /*
1026      * Until we get past the authentication phase, toss all packets
1027      * except LCP, LQR and authentication packets.
1028      */
1029     if (phase <= PHASE_AUTHENTICATE
1030         && !(protocol == PPP_LCP || protocol == PPP_LQR
1031              || protocol == PPP_PAP || protocol == PPP_CHAP ||
1032                 protocol == PPP_EAP)) {
1033         dbglog("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         const char *pname = protocol_name(protocol);
1055         if (pname != NULL)
1056             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1057         else
1058             warn("Unsupported protocol 0x%x received", protocol);
1059     }
1060     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1061 }
1062
1063 /*
1064  * new_phase - signal the start of a new phase of pppd's operation.
1065  */
1066 void
1067 new_phase(p)
1068     int p;
1069 {
1070     phase = p;
1071     if (new_phase_hook)
1072         (*new_phase_hook)(p);
1073     notify(phasechange, p);
1074 }
1075
1076 /*
1077  * die - clean up state and exit with the specified status.
1078  */
1079 void
1080 die(status)
1081     int status;
1082 {
1083         print_link_stats();
1084     cleanup();
1085     notify(exitnotify, status);
1086     syslog(LOG_INFO, "Exit.");
1087     exit(status);
1088 }
1089
1090 /*
1091  * cleanup - restore anything which needs to be restored before we exit
1092  */
1093 /* ARGSUSED */
1094 static void
1095 cleanup()
1096 {
1097     sys_cleanup();
1098
1099     if (fd_ppp >= 0)
1100         the_channel->disestablish_ppp(devfd);
1101     if (the_channel->cleanup)
1102         (*the_channel->cleanup)();
1103
1104     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1105         warn("unable to delete pid file %s: %m", pidfilename);
1106     pidfilename[0] = 0;
1107     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1108         warn("unable to delete pid file %s: %m", linkpidfile);
1109     linkpidfile[0] = 0;
1110
1111 #ifdef USE_TDB
1112     if (pppdb != NULL)
1113         cleanup_db();
1114 #endif
1115
1116 }
1117
1118 void
1119 print_link_stats()
1120 {
1121     /*
1122      * Print connect time and statistics.
1123      */
1124     if (link_stats_valid) {
1125        int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
1126        info("Connect time %d.%d minutes.", t/10, t%10);
1127        info("Sent %u bytes, received %u bytes.",
1128             link_stats.bytes_out, link_stats.bytes_in);
1129     }
1130 }
1131
1132 /*
1133  * update_link_stats - get stats at link termination.
1134  */
1135 void
1136 update_link_stats(u)
1137     int u;
1138 {
1139     struct timeval now;
1140     char numbuf[32];
1141
1142     if (!get_ppp_stats(u, &link_stats)
1143         || gettimeofday(&now, NULL) < 0)
1144         return;
1145     link_connect_time = now.tv_sec - start_time.tv_sec;
1146     link_stats_valid = 1;
1147
1148     slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
1149     script_setenv("CONNECT_TIME", numbuf, 0);
1150     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
1151     script_setenv("BYTES_SENT", numbuf, 0);
1152     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
1153     script_setenv("BYTES_RCVD", numbuf, 0);
1154 }
1155
1156
1157 struct  callout {
1158     struct timeval      c_time;         /* time at which to call routine */
1159     void                *c_arg;         /* argument to routine */
1160     void                (*c_func) __P((void *)); /* routine */
1161     struct              callout *c_next;
1162 };
1163
1164 static struct callout *callout = NULL;  /* Callout list */
1165 static struct timeval timenow;          /* Current time */
1166
1167 /*
1168  * timeout - Schedule a timeout.
1169  */
1170 void
1171 timeout(func, arg, secs, usecs)
1172     void (*func) __P((void *));
1173     void *arg;
1174     int secs, usecs;
1175 {
1176     struct callout *newp, *p, **pp;
1177
1178     MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
1179                secs, usecs/1000));
1180
1181     /*
1182      * Allocate timeout.
1183      */
1184     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1185         fatal("Out of memory in timeout()!");
1186     newp->c_arg = arg;
1187     newp->c_func = func;
1188     gettimeofday(&timenow, NULL);
1189     newp->c_time.tv_sec = timenow.tv_sec + secs;
1190     newp->c_time.tv_usec = timenow.tv_usec + usecs;
1191     if (newp->c_time.tv_usec >= 1000000) {
1192         newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1193         newp->c_time.tv_usec %= 1000000;
1194     }
1195
1196     /*
1197      * Find correct place and link it in.
1198      */
1199     for (pp = &callout; (p = *pp); pp = &p->c_next)
1200         if (newp->c_time.tv_sec < p->c_time.tv_sec
1201             || (newp->c_time.tv_sec == p->c_time.tv_sec
1202                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1203             break;
1204     newp->c_next = p;
1205     *pp = newp;
1206 }
1207
1208
1209 /*
1210  * untimeout - Unschedule a timeout.
1211  */
1212 void
1213 untimeout(func, arg)
1214     void (*func) __P((void *));
1215     void *arg;
1216 {
1217     struct callout **copp, *freep;
1218
1219     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1220
1221     /*
1222      * Find first matching timeout and remove it from the list.
1223      */
1224     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1225         if (freep->c_func == func && freep->c_arg == arg) {
1226             *copp = freep->c_next;
1227             free((char *) freep);
1228             break;
1229         }
1230 }
1231
1232
1233 /*
1234  * calltimeout - Call any timeout routines which are now due.
1235  */
1236 static void
1237 calltimeout()
1238 {
1239     struct callout *p;
1240
1241     while (callout != NULL) {
1242         p = callout;
1243
1244         if (gettimeofday(&timenow, NULL) < 0)
1245             fatal("Failed to get time of day: %m");
1246         if (!(p->c_time.tv_sec < timenow.tv_sec
1247               || (p->c_time.tv_sec == timenow.tv_sec
1248                   && p->c_time.tv_usec <= timenow.tv_usec)))
1249             break;              /* no, it's not time yet */
1250
1251         callout = p->c_next;
1252         (*p->c_func)(p->c_arg);
1253
1254         free((char *) p);
1255     }
1256 }
1257
1258
1259 /*
1260  * timeleft - return the length of time until the next timeout is due.
1261  */
1262 static struct timeval *
1263 timeleft(tvp)
1264     struct timeval *tvp;
1265 {
1266     if (callout == NULL)
1267         return NULL;
1268
1269     gettimeofday(&timenow, NULL);
1270     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1271     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1272     if (tvp->tv_usec < 0) {
1273         tvp->tv_usec += 1000000;
1274         tvp->tv_sec -= 1;
1275     }
1276     if (tvp->tv_sec < 0)
1277         tvp->tv_sec = tvp->tv_usec = 0;
1278
1279     return tvp;
1280 }
1281
1282
1283 /*
1284  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1285  */
1286 static void
1287 kill_my_pg(sig)
1288     int sig;
1289 {
1290     struct sigaction act, oldact;
1291
1292     act.sa_handler = SIG_IGN;
1293     act.sa_flags = 0;
1294     kill(0, sig);
1295     sigaction(sig, &act, &oldact);
1296     sigaction(sig, &oldact, NULL);
1297 }
1298
1299
1300 /*
1301  * hup - Catch SIGHUP signal.
1302  *
1303  * Indicates that the physical layer has been disconnected.
1304  * We don't rely on this indication; if the user has sent this
1305  * signal, we just take the link down.
1306  */
1307 static void
1308 hup(sig)
1309     int sig;
1310 {
1311     info("Hangup (SIGHUP)");
1312     got_sighup = 1;
1313     if (conn_running)
1314         /* Send the signal to the [dis]connector process(es) also */
1315         kill_my_pg(sig);
1316     notify(sigreceived, sig);
1317     if (waiting)
1318         siglongjmp(sigjmp, 1);
1319 }
1320
1321
1322 /*
1323  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1324  *
1325  * Indicates that we should initiate a graceful disconnect and exit.
1326  */
1327 /*ARGSUSED*/
1328 static void
1329 term(sig)
1330     int sig;
1331 {
1332     info("Terminating on signal %d.", sig);
1333     got_sigterm = 1;
1334     if (conn_running)
1335         /* Send the signal to the [dis]connector process(es) also */
1336         kill_my_pg(sig);
1337     notify(sigreceived, sig);
1338     if (waiting)
1339         siglongjmp(sigjmp, 1);
1340 }
1341
1342
1343 /*
1344  * chld - Catch SIGCHLD signal.
1345  * Sets a flag so we will call reap_kids in the mainline.
1346  */
1347 static void
1348 chld(sig)
1349     int sig;
1350 {
1351     got_sigchld = 1;
1352     if (waiting)
1353         siglongjmp(sigjmp, 1);
1354 }
1355
1356
1357 /*
1358  * toggle_debug - Catch SIGUSR1 signal.
1359  *
1360  * Toggle debug flag.
1361  */
1362 /*ARGSUSED*/
1363 static void
1364 toggle_debug(sig)
1365     int sig;
1366 {
1367     debug = !debug;
1368     if (debug) {
1369         setlogmask(LOG_UPTO(LOG_DEBUG));
1370     } else {
1371         setlogmask(LOG_UPTO(LOG_WARNING));
1372     }
1373 }
1374
1375
1376 /*
1377  * open_ccp - Catch SIGUSR2 signal.
1378  *
1379  * Try to (re)negotiate compression.
1380  */
1381 /*ARGSUSED*/
1382 static void
1383 open_ccp(sig)
1384     int sig;
1385 {
1386     got_sigusr2 = 1;
1387     if (waiting)
1388         siglongjmp(sigjmp, 1);
1389 }
1390
1391
1392 /*
1393  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1394  */
1395 static void
1396 bad_signal(sig)
1397     int sig;
1398 {
1399     static int crashed = 0;
1400
1401     if (crashed)
1402         _exit(127);
1403     crashed = 1;
1404     error("Fatal signal %d", sig);
1405     if (conn_running)
1406         kill_my_pg(SIGTERM);
1407     notify(sigreceived, sig);
1408     die(127);
1409 }
1410
1411 /*
1412  * safe_fork - Create a child process.  The child closes all the
1413  * file descriptors that we don't want to leak to a script.
1414  * The parent waits for the child to do this before returning.
1415  */
1416 pid_t
1417 safe_fork()
1418 {
1419         pid_t pid;
1420         int pipefd[2];
1421         char buf[1];
1422
1423         if (pipe(pipefd) == -1)
1424                 pipefd[0] = pipefd[1] = -1;
1425         pid = fork();
1426         if (pid < 0)
1427                 return -1;
1428         if (pid > 0) {
1429                 close(pipefd[1]);
1430                 /* this read() blocks until the close(pipefd[1]) below */
1431                 read(pipefd[0], buf, 1);
1432                 close(pipefd[0]);
1433                 return pid;
1434         }
1435         sys_close();
1436 #ifdef USE_TDB
1437         tdb_close(pppdb);
1438 #endif
1439         notify(fork_notifier, 0);
1440         close(pipefd[0]);
1441         /* this close unblocks the read() call above in the parent */
1442         close(pipefd[1]);
1443         return 0;
1444 }
1445
1446 /*
1447  * device_script - run a program to talk to the specified fds
1448  * (e.g. to run the connector or disconnector script).
1449  * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1450  */
1451 int
1452 device_script(program, in, out, dont_wait)
1453     char *program;
1454     int in, out;
1455     int dont_wait;
1456 {
1457     int pid;
1458     int status = -1;
1459     int errfd;
1460
1461     ++conn_running;
1462     pid = safe_fork();
1463
1464     if (pid < 0) {
1465         --conn_running;
1466         error("Failed to create child process: %m");
1467         return -1;
1468     }
1469
1470     if (pid != 0) {
1471         if (dont_wait) {
1472             record_child(pid, program, NULL, NULL);
1473             status = 0;
1474         } else {
1475             while (waitpid(pid, &status, 0) < 0) {
1476                 if (errno == EINTR)
1477                     continue;
1478                 fatal("error waiting for (dis)connection process: %m");
1479             }
1480             --conn_running;
1481         }
1482         return (status == 0 ? 0 : -1);
1483     }
1484
1485     /* here we are executing in the child */
1486
1487     /* dup in and out to fds > 2 */
1488     {
1489         int fd1 = in, fd2 = out, fd3 = log_to_fd;
1490
1491         in = dup(in);
1492         out = dup(out);
1493         if (log_to_fd >= 0) {
1494             errfd = dup(log_to_fd);
1495         } else {
1496             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1497         }
1498         close(fd1);
1499         close(fd2);
1500         close(fd3);
1501     }
1502
1503     /* close fds 0 - 2 and any others we can think of */
1504     close(0);
1505     close(1);
1506     close(2);
1507     if (the_channel->close)
1508         (*the_channel->close)();
1509     closelog();
1510     close(fd_devnull);
1511
1512     /* dup the in, out, err fds to 0, 1, 2 */
1513     dup2(in, 0);
1514     close(in);
1515     dup2(out, 1);
1516     close(out);
1517     if (errfd >= 0) {
1518         dup2(errfd, 2);
1519         close(errfd);
1520     }
1521
1522     setuid(uid);
1523     if (getuid() != uid) {
1524         error("setuid failed");
1525         exit(1);
1526     }
1527     setgid(getgid());
1528     execl("/bin/sh", "sh", "-c", program, (char *)0);
1529     error("could not exec /bin/sh: %m");
1530     exit(99);
1531     /* NOTREACHED */
1532 }
1533
1534
1535 /*
1536  * run-program - execute a program with given arguments,
1537  * but don't wait for it.
1538  * If the program can't be executed, logs an error unless
1539  * must_exist is 0 and the program file doesn't exist.
1540  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1541  * or isn't an executable plain file, or the process ID of the child.
1542  * If done != NULL, (*done)(arg) will be called later (within
1543  * reap_kids) iff the return value is > 0.
1544  */
1545 pid_t
1546 run_program(prog, args, must_exist, done, arg)
1547     char *prog;
1548     char **args;
1549     int must_exist;
1550     void (*done) __P((void *));
1551     void *arg;
1552 {
1553     int pid;
1554     struct stat sbuf;
1555
1556     /*
1557      * First check if the file exists and is executable.
1558      * We don't use access() because that would use the
1559      * real user-id, which might not be root, and the script
1560      * might be accessible only to root.
1561      */
1562     errno = EINVAL;
1563     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1564         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1565         if (must_exist || errno != ENOENT)
1566             warn("Can't execute %s: %m", prog);
1567         return 0;
1568     }
1569
1570     pid = safe_fork();
1571     if (pid == -1) {
1572         error("Failed to create child process for %s: %m", prog);
1573         return -1;
1574     }
1575     if (pid != 0) {
1576         if (debug)
1577             dbglog("Script %s started (pid %d)", prog, pid);
1578         record_child(pid, prog, done, arg);
1579         return pid;
1580     }
1581
1582     /* Leave the current location */
1583     (void) setsid();    /* No controlling tty. */
1584     (void) umask (S_IRWXG|S_IRWXO);
1585     (void) chdir ("/"); /* no current directory. */
1586     setuid(0);          /* set real UID = root */
1587     setgid(getegid());
1588
1589     /* Ensure that nothing of our device environment is inherited. */
1590     closelog();
1591     if (the_channel->close)
1592         (*the_channel->close)();
1593
1594     /* Don't pass handles to the PPP device, even by accident. */
1595     dup2(fd_devnull, 0);
1596     dup2(fd_devnull, 1);
1597     dup2(fd_devnull, 2);
1598     close(fd_devnull);
1599
1600 #ifdef BSD
1601     /* Force the priority back to zero if pppd is running higher. */
1602     if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1603         warn("can't reset priority to 0: %m");
1604 #endif
1605
1606     /* SysV recommends a second fork at this point. */
1607
1608     /* run the program */
1609     execve(prog, args, script_env);
1610     if (must_exist || errno != ENOENT) {
1611         /* have to reopen the log, there's nowhere else
1612            for the message to go. */
1613         reopen_log();
1614         syslog(LOG_ERR, "Can't execute %s: %m", prog);
1615         closelog();
1616     }
1617     _exit(-1);
1618 }
1619
1620
1621 /*
1622  * record_child - add a child process to the list for reap_kids
1623  * to use.
1624  */
1625 void
1626 record_child(pid, prog, done, arg)
1627     int pid;
1628     char *prog;
1629     void (*done) __P((void *));
1630     void *arg;
1631 {
1632     struct subprocess *chp;
1633
1634     ++n_children;
1635
1636     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1637     if (chp == NULL) {
1638         warn("losing track of %s process", prog);
1639     } else {
1640         chp->pid = pid;
1641         chp->prog = prog;
1642         chp->done = done;
1643         chp->arg = arg;
1644         chp->next = children;
1645         children = chp;
1646     }
1647 }
1648
1649
1650 /*
1651  * reap_kids - get status from any dead child processes,
1652  * and log a message for abnormal terminations.
1653  */
1654 static int
1655 reap_kids(waitfor)
1656     int waitfor;
1657 {
1658     int pid, status;
1659     struct subprocess *chp, **prevp;
1660
1661     if (n_children == 0)
1662         return 0;
1663     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1664            && pid != 0) {
1665         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1666             if (chp->pid == pid) {
1667                 --n_children;
1668                 *prevp = chp->next;
1669                 break;
1670             }
1671         }
1672         if (WIFSIGNALED(status)) {
1673             warn("Child process %s (pid %d) terminated with signal %d",
1674                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1675         } else if (debug)
1676             dbglog("Script %s finished (pid %d), status = 0x%x",
1677                    (chp? chp->prog: "??"), pid,
1678                    WIFEXITED(status) ? WEXITSTATUS(status) : status);
1679         if (chp && chp->done)
1680             (*chp->done)(chp->arg);
1681         if (chp)
1682             free(chp);
1683     }
1684     if (pid == -1) {
1685         if (errno == ECHILD)
1686             return -1;
1687         if (errno != EINTR)
1688             error("Error waiting for child process: %m");
1689     }
1690     return 0;
1691 }
1692
1693 /*
1694  * add_notifier - add a new function to be called when something happens.
1695  */
1696 void
1697 add_notifier(notif, func, arg)
1698     struct notifier **notif;
1699     notify_func func;
1700     void *arg;
1701 {
1702     struct notifier *np;
1703
1704     np = malloc(sizeof(struct notifier));
1705     if (np == 0)
1706         novm("notifier struct");
1707     np->next = *notif;
1708     np->func = func;
1709     np->arg = arg;
1710     *notif = np;
1711 }
1712
1713 /*
1714  * remove_notifier - remove a function from the list of things to
1715  * be called when something happens.
1716  */
1717 void
1718 remove_notifier(notif, func, arg)
1719     struct notifier **notif;
1720     notify_func func;
1721     void *arg;
1722 {
1723     struct notifier *np;
1724
1725     for (; (np = *notif) != 0; notif = &np->next) {
1726         if (np->func == func && np->arg == arg) {
1727             *notif = np->next;
1728             free(np);
1729             break;
1730         }
1731     }
1732 }
1733
1734 /*
1735  * notify - call a set of functions registered with add_notifier.
1736  */
1737 void
1738 notify(notif, val)
1739     struct notifier *notif;
1740     int val;
1741 {
1742     struct notifier *np;
1743
1744     while ((np = notif) != 0) {
1745         notif = np->next;
1746         (*np->func)(np->arg, val);
1747     }
1748 }
1749
1750 /*
1751  * novm - log an error message saying we ran out of memory, and die.
1752  */
1753 void
1754 novm(msg)
1755     char *msg;
1756 {
1757     fatal("Virtual memory exhausted allocating %s\n", msg);
1758 }
1759
1760 /*
1761  * script_setenv - set an environment variable value to be used
1762  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1763  */
1764 void
1765 script_setenv(var, value, iskey)
1766     char *var, *value;
1767     int iskey;
1768 {
1769     size_t varl = strlen(var);
1770     size_t vl = varl + strlen(value) + 2;
1771     int i;
1772     char *p, *newstring;
1773
1774     newstring = (char *) malloc(vl+1);
1775     if (newstring == 0)
1776         return;
1777     *newstring++ = iskey;
1778     slprintf(newstring, vl, "%s=%s", var, value);
1779
1780     /* check if this variable is already set */
1781     if (script_env != 0) {
1782         for (i = 0; (p = script_env[i]) != 0; ++i) {
1783             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1784 #ifdef USE_TDB
1785                 if (p[-1] && pppdb != NULL)
1786                     delete_db_key(p);
1787 #endif
1788                 free(p-1);
1789                 script_env[i] = newstring;
1790 #ifdef USE_TDB
1791                 if (iskey && pppdb != NULL)
1792                     add_db_key(newstring);
1793                 update_db_entry();
1794 #endif
1795                 return;
1796             }
1797         }
1798     } else {
1799         /* no space allocated for script env. ptrs. yet */
1800         i = 0;
1801         script_env = (char **) malloc(16 * sizeof(char *));
1802         if (script_env == 0)
1803             return;
1804         s_env_nalloc = 16;
1805     }
1806
1807     /* reallocate script_env with more space if needed */
1808     if (i + 1 >= s_env_nalloc) {
1809         int new_n = i + 17;
1810         char **newenv = (char **) realloc((void *)script_env,
1811                                           new_n * sizeof(char *));
1812         if (newenv == 0)
1813             return;
1814         script_env = newenv;
1815         s_env_nalloc = new_n;
1816     }
1817
1818     script_env[i] = newstring;
1819     script_env[i+1] = 0;
1820
1821 #ifdef USE_TDB
1822     if (pppdb != NULL) {
1823         if (iskey)
1824             add_db_key(newstring);
1825         update_db_entry();
1826     }
1827 #endif
1828 }
1829
1830 /*
1831  * script_unsetenv - remove a variable from the environment
1832  * for scripts.
1833  */
1834 void
1835 script_unsetenv(var)
1836     char *var;
1837 {
1838     int vl = strlen(var);
1839     int i;
1840     char *p;
1841
1842     if (script_env == 0)
1843         return;
1844     for (i = 0; (p = script_env[i]) != 0; ++i) {
1845         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1846 #ifdef USE_TDB
1847             if (p[-1] && pppdb != NULL)
1848                 delete_db_key(p);
1849 #endif
1850             free(p-1);
1851             while ((script_env[i] = script_env[i+1]) != 0)
1852                 ++i;
1853             break;
1854         }
1855     }
1856 #ifdef USE_TDB
1857     if (pppdb != NULL)
1858         update_db_entry();
1859 #endif
1860 }
1861
1862 #ifdef USE_TDB
1863 /*
1864  * update_db_entry - update our entry in the database.
1865  */
1866 static void
1867 update_db_entry()
1868 {
1869     TDB_DATA key, dbuf;
1870     int vlen, i;
1871     char *p, *q, *vbuf;
1872
1873     if (script_env == NULL)
1874         return;
1875     vlen = 0;
1876     for (i = 0; (p = script_env[i]) != 0; ++i)
1877         vlen += strlen(p) + 1;
1878     vbuf = malloc(vlen);
1879     if (vbuf == 0)
1880         novm("database entry");
1881     q = vbuf;
1882     for (i = 0; (p = script_env[i]) != 0; ++i)
1883         q += slprintf(q, vbuf + vlen - q, "%s;", p);
1884
1885     key.dptr = db_key;
1886     key.dsize = strlen(db_key);
1887     dbuf.dptr = vbuf;
1888     dbuf.dsize = vlen;
1889     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1890         error("tdb_store failed: %s", tdb_error(pppdb));
1891
1892     if (vbuf)
1893         free(vbuf);
1894
1895 }
1896
1897 /*
1898  * add_db_key - add a key that we can use to look up our database entry.
1899  */
1900 static void
1901 add_db_key(str)
1902     const char *str;
1903 {
1904     TDB_DATA key, dbuf;
1905
1906     key.dptr = (char *) str;
1907     key.dsize = strlen(str);
1908     dbuf.dptr = db_key;
1909     dbuf.dsize = strlen(db_key);
1910     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1911         error("tdb_store key failed: %s", tdb_error(pppdb));
1912 }
1913
1914 /*
1915  * delete_db_key - delete a key for looking up our database entry.
1916  */
1917 static void
1918 delete_db_key(str)
1919     const char *str;
1920 {
1921     TDB_DATA key;
1922
1923     key.dptr = (char *) str;
1924     key.dsize = strlen(str);
1925     tdb_delete(pppdb, key);
1926 }
1927
1928 /*
1929  * cleanup_db - delete all the entries we put in the database.
1930  */
1931 static void
1932 cleanup_db()
1933 {
1934     TDB_DATA key;
1935     int i;
1936     char *p;
1937
1938     key.dptr = db_key;
1939     key.dsize = strlen(db_key);
1940     tdb_delete(pppdb, key);
1941     for (i = 0; (p = script_env[i]) != 0; ++i)
1942         if (p[-1])
1943             delete_db_key(p);
1944 }
1945 #endif /* USE_TDB */