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