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