]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
define HAVE_CRYPT_H if we have a /usr/include/crypt.h
[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.47 1998/03/30 06:25:34 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     syslog(LOG_ERR, "Fatal signal %d", sig);
1041     if (conn_running)
1042         kill_my_pg(SIGTERM);
1043     die(1);
1044 }
1045
1046
1047 /*
1048  * device_script - run a program to connect or disconnect the
1049  * serial device.
1050  */
1051 static int
1052 device_script(program, in, out)
1053     char *program;
1054     int in, out;
1055 {
1056     int pid;
1057     int status;
1058     int errfd;
1059
1060     conn_running = 1;
1061     pid = fork();
1062
1063     if (pid < 0) {
1064         conn_running = 0;
1065         syslog(LOG_ERR, "Failed to create child process: %m");
1066         die(1);
1067     }
1068
1069     if (pid == 0) {
1070         sys_close();
1071         closelog();
1072         if (in == out) {
1073             if (in != 0) {
1074                 dup2(in, 0);
1075                 close(in);
1076             }
1077             dup2(0, 1);
1078         } else {
1079             if (out == 0)
1080                 out = dup(out);
1081             if (in != 0) {
1082                 dup2(in, 0);
1083                 close(in);
1084             }
1085             if (out != 1) {
1086                 dup2(out, 1);
1087                 close(out);
1088             }
1089         }
1090         if (nodetach == 0) {
1091             close(2);
1092             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1093             if (errfd >= 0 && errfd != 2) {
1094                 dup2(errfd, 2);
1095                 close(errfd);
1096             }
1097         }
1098         setuid(getuid());
1099         setgid(getgid());
1100         execl("/bin/sh", "sh", "-c", program, (char *)0);
1101         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1102         _exit(99);
1103         /* NOTREACHED */
1104     }
1105
1106     while (waitpid(pid, &status, 0) < 0) {
1107         if (errno == EINTR)
1108             continue;
1109         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1110         die(1);
1111     }
1112     conn_running = 0;
1113
1114     return (status == 0 ? 0 : -1);
1115 }
1116
1117
1118 /*
1119  * run-program - execute a program with given arguments,
1120  * but don't wait for it.
1121  * If the program can't be executed, logs an error unless
1122  * must_exist is 0 and the program file doesn't exist.
1123  */
1124 int
1125 run_program(prog, args, must_exist)
1126     char *prog;
1127     char **args;
1128     int must_exist;
1129 {
1130     int pid;
1131
1132     pid = fork();
1133     if (pid == -1) {
1134         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1135         return -1;
1136     }
1137     if (pid == 0) {
1138         int new_fd;
1139
1140         /* Leave the current location */
1141         (void) setsid();    /* No controlling tty. */
1142         (void) umask (S_IRWXG|S_IRWXO);
1143         (void) chdir ("/"); /* no current directory. */
1144         setuid(geteuid());
1145         setgid(getegid());
1146
1147         /* Ensure that nothing of our device environment is inherited. */
1148         sys_close();
1149         closelog();
1150         close (0);
1151         close (1);
1152         close (2);
1153         close (ttyfd);  /* tty interface to the ppp device */
1154
1155         /* Don't pass handles to the PPP device, even by accident. */
1156         new_fd = open (_PATH_DEVNULL, O_RDWR);
1157         if (new_fd >= 0) {
1158             if (new_fd != 0) {
1159                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1160                 close (new_fd);
1161             }
1162             dup2 (0, 1); /* stdout -> /dev/null */
1163             dup2 (0, 2); /* stderr -> /dev/null */
1164         }
1165
1166 #ifdef BSD
1167         /* Force the priority back to zero if pppd is running higher. */
1168         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1169             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1170 #endif
1171
1172         /* SysV recommends a second fork at this point. */
1173
1174         /* run the program; give it a null environment */
1175         execve(prog, args, script_env);
1176         if (must_exist || errno != ENOENT)
1177             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1178         _exit(-1);
1179     }
1180     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1181     ++n_children;
1182     return 0;
1183 }
1184
1185
1186 /*
1187  * reap_kids - get status from any dead child processes,
1188  * and log a message for abnormal terminations.
1189  */
1190 static void
1191 reap_kids()
1192 {
1193     int pid, status;
1194
1195     if (n_children == 0)
1196         return;
1197     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1198         if (errno != ECHILD)
1199             syslog(LOG_ERR, "Error waiting for child process: %m");
1200         return;
1201     }
1202     if (pid > 0) {
1203         --n_children;
1204         if (WIFSIGNALED(status)) {
1205             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1206                    pid, WTERMSIG(status));
1207         }
1208     }
1209 }
1210
1211
1212 /*
1213  * log_packet - format a packet and log it.
1214  */
1215
1216 char line[256];                 /* line to be logged accumulated here */
1217 char *linep;
1218
1219 void
1220 log_packet(p, len, prefix, level)
1221     u_char *p;
1222     int len;
1223     char *prefix;
1224     int level;
1225 {
1226     strcpy(line, prefix);
1227     linep = line + strlen(line);
1228     format_packet(p, len, pr_log, NULL);
1229     if (linep != line)
1230         syslog(level, "%s", line);
1231 }
1232
1233 /*
1234  * format_packet - make a readable representation of a packet,
1235  * calling `printer(arg, format, ...)' to output it.
1236  */
1237 void
1238 format_packet(p, len, printer, arg)
1239     u_char *p;
1240     int len;
1241     void (*printer) __P((void *, char *, ...));
1242     void *arg;
1243 {
1244     int i, n;
1245     u_short proto;
1246     u_char x;
1247     struct protent *protp;
1248
1249     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1250         p += 2;
1251         GETSHORT(proto, p);
1252         len -= PPP_HDRLEN;
1253         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1254             if (proto == protp->protocol)
1255                 break;
1256         if (protp != NULL) {
1257             printer(arg, "[%s", protp->name);
1258             n = (*protp->printpkt)(p, len, printer, arg);
1259             printer(arg, "]");
1260             p += n;
1261             len -= n;
1262         } else {
1263             printer(arg, "[proto=0x%x]", proto);
1264         }
1265     }
1266
1267     for (; len > 0; --len) {
1268         GETCHAR(x, p);
1269         printer(arg, " %.2x", x);
1270     }
1271 }
1272
1273 static void
1274 pr_log __V((void *arg, char *fmt, ...))
1275 {
1276     int n;
1277     va_list pvar;
1278     char buf[256];
1279
1280 #if __STDC__
1281     va_start(pvar, fmt);
1282 #else
1283     void *arg;
1284     char *fmt;
1285     va_start(pvar);
1286     arg = va_arg(pvar, void *);
1287     fmt = va_arg(pvar, char *);
1288 #endif
1289
1290     vsprintf(buf, fmt, pvar);
1291     va_end(pvar);
1292
1293     n = strlen(buf);
1294     if (linep + n + 1 > line + sizeof(line)) {
1295         syslog(LOG_DEBUG, "%s", line);
1296         linep = line;
1297     }
1298     strcpy(linep, buf);
1299     linep += n;
1300 }
1301
1302 /*
1303  * print_string - print a readable representation of a string using
1304  * printer.
1305  */
1306 void
1307 print_string(p, len, printer, arg)
1308     char *p;
1309     int len;
1310     void (*printer) __P((void *, char *, ...));
1311     void *arg;
1312 {
1313     int c;
1314
1315     printer(arg, "\"");
1316     for (; len > 0; --len) {
1317         c = *p++;
1318         if (' ' <= c && c <= '~') {
1319             if (c == '\\' || c == '"')
1320                 printer(arg, "\\");
1321             printer(arg, "%c", c);
1322         } else {
1323             switch (c) {
1324             case '\n':
1325                 printer(arg, "\\n");
1326                 break;
1327             case '\r':
1328                 printer(arg, "\\r");
1329                 break;
1330             case '\t':
1331                 printer(arg, "\\t");
1332                 break;
1333             default:
1334                 printer(arg, "\\%.3o", c);
1335             }
1336         }
1337     }
1338     printer(arg, "\"");
1339 }
1340
1341 /*
1342  * novm - log an error message saying we ran out of memory, and die.
1343  */
1344 void
1345 novm(msg)
1346     char *msg;
1347 {
1348     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1349     die(1);
1350 }
1351
1352 /*
1353  * fmtmsg - format a message into a buffer.  Like sprintf except we
1354  * also specify the length of the output buffer, and we handle
1355  * %r (recursive format), %m (error message) and %I (IP address) formats.
1356  * Doesn't do floating-point formats.
1357  * Returns the number of chars put into buf.
1358  */
1359 int
1360 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1361 {
1362     va_list args;
1363     int n;
1364
1365 #if __STDC__
1366     va_start(args, fmt);
1367 #else
1368     char *buf;
1369     int buflen;
1370     char *fmt;
1371     va_start(args);
1372     buf = va_arg(args, char *);
1373     buflen = va_arg(args, int);
1374     fmt = va_arg(args, char *);
1375 #endif
1376     n = vfmtmsg(buf, buflen, fmt, args);
1377     va_end(args);
1378     return n;
1379 }
1380
1381 /*
1382  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1383  */
1384 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1385
1386 int
1387 vfmtmsg(buf, buflen, fmt, args)
1388     char *buf;
1389     int buflen;
1390     char *fmt;
1391     va_list args;
1392 {
1393     int c, i, n;
1394     int width, prec, fillch;
1395     int base, len, neg, quoted;
1396     unsigned long val = 0;
1397     char *str, *f, *buf0;
1398     unsigned char *p;
1399     char num[32];
1400     time_t t;
1401     static char hexchars[] = "0123456789abcdef";
1402
1403     buf0 = buf;
1404     --buflen;
1405     while (buflen > 0) {
1406         for (f = fmt; *f != '%' && *f != 0; ++f)
1407             ;
1408         if (f > fmt) {
1409             len = f - fmt;
1410             if (len > buflen)
1411                 len = buflen;
1412             memcpy(buf, fmt, len);
1413             buf += len;
1414             buflen -= len;
1415             fmt = f;
1416         }
1417         if (*fmt == 0)
1418             break;
1419         c = *++fmt;
1420         width = prec = 0;
1421         fillch = ' ';
1422         if (c == '0') {
1423             fillch = '0';
1424             c = *++fmt;
1425         }
1426         if (c == '*') {
1427             width = va_arg(args, int);
1428             c = *++fmt;
1429         } else {
1430             while (isdigit(c)) {
1431                 width = width * 10 + c - '0';
1432                 c = *++fmt;
1433             }
1434         }
1435         if (c == '.') {
1436             c = *++fmt;
1437             if (c == '*') {
1438                 prec = va_arg(args, int);
1439                 c = *++fmt;
1440             } else {
1441                 while (isdigit(c)) {
1442                     prec = prec * 10 + c - '0';
1443                     c = *++fmt;
1444                 }
1445             }
1446         }
1447         str = 0;
1448         base = 0;
1449         neg = 0;
1450         ++fmt;
1451         switch (c) {
1452         case 'd':
1453             i = va_arg(args, int);
1454             if (i < 0) {
1455                 neg = 1;
1456                 val = -i;
1457             } else
1458                 val = i;
1459             base = 10;
1460             break;
1461         case 'o':
1462             val = va_arg(args, unsigned int);
1463             base = 8;
1464             break;
1465         case 'x':
1466             val = va_arg(args, unsigned int);
1467             base = 16;
1468             break;
1469         case 'p':
1470             val = (unsigned long) va_arg(args, void *);
1471             base = 16;
1472             neg = 2;
1473             break;
1474         case 's':
1475             str = va_arg(args, char *);
1476             break;
1477         case 'c':
1478             num[0] = va_arg(args, int);
1479             num[1] = 0;
1480             str = num;
1481             break;
1482         case 'm':
1483             str = strerror(errno);
1484             break;
1485         case 'I':
1486             str = ip_ntoa(va_arg(args, u_int32_t));
1487             break;
1488         case 'r':
1489             f = va_arg(args, char *);
1490 #ifndef __powerpc__
1491             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1492 #else
1493             /* On the powerpc, a va_list is an array of 1 structure */
1494             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1495 #endif
1496             buf += n;
1497             buflen -= n;
1498             continue;
1499         case 't':
1500             time(&t);
1501             str = ctime(&t);
1502             str += 4;           /* chop off the day name */
1503             str[15] = 0;        /* chop off year and newline */
1504             break;
1505         case 'v':               /* "visible" string */
1506         case 'q':               /* quoted string */
1507             quoted = c == 'q';
1508             p = va_arg(args, unsigned char *);
1509             if (fillch == '0' && prec > 0) {
1510                 n = prec;
1511             } else {
1512                 n = strlen((char *)p);
1513                 if (prec > 0 && prec < n)
1514                     n = prec;
1515             }
1516             while (n > 0 && buflen > 0) {
1517                 c = *p++;
1518                 --n;
1519                 if (!quoted && c >= 0x80) {
1520                     OUTCHAR('M');
1521                     OUTCHAR('-');
1522                     c -= 0x80;
1523                 }
1524                 if (quoted && (c == '"' || c == '\\'))
1525                     OUTCHAR('\\');
1526                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1527                     if (quoted) {
1528                         OUTCHAR('\\');
1529                         switch (c) {
1530                         case '\t':      OUTCHAR('t');   break;
1531                         case '\n':      OUTCHAR('n');   break;
1532                         case '\b':      OUTCHAR('b');   break;
1533                         case '\f':      OUTCHAR('f');   break;
1534                         default:
1535                             OUTCHAR('x');
1536                             OUTCHAR(hexchars[c >> 4]);
1537                             OUTCHAR(hexchars[c & 0xf]);
1538                         }
1539                     } else {
1540                         if (c == '\t')
1541                             OUTCHAR(c);
1542                         else {
1543                             OUTCHAR('^');
1544                             OUTCHAR(c ^ 0x40);
1545                         }
1546                     }
1547                 } else
1548                     OUTCHAR(c);
1549             }
1550             continue;
1551         default:
1552             *buf++ = '%';
1553             if (c != '%')
1554                 --fmt;          /* so %z outputs %z etc. */
1555             --buflen;
1556             continue;
1557         }
1558         if (base != 0) {
1559             str = num + sizeof(num);
1560             *--str = 0;
1561             while (str > num + neg) {
1562                 *--str = hexchars[val % base];
1563                 val = val / base;
1564                 if (--prec <= 0 && val == 0)
1565                     break;
1566             }
1567             switch (neg) {
1568             case 1:
1569                 *--str = '-';
1570                 break;
1571             case 2:
1572                 *--str = 'x';
1573                 *--str = '0';
1574                 break;
1575             }
1576             len = num + sizeof(num) - 1 - str;
1577         } else {
1578             len = strlen(str);
1579             if (prec > 0 && len > prec)
1580                 len = prec;
1581         }
1582         if (width > 0) {
1583             if (width > buflen)
1584                 width = buflen;
1585             if ((n = width - len) > 0) {
1586                 buflen -= n;
1587                 for (; n > 0; --n)
1588                     *buf++ = fillch;
1589             }
1590         }
1591         if (len > buflen)
1592             len = buflen;
1593         memcpy(buf, str, len);
1594         buf += len;
1595         buflen -= len;
1596     }
1597     *buf = 0;
1598     return buf - buf0;
1599 }
1600
1601 /*
1602  * script_setenv - set an environment variable value to be used
1603  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1604  */
1605 void
1606 script_setenv(var, value)
1607     char *var, *value;
1608 {
1609     int vl = strlen(var);
1610     int i;
1611     char *p, *newstring;
1612
1613     newstring = (char *) malloc(vl + strlen(value) + 2);
1614     if (newstring == 0)
1615         return;
1616     strcpy(newstring, var);
1617     newstring[vl] = '=';
1618     strcpy(newstring+vl+1, value);
1619
1620     /* check if this variable is already set */
1621     if (script_env != 0) {
1622         for (i = 0; (p = script_env[i]) != 0; ++i) {
1623             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1624                 free(p);
1625                 script_env[i] = newstring;
1626                 return;
1627             }
1628         }
1629     } else {
1630         i = 0;
1631         script_env = (char **) malloc(16 * sizeof(char *));
1632         if (script_env == 0)
1633             return;
1634         s_env_nalloc = 16;
1635     }
1636
1637     /* reallocate script_env with more space if needed */
1638     if (i + 1 >= s_env_nalloc) {
1639         int new_n = i + 17;
1640         char **newenv = (char **) realloc((void *)script_env,
1641                                           new_n * sizeof(char *));
1642         if (newenv == 0)
1643             return;
1644         script_env = newenv;
1645         s_env_nalloc = new_n;
1646     }
1647
1648     script_env[i] = newstring;
1649     script_env[i+1] = 0;
1650 }
1651
1652 /*
1653  * script_unsetenv - remove a variable from the environment
1654  * for scripts.
1655  */
1656 void
1657 script_unsetenv(var)
1658     char *var;
1659 {
1660     int vl = strlen(var);
1661     int i;
1662     char *p;
1663
1664     if (script_env == 0)
1665         return;
1666     for (i = 0; (p = script_env[i]) != 0; ++i) {
1667         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1668             free(p);
1669             while ((script_env[i] = script_env[i+1]) != 0)
1670                 ++i;
1671             break;
1672         }
1673     }
1674 }