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