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