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