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