]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
eec19c760398d598ca9eb8e7650f295db0d9101a
[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.46 1998/03/26 04:46:04 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 <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/time.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42 #include <sys/socket.h>
43
44 #include "pppd.h"
45 #include "magic.h"
46 #include "fsm.h"
47 #include "lcp.h"
48 #include "ipcp.h"
49 #include "upap.h"
50 #include "chap.h"
51 #include "ccp.h"
52 #include "pathnames.h"
53 #include "patchlevel.h"
54
55 #ifdef CBCP_SUPPORT
56 #include "cbcp.h"
57 #endif
58
59 #if defined(SUNOS4)
60 extern char *strerror();
61 #endif
62
63 #ifdef IPX_CHANGE
64 #include "ipxcp.h"
65 #endif /* IPX_CHANGE */
66 #ifdef AT_CHANGE
67 #include "atcp.h"
68 #endif
69
70 /* interface vars */
71 char ifname[32];                /* Interface name */
72 int ifunit;                     /* Interface unit number */
73
74 char *progname;                 /* Name of this program */
75 char hostname[MAXNAMELEN];      /* Our hostname */
76 static char pidfilename[MAXPATHLEN];    /* name of pid file */
77 static char default_devnam[MAXPATHLEN]; /* name of default device */
78 static pid_t pid;               /* Our pid */
79 static uid_t uid;               /* Our real user-id */
80 static int conn_running;        /* we have a [dis]connector running */
81
82 int ttyfd = -1;                 /* Serial port file descriptor */
83 mode_t tty_mode = -1;           /* Original access permissions to tty */
84 int baud_rate;                  /* Actual bits/second for serial device */
85 int hungup;                     /* terminal has been hung up */
86 int privileged;                 /* we're running as real uid root */
87 int need_holdoff;               /* need holdoff period before restarting */
88 int detached;                   /* have detached from terminal */
89
90 int phase;                      /* where the link is at */
91 int kill_link;
92 int open_ccp_flag;
93
94 char **script_env;              /* Env. variable values for scripts */
95 int s_env_nalloc;               /* # words avail at script_env */
96
97 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
98 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
99
100 static int n_children;          /* # child processes still running */
101
102 static int locked;              /* lock() has succeeded */
103
104 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
105
106 /* Prototypes for procedures local to this file. */
107
108 static void cleanup __P((void));
109 static void close_tty __P((void));
110 static void get_input __P((void));
111 static void calltimeout __P((void));
112 static struct timeval *timeleft __P((struct timeval *));
113 static void kill_my_pg __P((int));
114 static void hup __P((int));
115 static void term __P((int));
116 static void chld __P((int));
117 static void toggle_debug __P((int));
118 static void open_ccp __P((int));
119 static void bad_signal __P((int));
120 static void holdoff_end __P((void *));
121 static int device_script __P((char *, int, int));
122 static void reap_kids __P((void));
123 static void pr_log __P((void *, char *, ...));
124
125 extern  char    *ttyname __P((int));
126 extern  char    *getlogin __P((void));
127 int main __P((int, char *[]));
128
129 #ifdef ultrix
130 #undef  O_NONBLOCK
131 #define O_NONBLOCK      O_NDELAY
132 #endif
133
134 #ifdef ULTRIX
135 #define setlogmask(x)
136 #endif
137
138 /*
139  * PPP Data Link Layer "protocol" table.
140  * One entry per supported protocol.
141  * The last entry must be NULL.
142  */
143 struct protent *protocols[] = {
144     &lcp_protent,
145     &pap_protent,
146     &chap_protent,
147 #ifdef CBCP_SUPPORT
148     &cbcp_protent,
149 #endif
150     &ipcp_protent,
151     &ccp_protent,
152 #ifdef IPX_CHANGE
153     &ipxcp_protent,
154 #endif
155 #ifdef AT_CHANGE
156     &atcp_protent,
157 #endif
158     NULL
159 };
160
161 int
162 main(argc, argv)
163     int argc;
164     char *argv[];
165 {
166     int i, fdflags;
167     struct sigaction sa;
168     FILE *pidfile;
169     char *p;
170     struct passwd *pw;
171     struct timeval timo;
172     sigset_t mask;
173     struct protent *protp;
174     struct stat statbuf;
175     char numbuf[16];
176
177     phase = PHASE_INITIALIZE;
178     p = ttyname(0);
179     if (p)
180         strcpy(devnam, p);
181     strcpy(default_devnam, devnam);
182
183     script_env = NULL;
184
185     /* Initialize syslog facilities */
186 #ifdef ULTRIX
187     openlog("pppd", LOG_PID);
188 #else
189     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
190     setlogmask(LOG_UPTO(LOG_INFO));
191 #endif
192
193     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
194         option_error("Couldn't get hostname: %m");
195         die(1);
196     }
197     hostname[MAXNAMELEN-1] = 0;
198
199     uid = getuid();
200     privileged = uid == 0;
201     sprintf(numbuf, "%d", uid);
202     script_setenv("UID", numbuf);
203
204     /*
205      * Initialize to the standard option set, then parse, in order,
206      * the system options file, the user's options file,
207      * the tty's options file, and the command line arguments.
208      */
209     for (i = 0; (protp = protocols[i]) != NULL; ++i)
210         (*protp->init)(0);
211
212     progname = *argv;
213
214     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
215         || !options_from_user())
216         exit(1);
217     scan_args(argc-1, argv+1);  /* look for tty name on command line */
218     if (!options_for_tty()
219         || !parse_args(argc-1, argv+1))
220         exit(1);
221
222     /*
223      * Check that we are running as root.
224      */
225     if (geteuid() != 0) {
226         option_error("must be root to run %s, since it is not setuid-root",
227                      argv[0]);
228         die(1);
229     }
230
231     if (!ppp_available()) {
232         option_error(no_ppp_msg);
233         exit(1);
234     }
235
236     /*
237      * Check that the options given are valid and consistent.
238      */
239     sys_check_options();
240     auth_check_options();
241     for (i = 0; (protp = protocols[i]) != NULL; ++i)
242         if (protp->check_options != NULL)
243             (*protp->check_options)();
244     if (demand && connector == 0) {
245         option_error("connect script required for demand-dialling\n");
246         exit(1);
247     }
248
249     script_setenv("DEVICE", devnam);
250     sprintf(numbuf, "%d", baud_rate);
251     script_setenv("SPEED", numbuf);
252
253     /*
254      * If the user has specified the default device name explicitly,
255      * pretend they hadn't.
256      */
257     if (!default_device && strcmp(devnam, default_devnam) == 0)
258         default_device = 1;
259     if (default_device)
260         nodetach = 1;
261
262     /*
263      * Initialize system-dependent stuff and magic number package.
264      */
265     sys_init();
266     magic_init();
267     if (debug)
268         setlogmask(LOG_UPTO(LOG_DEBUG));
269
270     /*
271      * Detach ourselves from the terminal, if required,
272      * and identify who is running us.
273      */
274     if (nodetach == 0)
275         detach();
276     pid = getpid();
277     p = getlogin();
278     if (p == NULL) {
279         pw = getpwuid(uid);
280         if (pw != NULL && pw->pw_name != NULL)
281             p = pw->pw_name;
282         else
283             p = "(unknown)";
284     }
285     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
286            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
287   
288     /*
289      * Compute mask of all interesting signals and install signal handlers
290      * for each.  Only one signal handler may be active at a time.  Therefore,
291      * all other signals should be masked when any handler is executing.
292      */
293     sigemptyset(&mask);
294     sigaddset(&mask, SIGHUP);
295     sigaddset(&mask, SIGINT);
296     sigaddset(&mask, SIGTERM);
297     sigaddset(&mask, SIGCHLD);
298
299 #define SIGNAL(s, handler)      { \
300         sa.sa_handler = handler; \
301         if (sigaction(s, &sa, NULL) < 0) { \
302             syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
303             die(1); \
304         } \
305     }
306
307     sa.sa_mask = mask;
308     sa.sa_flags = 0;
309     SIGNAL(SIGHUP, hup);                /* Hangup */
310     SIGNAL(SIGINT, term);               /* Interrupt */
311     SIGNAL(SIGTERM, term);              /* Terminate */
312     SIGNAL(SIGCHLD, chld);
313
314     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
315     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
316
317     /*
318      * Install a handler for other signals which would otherwise
319      * cause pppd to exit without cleaning up.
320      */
321     SIGNAL(SIGABRT, bad_signal);
322     SIGNAL(SIGALRM, bad_signal);
323     SIGNAL(SIGFPE, bad_signal);
324     SIGNAL(SIGILL, bad_signal);
325     SIGNAL(SIGPIPE, bad_signal);
326     SIGNAL(SIGQUIT, bad_signal);
327     SIGNAL(SIGSEGV, bad_signal);
328 #ifdef SIGBUS
329     SIGNAL(SIGBUS, bad_signal);
330 #endif
331 #ifdef SIGEMT
332     SIGNAL(SIGEMT, bad_signal);
333 #endif
334 #ifdef SIGPOLL
335     SIGNAL(SIGPOLL, bad_signal);
336 #endif
337 #ifdef SIGPROF
338     SIGNAL(SIGPROF, bad_signal);
339 #endif
340 #ifdef SIGSYS
341     SIGNAL(SIGSYS, bad_signal);
342 #endif
343 #ifdef SIGTRAP
344     SIGNAL(SIGTRAP, bad_signal);
345 #endif
346 #ifdef SIGVTALRM
347     SIGNAL(SIGVTALRM, bad_signal);
348 #endif
349 #ifdef SIGXCPU
350     SIGNAL(SIGXCPU, bad_signal);
351 #endif
352 #ifdef SIGXFSZ
353     SIGNAL(SIGXFSZ, bad_signal);
354 #endif
355
356     /*
357      * Apparently we can get a SIGPIPE when we call syslog, if
358      * syslogd has died and been restarted.  Ignoring it seems
359      * be sufficient.
360      */
361     signal(SIGPIPE, SIG_IGN);
362
363     /*
364      * If we're doing dial-on-demand, set up the interface now.
365      */
366     if (demand) {
367         /*
368          * Open the loopback channel and set it up to be the ppp interface.
369          */
370         open_ppp_loopback();
371
372         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
373         (void) sprintf(ifname, "ppp%d", ifunit);
374         script_setenv("IFNAME", ifname);
375
376         /* write pid to file */
377         (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
378         if ((pidfile = fopen(pidfilename, "w")) != NULL) {
379             fprintf(pidfile, "%d\n", pid);
380             (void) fclose(pidfile);
381         } else {
382             syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
383             pidfilename[0] = 0;
384         }
385
386         /*
387          * Configure the interface and mark it up, etc.
388          */
389         demand_conf();
390     }
391
392     for (;;) {
393
394         need_holdoff = 1;
395
396         if (demand) {
397             /*
398              * Don't do anything until we see some activity.
399              */
400             phase = PHASE_DORMANT;
401             kill_link = 0;
402             demand_unblock();
403             for (;;) {
404                 wait_loop_output(timeleft(&timo));
405                 calltimeout();
406                 if (kill_link) {
407                     if (!persist)
408                         die(0);
409                     kill_link = 0;
410                 }
411                 if (get_loop_output())
412                     break;
413                 reap_kids();
414             }
415
416             /*
417              * Now we want to bring up the link.
418              */
419             demand_block();
420             syslog(LOG_INFO, "Starting link");
421         }
422
423         /*
424          * Lock the device if we've been asked to.
425          */
426         if (lockflag && !default_device) {
427             if (lock(devnam) < 0)
428                 goto fail;
429             locked = 1;
430         }
431
432         /*
433          * Open the serial device and set it up to be the ppp interface.
434          * First we open it in non-blocking mode so we can set the
435          * various termios flags appropriately.  If we aren't dialling
436          * out and we want to use the modem lines, we reopen it later
437          * in order to wait for the carrier detect signal from the modem.
438          */
439         while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
440             if (errno != EINTR)
441                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
442             if (!persist || errno != EINTR)
443                 goto fail;
444         }
445         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
446             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
447             syslog(LOG_WARNING,
448                    "Couldn't reset non-blocking mode on device: %m");
449
450         hungup = 0;
451         kill_link = 0;
452
453         /*
454          * Do the equivalent of `mesg n' to stop broadcast messages.
455          */
456         if (fstat(ttyfd, &statbuf) < 0
457             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
458             syslog(LOG_WARNING,
459                    "Couldn't restrict write permissions to %s: %m", devnam);
460         } else
461             tty_mode = statbuf.st_mode;
462
463         /* run connection script */
464         if (connector && connector[0]) {
465             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
466
467             /*
468              * Set line speed, flow control, etc.
469              * On most systems we set CLOCAL for now so that we can talk
470              * to the modem before carrier comes up.  But this has the
471              * side effect that we might miss it if CD drops before we
472              * get to clear CLOCAL below.  On systems where we can talk
473              * successfully to the modem with CLOCAL clear and CD down,
474              * we can clear CLOCAL at this point.
475              */
476             set_up_tty(ttyfd, 1);
477
478             /* drop dtr to hang up in case modem is off hook */
479             if (!default_device && modem) {
480                 setdtr(ttyfd, FALSE);
481                 sleep(1);
482                 setdtr(ttyfd, TRUE);
483             }
484
485             if (device_script(connector, ttyfd, ttyfd) < 0) {
486                 syslog(LOG_ERR, "Connect script failed");
487                 setdtr(ttyfd, FALSE);
488                 goto fail;
489             }
490
491
492             syslog(LOG_INFO, "Serial connection established.");
493             sleep(1);           /* give it time to set up its terminal */
494         }
495
496         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
497         set_up_tty(ttyfd, 0);
498
499         /* reopen tty if necessary to wait for carrier */
500         if (connector == NULL && modem) {
501             while ((i = open(devnam, O_RDWR)) < 0) {
502                 if (errno != EINTR)
503                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
504                 if (!persist || errno != EINTR || hungup || kill_link)
505                     goto fail;
506             }
507             close(i);
508         }
509
510         /* run welcome script, if any */
511         if (welcomer && welcomer[0]) {
512             if (device_script(welcomer, ttyfd, ttyfd) < 0)
513                 syslog(LOG_WARNING, "Welcome script failed");
514         }
515
516         /* set up the serial device as a ppp interface */
517         establish_ppp(ttyfd);
518
519         if (!demand) {
520             
521             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
522             (void) sprintf(ifname, "ppp%d", ifunit);
523             script_setenv("IFNAME", ifname);
524
525             /* write pid to file */
526             (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
527             if ((pidfile = fopen(pidfilename, "w")) != NULL) {
528                 fprintf(pidfile, "%d\n", pid);
529                 (void) fclose(pidfile);
530             } else {
531                 syslog(LOG_ERR, "Failed to create pid file %s: %m",
532                        pidfilename);
533                 pidfilename[0] = 0;
534             }
535         }
536
537         /*
538          * Start opening the connection and wait for
539          * incoming events (reply, timeout, etc.).
540          */
541         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
542         lcp_lowerup(0);
543         lcp_open(0);            /* Start protocol */
544         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
545             wait_input(timeleft(&timo));
546             calltimeout();
547             get_input();
548             if (kill_link) {
549                 lcp_close(0, "User request");
550                 kill_link = 0;
551             }
552             if (open_ccp_flag) {
553                 if (phase == PHASE_NETWORK) {
554                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
555                     (*ccp_protent.open)(0);
556                 }
557                 open_ccp_flag = 0;
558             }
559             reap_kids();        /* Don't leave dead kids lying around */
560         }
561
562         /*
563          * If we may want to bring the link up again, transfer
564          * the ppp unit back to the loopback.  Set the
565          * real serial device back to its normal mode of operation.
566          */
567         clean_check();
568         if (demand)
569             restore_loop();
570         disestablish_ppp(ttyfd);
571
572         /*
573          * Run disconnector script, if requested.
574          * XXX we may not be able to do this if the line has hung up!
575          */
576         if (disconnector && !hungup) {
577             set_up_tty(ttyfd, 1);
578             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
579                 syslog(LOG_WARNING, "disconnect script failed");
580             } else {
581                 syslog(LOG_INFO, "Serial link disconnected.");
582             }
583         }
584
585     fail:
586         if (ttyfd >= 0)
587             close_tty();
588         if (locked) {
589             unlock();
590             locked = 0;
591         }
592
593         if (!demand) {
594             if (pidfilename[0] != 0
595                 && unlink(pidfilename) < 0 && errno != ENOENT) 
596                 syslog(LOG_WARNING, "unable to delete pid file: %m");
597             pidfilename[0] = 0;
598         }
599
600         if (!persist)
601             die(1);
602
603         if (demand)
604             demand_discard();
605         if (holdoff > 0 && need_holdoff) {
606             phase = PHASE_HOLDOFF;
607             TIMEOUT(holdoff_end, NULL, holdoff);
608             do {
609                 wait_time(timeleft(&timo));
610                 calltimeout();
611                 if (kill_link) {
612                     if (!persist)
613                         die(0);
614                     kill_link = 0;
615                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
616                 }
617                 reap_kids();
618             } while (phase == PHASE_HOLDOFF);
619         }
620     }
621
622     die(0);
623     return 0;
624 }
625
626 /*
627  * detach - detach us from the controlling terminal.
628  */
629 void
630 detach()
631 {
632     if (detached)
633         return;
634     if (daemon(0, 0) < 0) {
635         perror("Couldn't detach from controlling terminal");
636         die(1);
637     }
638     detached = 1;
639 }
640
641 /*
642  * holdoff_end - called via a timeout when the holdoff period ends.
643  */
644 static void
645 holdoff_end(arg)
646     void *arg;
647 {
648     phase = PHASE_DORMANT;
649 }
650
651 /*
652  * get_input - called when incoming data is available.
653  */
654 static void
655 get_input()
656 {
657     int len, i;
658     u_char *p;
659     u_short protocol;
660     struct protent *protp;
661
662     p = inpacket_buf;   /* point to beginning of packet buffer */
663
664     len = read_packet(inpacket_buf);
665     if (len < 0)
666         return;
667
668     if (len == 0) {
669         syslog(LOG_NOTICE, "Modem hangup");
670         hungup = 1;
671         lcp_lowerdown(0);       /* serial link is no longer available */
672         link_terminated(0);
673         return;
674     }
675
676     if (debug /*&& (debugflags & DBG_INPACKET)*/)
677         log_packet(p, len, "rcvd ", LOG_DEBUG);
678
679     if (len < PPP_HDRLEN) {
680         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
681         return;
682     }
683
684     p += 2;                             /* Skip address and control */
685     GETSHORT(protocol, p);
686     len -= PPP_HDRLEN;
687
688     /*
689      * Toss all non-LCP packets unless LCP is OPEN.
690      */
691     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
692         MAINDEBUG((LOG_INFO,
693                    "get_input: Received non-LCP packet when LCP not open."));
694         return;
695     }
696
697     /*
698      * Until we get past the authentication phase, toss all packets
699      * except LCP, LQR and authentication packets.
700      */
701     if (phase <= PHASE_AUTHENTICATE
702         && !(protocol == PPP_LCP || protocol == PPP_LQR
703              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
704         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
705                    protocol, phase));
706         return;
707     }
708
709     /*
710      * Upcall the proper protocol input routine.
711      */
712     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
713         if (protp->protocol == protocol && protp->enabled_flag) {
714             (*protp->input)(0, p, len);
715             return;
716         }
717         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
718             && protp->datainput != NULL) {
719             (*protp->datainput)(0, p, len);
720             return;
721         }
722     }
723
724     if (debug)
725         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
726     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
727 }
728
729
730 /*
731  * quit - Clean up state and exit (with an error indication).
732  */
733 void 
734 quit()
735 {
736     die(1);
737 }
738
739 /*
740  * die - like quit, except we can specify an exit status.
741  */
742 void
743 die(status)
744     int status;
745 {
746     cleanup();
747     syslog(LOG_INFO, "Exit.");
748     exit(status);
749 }
750
751 /*
752  * cleanup - restore anything which needs to be restored before we exit
753  */
754 /* ARGSUSED */
755 static void
756 cleanup()
757 {
758     sys_cleanup();
759
760     if (ttyfd >= 0)
761         close_tty();
762
763     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
764         syslog(LOG_WARNING, "unable to delete pid file: %m");
765     pidfilename[0] = 0;
766
767     if (locked)
768         unlock();
769 }
770
771 /*
772  * close_tty - restore the terminal device and close it.
773  */
774 static void
775 close_tty()
776 {
777     disestablish_ppp(ttyfd);
778
779     /* drop dtr to hang up */
780     if (modem) {
781         setdtr(ttyfd, FALSE);
782         /*
783          * This sleep is in case the serial port has CLOCAL set by default,
784          * and consequently will reassert DTR when we close the device.
785          */
786         sleep(1);
787     }
788
789     restore_tty(ttyfd);
790
791     if (tty_mode != (mode_t) -1)
792         chmod(devnam, tty_mode);
793
794     close(ttyfd);
795     ttyfd = -1;
796 }
797
798
799 struct  callout {
800     struct timeval      c_time;         /* time at which to call routine */
801     void                *c_arg;         /* argument to routine */
802     void                (*c_func) __P((void *)); /* routine */
803     struct              callout *c_next;
804 };
805
806 static struct callout *callout = NULL;  /* Callout list */
807 static struct timeval timenow;          /* Current time */
808
809 /*
810  * timeout - Schedule a timeout.
811  *
812  * Note that this timeout takes the number of seconds, NOT hz (as in
813  * the kernel).
814  */
815 void
816 timeout(func, arg, time)
817     void (*func) __P((void *));
818     void *arg;
819     int time;
820 {
821     struct callout *newp, *p, **pp;
822   
823     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
824                (long) func, (long) arg, time));
825   
826     /*
827      * Allocate timeout.
828      */
829     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
830         syslog(LOG_ERR, "Out of memory in timeout()!");
831         die(1);
832     }
833     newp->c_arg = arg;
834     newp->c_func = func;
835     gettimeofday(&timenow, NULL);
836     newp->c_time.tv_sec = timenow.tv_sec + time;
837     newp->c_time.tv_usec = timenow.tv_usec;
838   
839     /*
840      * Find correct place and link it in.
841      */
842     for (pp = &callout; (p = *pp); pp = &p->c_next)
843         if (newp->c_time.tv_sec < p->c_time.tv_sec
844             || (newp->c_time.tv_sec == p->c_time.tv_sec
845                 && newp->c_time.tv_usec < p->c_time.tv_sec))
846             break;
847     newp->c_next = p;
848     *pp = newp;
849 }
850
851
852 /*
853  * untimeout - Unschedule a timeout.
854  */
855 void
856 untimeout(func, arg)
857     void (*func) __P((void *));
858     void *arg;
859 {
860     struct callout **copp, *freep;
861   
862     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
863   
864     /*
865      * Find first matching timeout and remove it from the list.
866      */
867     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
868         if (freep->c_func == func && freep->c_arg == arg) {
869             *copp = freep->c_next;
870             (void) free((char *) freep);
871             break;
872         }
873 }
874
875
876 /*
877  * calltimeout - Call any timeout routines which are now due.
878  */
879 static void
880 calltimeout()
881 {
882     struct callout *p;
883
884     while (callout != NULL) {
885         p = callout;
886
887         if (gettimeofday(&timenow, NULL) < 0) {
888             syslog(LOG_ERR, "Failed to get time of day: %m");
889             die(1);
890         }
891         if (!(p->c_time.tv_sec < timenow.tv_sec
892               || (p->c_time.tv_sec == timenow.tv_sec
893                   && p->c_time.tv_usec <= timenow.tv_usec)))
894             break;              /* no, it's not time yet */
895
896         callout = p->c_next;
897         (*p->c_func)(p->c_arg);
898
899         free((char *) p);
900     }
901 }
902
903
904 /*
905  * timeleft - return the length of time until the next timeout is due.
906  */
907 static struct timeval *
908 timeleft(tvp)
909     struct timeval *tvp;
910 {
911     if (callout == NULL)
912         return NULL;
913
914     gettimeofday(&timenow, NULL);
915     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
916     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
917     if (tvp->tv_usec < 0) {
918         tvp->tv_usec += 1000000;
919         tvp->tv_sec -= 1;
920     }
921     if (tvp->tv_sec < 0)
922         tvp->tv_sec = tvp->tv_usec = 0;
923
924     return tvp;
925 }
926
927
928 /*
929  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
930  */
931 static void
932 kill_my_pg(sig)
933     int sig;
934 {
935     struct sigaction act, oldact;
936
937     act.sa_handler = SIG_IGN;
938     act.sa_flags = 0;
939     kill(0, sig);
940     sigaction(sig, &act, &oldact);
941     sigaction(sig, &oldact, NULL);
942 }
943
944
945 /*
946  * hup - Catch SIGHUP signal.
947  *
948  * Indicates that the physical layer has been disconnected.
949  * We don't rely on this indication; if the user has sent this
950  * signal, we just take the link down.
951  */
952 static void
953 hup(sig)
954     int sig;
955 {
956     syslog(LOG_INFO, "Hangup (SIGHUP)");
957     kill_link = 1;
958     if (conn_running)
959         /* Send the signal to the [dis]connector process(es) also */
960         kill_my_pg(sig);
961 }
962
963
964 /*
965  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
966  *
967  * Indicates that we should initiate a graceful disconnect and exit.
968  */
969 /*ARGSUSED*/
970 static void
971 term(sig)
972     int sig;
973 {
974     syslog(LOG_INFO, "Terminating on signal %d.", sig);
975     persist = 0;                /* don't try to restart */
976     kill_link = 1;
977     if (conn_running)
978         /* Send the signal to the [dis]connector process(es) also */
979         kill_my_pg(sig);
980 }
981
982
983 /*
984  * chld - Catch SIGCHLD signal.
985  * Calls reap_kids to get status for any dead kids.
986  */
987 static void
988 chld(sig)
989     int sig;
990 {
991     reap_kids();
992 }
993
994
995 /*
996  * toggle_debug - Catch SIGUSR1 signal.
997  *
998  * Toggle debug flag.
999  */
1000 /*ARGSUSED*/
1001 static void
1002 toggle_debug(sig)
1003     int sig;
1004 {
1005     debug = !debug;
1006     if (debug) {
1007         setlogmask(LOG_UPTO(LOG_DEBUG));
1008     } else {
1009         setlogmask(LOG_UPTO(LOG_WARNING));
1010     }
1011 }
1012
1013
1014 /*
1015  * open_ccp - Catch SIGUSR2 signal.
1016  *
1017  * Try to (re)negotiate compression.
1018  */
1019 /*ARGSUSED*/
1020 static void
1021 open_ccp(sig)
1022     int sig;
1023 {
1024     open_ccp_flag = 1;
1025 }
1026
1027
1028 /*
1029  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1030  */
1031 static void
1032 bad_signal(sig)
1033     int sig;
1034 {
1035     syslog(LOG_ERR, "Fatal signal %d", sig);
1036     if (conn_running)
1037         kill_my_pg(SIGTERM);
1038     die(1);
1039 }
1040
1041
1042 /*
1043  * device_script - run a program to connect or disconnect the
1044  * serial device.
1045  */
1046 static int
1047 device_script(program, in, out)
1048     char *program;
1049     int in, out;
1050 {
1051     int pid;
1052     int status;
1053     int errfd;
1054
1055     conn_running = 1;
1056     pid = fork();
1057
1058     if (pid < 0) {
1059         conn_running = 0;
1060         syslog(LOG_ERR, "Failed to create child process: %m");
1061         die(1);
1062     }
1063
1064     if (pid == 0) {
1065         sys_close();
1066         closelog();
1067         if (in == out) {
1068             if (in != 0) {
1069                 dup2(in, 0);
1070                 close(in);
1071             }
1072             dup2(0, 1);
1073         } else {
1074             if (out == 0)
1075                 out = dup(out);
1076             if (in != 0) {
1077                 dup2(in, 0);
1078                 close(in);
1079             }
1080             if (out != 1) {
1081                 dup2(out, 1);
1082                 close(out);
1083             }
1084         }
1085         if (nodetach == 0) {
1086             close(2);
1087             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1088             if (errfd >= 0 && errfd != 2) {
1089                 dup2(errfd, 2);
1090                 close(errfd);
1091             }
1092         }
1093         setuid(getuid());
1094         setgid(getgid());
1095         execl("/bin/sh", "sh", "-c", program, (char *)0);
1096         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1097         _exit(99);
1098         /* NOTREACHED */
1099     }
1100
1101     while (waitpid(pid, &status, 0) < 0) {
1102         if (errno == EINTR)
1103             continue;
1104         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1105         die(1);
1106     }
1107     conn_running = 0;
1108
1109     return (status == 0 ? 0 : -1);
1110 }
1111
1112
1113 /*
1114  * run-program - execute a program with given arguments,
1115  * but don't wait for it.
1116  * If the program can't be executed, logs an error unless
1117  * must_exist is 0 and the program file doesn't exist.
1118  */
1119 int
1120 run_program(prog, args, must_exist)
1121     char *prog;
1122     char **args;
1123     int must_exist;
1124 {
1125     int pid;
1126
1127     pid = fork();
1128     if (pid == -1) {
1129         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1130         return -1;
1131     }
1132     if (pid == 0) {
1133         int new_fd;
1134
1135         /* Leave the current location */
1136         (void) setsid();    /* No controlling tty. */
1137         (void) umask (S_IRWXG|S_IRWXO);
1138         (void) chdir ("/"); /* no current directory. */
1139         setuid(geteuid());
1140         setgid(getegid());
1141
1142         /* Ensure that nothing of our device environment is inherited. */
1143         sys_close();
1144         closelog();
1145         close (0);
1146         close (1);
1147         close (2);
1148         close (ttyfd);  /* tty interface to the ppp device */
1149
1150         /* Don't pass handles to the PPP device, even by accident. */
1151         new_fd = open (_PATH_DEVNULL, O_RDWR);
1152         if (new_fd >= 0) {
1153             if (new_fd != 0) {
1154                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1155                 close (new_fd);
1156             }
1157             dup2 (0, 1); /* stdout -> /dev/null */
1158             dup2 (0, 2); /* stderr -> /dev/null */
1159         }
1160
1161 #ifdef BSD
1162         /* Force the priority back to zero if pppd is running higher. */
1163         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1164             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1165 #endif
1166
1167         /* SysV recommends a second fork at this point. */
1168
1169         /* run the program; give it a null environment */
1170         execve(prog, args, script_env);
1171         if (must_exist || errno != ENOENT)
1172             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1173         _exit(-1);
1174     }
1175     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1176     ++n_children;
1177     return 0;
1178 }
1179
1180
1181 /*
1182  * reap_kids - get status from any dead child processes,
1183  * and log a message for abnormal terminations.
1184  */
1185 static void
1186 reap_kids()
1187 {
1188     int pid, status;
1189
1190     if (n_children == 0)
1191         return;
1192     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1193         if (errno != ECHILD)
1194             syslog(LOG_ERR, "Error waiting for child process: %m");
1195         return;
1196     }
1197     if (pid > 0) {
1198         --n_children;
1199         if (WIFSIGNALED(status)) {
1200             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1201                    pid, WTERMSIG(status));
1202         }
1203     }
1204 }
1205
1206
1207 /*
1208  * log_packet - format a packet and log it.
1209  */
1210
1211 char line[256];                 /* line to be logged accumulated here */
1212 char *linep;
1213
1214 void
1215 log_packet(p, len, prefix, level)
1216     u_char *p;
1217     int len;
1218     char *prefix;
1219     int level;
1220 {
1221     strcpy(line, prefix);
1222     linep = line + strlen(line);
1223     format_packet(p, len, pr_log, NULL);
1224     if (linep != line)
1225         syslog(level, "%s", line);
1226 }
1227
1228 /*
1229  * format_packet - make a readable representation of a packet,
1230  * calling `printer(arg, format, ...)' to output it.
1231  */
1232 void
1233 format_packet(p, len, printer, arg)
1234     u_char *p;
1235     int len;
1236     void (*printer) __P((void *, char *, ...));
1237     void *arg;
1238 {
1239     int i, n;
1240     u_short proto;
1241     u_char x;
1242     struct protent *protp;
1243
1244     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1245         p += 2;
1246         GETSHORT(proto, p);
1247         len -= PPP_HDRLEN;
1248         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1249             if (proto == protp->protocol)
1250                 break;
1251         if (protp != NULL) {
1252             printer(arg, "[%s", protp->name);
1253             n = (*protp->printpkt)(p, len, printer, arg);
1254             printer(arg, "]");
1255             p += n;
1256             len -= n;
1257         } else {
1258             printer(arg, "[proto=0x%x]", proto);
1259         }
1260     }
1261
1262     for (; len > 0; --len) {
1263         GETCHAR(x, p);
1264         printer(arg, " %.2x", x);
1265     }
1266 }
1267
1268 static void
1269 pr_log __V((void *arg, char *fmt, ...))
1270 {
1271     int n;
1272     va_list pvar;
1273     char buf[256];
1274
1275 #if __STDC__
1276     va_start(pvar, fmt);
1277 #else
1278     void *arg;
1279     char *fmt;
1280     va_start(pvar);
1281     arg = va_arg(pvar, void *);
1282     fmt = va_arg(pvar, char *);
1283 #endif
1284
1285     vsprintf(buf, fmt, pvar);
1286     va_end(pvar);
1287
1288     n = strlen(buf);
1289     if (linep + n + 1 > line + sizeof(line)) {
1290         syslog(LOG_DEBUG, "%s", line);
1291         linep = line;
1292     }
1293     strcpy(linep, buf);
1294     linep += n;
1295 }
1296
1297 /*
1298  * print_string - print a readable representation of a string using
1299  * printer.
1300  */
1301 void
1302 print_string(p, len, printer, arg)
1303     char *p;
1304     int len;
1305     void (*printer) __P((void *, char *, ...));
1306     void *arg;
1307 {
1308     int c;
1309
1310     printer(arg, "\"");
1311     for (; len > 0; --len) {
1312         c = *p++;
1313         if (' ' <= c && c <= '~') {
1314             if (c == '\\' || c == '"')
1315                 printer(arg, "\\");
1316             printer(arg, "%c", c);
1317         } else {
1318             switch (c) {
1319             case '\n':
1320                 printer(arg, "\\n");
1321                 break;
1322             case '\r':
1323                 printer(arg, "\\r");
1324                 break;
1325             case '\t':
1326                 printer(arg, "\\t");
1327                 break;
1328             default:
1329                 printer(arg, "\\%.3o", c);
1330             }
1331         }
1332     }
1333     printer(arg, "\"");
1334 }
1335
1336 /*
1337  * novm - log an error message saying we ran out of memory, and die.
1338  */
1339 void
1340 novm(msg)
1341     char *msg;
1342 {
1343     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1344     die(1);
1345 }
1346
1347 /*
1348  * fmtmsg - format a message into a buffer.  Like sprintf except we
1349  * also specify the length of the output buffer, and we handle
1350  * %r (recursive format), %m (error message) and %I (IP address) formats.
1351  * Doesn't do floating-point formats.
1352  * Returns the number of chars put into buf.
1353  */
1354 int
1355 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1356 {
1357     va_list args;
1358     int n;
1359
1360 #if __STDC__
1361     va_start(args, fmt);
1362 #else
1363     char *buf;
1364     int buflen;
1365     char *fmt;
1366     va_start(args);
1367     buf = va_arg(args, char *);
1368     buflen = va_arg(args, int);
1369     fmt = va_arg(args, char *);
1370 #endif
1371     n = vfmtmsg(buf, buflen, fmt, args);
1372     va_end(args);
1373     return n;
1374 }
1375
1376 /*
1377  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1378  */
1379 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1380
1381 int
1382 vfmtmsg(buf, buflen, fmt, args)
1383     char *buf;
1384     int buflen;
1385     char *fmt;
1386     va_list args;
1387 {
1388     int c, i, n;
1389     int width, prec, fillch;
1390     int base, len, neg, quoted;
1391     unsigned long val = 0;
1392     char *str, *f, *buf0;
1393     unsigned char *p;
1394     char num[32];
1395     time_t t;
1396     static char hexchars[] = "0123456789abcdef";
1397
1398     buf0 = buf;
1399     --buflen;
1400     while (buflen > 0) {
1401         for (f = fmt; *f != '%' && *f != 0; ++f)
1402             ;
1403         if (f > fmt) {
1404             len = f - fmt;
1405             if (len > buflen)
1406                 len = buflen;
1407             memcpy(buf, fmt, len);
1408             buf += len;
1409             buflen -= len;
1410             fmt = f;
1411         }
1412         if (*fmt == 0)
1413             break;
1414         c = *++fmt;
1415         width = prec = 0;
1416         fillch = ' ';
1417         if (c == '0') {
1418             fillch = '0';
1419             c = *++fmt;
1420         }
1421         if (c == '*') {
1422             width = va_arg(args, int);
1423             c = *++fmt;
1424         } else {
1425             while (isdigit(c)) {
1426                 width = width * 10 + c - '0';
1427                 c = *++fmt;
1428             }
1429         }
1430         if (c == '.') {
1431             c = *++fmt;
1432             if (c == '*') {
1433                 prec = va_arg(args, int);
1434                 c = *++fmt;
1435             } else {
1436                 while (isdigit(c)) {
1437                     prec = prec * 10 + c - '0';
1438                     c = *++fmt;
1439                 }
1440             }
1441         }
1442         str = 0;
1443         base = 0;
1444         neg = 0;
1445         ++fmt;
1446         switch (c) {
1447         case 'd':
1448             i = va_arg(args, int);
1449             if (i < 0) {
1450                 neg = 1;
1451                 val = -i;
1452             } else
1453                 val = i;
1454             base = 10;
1455             break;
1456         case 'o':
1457             val = va_arg(args, unsigned int);
1458             base = 8;
1459             break;
1460         case 'x':
1461             val = va_arg(args, unsigned int);
1462             base = 16;
1463             break;
1464         case 'p':
1465             val = (unsigned long) va_arg(args, void *);
1466             base = 16;
1467             neg = 2;
1468             break;
1469         case 's':
1470             str = va_arg(args, char *);
1471             break;
1472         case 'c':
1473             num[0] = va_arg(args, int);
1474             num[1] = 0;
1475             str = num;
1476             break;
1477         case 'm':
1478             str = strerror(errno);
1479             break;
1480         case 'I':
1481             str = ip_ntoa(va_arg(args, u_int32_t));
1482             break;
1483         case 'r':
1484             f = va_arg(args, char *);
1485 #ifndef __powerpc__
1486             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1487 #else
1488             /* On the powerpc, a va_list is an array of 1 structure */
1489             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1490 #endif
1491             buf += n;
1492             buflen -= n;
1493             continue;
1494         case 't':
1495             time(&t);
1496             str = ctime(&t);
1497             str += 4;           /* chop off the day name */
1498             str[15] = 0;        /* chop off year and newline */
1499             break;
1500         case 'v':               /* "visible" string */
1501         case 'q':               /* quoted string */
1502             quoted = c == 'q';
1503             p = va_arg(args, unsigned char *);
1504             if (fillch == '0' && prec > 0) {
1505                 n = prec;
1506             } else {
1507                 n = strlen((char *)p);
1508                 if (prec > 0 && prec < n)
1509                     n = prec;
1510             }
1511             while (n > 0 && buflen > 0) {
1512                 c = *p++;
1513                 --n;
1514                 if (!quoted && c >= 0x80) {
1515                     OUTCHAR('M');
1516                     OUTCHAR('-');
1517                     c -= 0x80;
1518                 }
1519                 if (quoted && (c == '"' || c == '\\'))
1520                     OUTCHAR('\\');
1521                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1522                     if (quoted) {
1523                         OUTCHAR('\\');
1524                         switch (c) {
1525                         case '\t':      OUTCHAR('t');   break;
1526                         case '\n':      OUTCHAR('n');   break;
1527                         case '\b':      OUTCHAR('b');   break;
1528                         case '\f':      OUTCHAR('f');   break;
1529                         default:
1530                             OUTCHAR('x');
1531                             OUTCHAR(hexchars[c >> 4]);
1532                             OUTCHAR(hexchars[c & 0xf]);
1533                         }
1534                     } else {
1535                         if (c == '\t')
1536                             OUTCHAR(c);
1537                         else {
1538                             OUTCHAR('^');
1539                             OUTCHAR(c ^ 0x40);
1540                         }
1541                     }
1542                 } else
1543                     OUTCHAR(c);
1544             }
1545             continue;
1546         default:
1547             *buf++ = '%';
1548             if (c != '%')
1549                 --fmt;          /* so %z outputs %z etc. */
1550             --buflen;
1551             continue;
1552         }
1553         if (base != 0) {
1554             str = num + sizeof(num);
1555             *--str = 0;
1556             while (str > num + neg) {
1557                 *--str = hexchars[val % base];
1558                 val = val / base;
1559                 if (--prec <= 0 && val == 0)
1560                     break;
1561             }
1562             switch (neg) {
1563             case 1:
1564                 *--str = '-';
1565                 break;
1566             case 2:
1567                 *--str = 'x';
1568                 *--str = '0';
1569                 break;
1570             }
1571             len = num + sizeof(num) - 1 - str;
1572         } else {
1573             len = strlen(str);
1574             if (prec > 0 && len > prec)
1575                 len = prec;
1576         }
1577         if (width > 0) {
1578             if (width > buflen)
1579                 width = buflen;
1580             if ((n = width - len) > 0) {
1581                 buflen -= n;
1582                 for (; n > 0; --n)
1583                     *buf++ = fillch;
1584             }
1585         }
1586         if (len > buflen)
1587             len = buflen;
1588         memcpy(buf, str, len);
1589         buf += len;
1590         buflen -= len;
1591     }
1592     *buf = 0;
1593     return buf - buf0;
1594 }
1595
1596 /*
1597  * script_setenv - set an environment variable value to be used
1598  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1599  */
1600 void
1601 script_setenv(var, value)
1602     char *var, *value;
1603 {
1604     int vl = strlen(var);
1605     int i;
1606     char *p, *newstring;
1607
1608     newstring = (char *) malloc(vl + strlen(value) + 2);
1609     if (newstring == 0)
1610         return;
1611     strcpy(newstring, var);
1612     newstring[vl] = '=';
1613     strcpy(newstring+vl+1, value);
1614
1615     /* check if this variable is already set */
1616     if (script_env != 0) {
1617         for (i = 0; (p = script_env[i]) != 0; ++i) {
1618             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1619                 free(p);
1620                 script_env[i] = newstring;
1621                 return;
1622             }
1623         }
1624     } else {
1625         i = 0;
1626         script_env = (char **) malloc(16 * sizeof(char *));
1627         if (script_env == 0)
1628             return;
1629         s_env_nalloc = 16;
1630     }
1631
1632     /* reallocate script_env with more space if needed */
1633     if (i + 1 >= s_env_nalloc) {
1634         int new_n = i + 17;
1635         char **newenv = (char **) realloc((void *)script_env,
1636                                           new_n * sizeof(char *));
1637         if (newenv == 0)
1638             return;
1639         script_env = newenv;
1640         s_env_nalloc = new_n;
1641     }
1642
1643     script_env[i] = newstring;
1644     script_env[i+1] = 0;
1645 }
1646
1647 /*
1648  * script_unsetenv - remove a variable from the environment
1649  * for scripts.
1650  */
1651 void
1652 script_unsetenv(var)
1653     char *var;
1654 {
1655     int vl = strlen(var);
1656     int i;
1657     char *p;
1658
1659     if (script_env == 0)
1660         return;
1661     for (i = 0; (p = script_env[i]) != 0; ++i) {
1662         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1663             free(p);
1664             while ((script_env[i] = script_env[i+1]) != 0)
1665                 ++i;
1666             break;
1667         }
1668     }
1669 }