var.c revision 97915
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38#if 0
39static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 5/4/95";
40#endif
41static const char rcsid[] =
42  "$FreeBSD: head/bin/sh/var.c 97915 2002-06-06 04:02:50Z tjr $";
43#endif /* not lint */
44
45#include <unistd.h>
46#include <stdlib.h>
47
48/*
49 * Shell variables.
50 */
51
52#include <locale.h>
53
54#include "shell.h"
55#include "output.h"
56#include "expand.h"
57#include "nodes.h"	/* for other headers */
58#include "eval.h"	/* defines cmdenviron */
59#include "exec.h"
60#include "syntax.h"
61#include "options.h"
62#include "mail.h"
63#include "var.h"
64#include "memalloc.h"
65#include "error.h"
66#include "mystring.h"
67#include "parser.h"
68#ifndef NO_HISTORY
69#include "myhistedit.h"
70#endif
71
72
73#define VTABSIZE 39
74
75
76struct varinit {
77	struct var *var;
78	int flags;
79	char *text;
80	void (*func)(const char *);
81};
82
83
84#if ATTY
85struct var vatty;
86#endif
87#ifndef NO_HISTORY
88struct var vhistsize;
89#endif
90struct var vifs;
91struct var vmail;
92struct var vmpath;
93struct var vpath;
94struct var vppid;
95struct var vps1;
96struct var vps2;
97struct var vvers;
98#if ATTY
99struct var vterm;
100#endif
101struct var voptind;
102
103const struct varinit varinit[] = {
104#if ATTY
105	{ &vatty,	VSTRFIXED|VTEXTFIXED|VUNSET,	"ATTY=",
106	  NULL },
107#endif
108#ifndef NO_HISTORY
109	{ &vhistsize,	VSTRFIXED|VTEXTFIXED|VUNSET,	"HISTSIZE=",
110	  sethistsize },
111#endif
112	{ &vifs,	VSTRFIXED|VTEXTFIXED,		"IFS= \t\n",
113	  NULL },
114	{ &vmail,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAIL=",
115	  NULL },
116	{ &vmpath,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAILPATH=",
117	  NULL },
118	{ &vpath,	VSTRFIXED|VTEXTFIXED,		"PATH=/bin:/usr/bin",
119	  changepath },
120	{ &vppid,	VSTRFIXED|VTEXTFIXED|VUNSET,	"PPID=",
121	  NULL },
122	/*
123	 * vps1 depends on uid
124	 */
125	{ &vps2,	VSTRFIXED|VTEXTFIXED,		"PS2=> ",
126	  NULL },
127#if ATTY
128	{ &vterm,	VSTRFIXED|VTEXTFIXED|VUNSET,	"TERM=",
129	  NULL },
130#endif
131	{ &voptind,	VSTRFIXED|VTEXTFIXED,		"OPTIND=1",
132	  getoptsreset },
133	{ NULL,	0,				NULL,
134	  NULL }
135};
136
137struct var *vartab[VTABSIZE];
138
139STATIC struct var **hashvar(char *);
140STATIC int varequal(char *, char *);
141STATIC int localevar(char *);
142
143/*
144 * Initialize the varable symbol tables and import the environment
145 */
146
147#ifdef mkinit
148INCLUDE "var.h"
149INIT {
150	char **envp;
151	extern char **environ;
152
153	initvar();
154	for (envp = environ ; *envp ; envp++) {
155		if (strchr(*envp, '=')) {
156			setvareq(*envp, VEXPORT|VTEXTFIXED);
157		}
158	}
159}
160#endif
161
162
163/*
164 * This routine initializes the builtin variables.  It is called when the
165 * shell is initialized and again when a shell procedure is spawned.
166 */
167
168void
169initvar(void)
170{
171	char ppid[20];
172	const struct varinit *ip;
173	struct var *vp;
174	struct var **vpp;
175
176	for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
177		if ((vp->flags & VEXPORT) == 0) {
178			vpp = hashvar(ip->text);
179			vp->next = *vpp;
180			*vpp = vp;
181			vp->text = ip->text;
182			vp->flags = ip->flags;
183			vp->func = ip->func;
184		}
185	}
186	/*
187	 * PS1 depends on uid
188	 */
189	if ((vps1.flags & VEXPORT) == 0) {
190		vpp = hashvar("PS1=");
191		vps1.next = *vpp;
192		*vpp = &vps1;
193		vps1.text = geteuid() ? "PS1=$ " : "PS1=# ";
194		vps1.flags = VSTRFIXED|VTEXTFIXED;
195	}
196	if ((vppid.flags & VEXPORT) == 0) {
197		fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
198		setvarsafe("PPID", ppid, 0);
199	}
200}
201
202/*
203 * Safe version of setvar, returns 1 on success 0 on failure.
204 */
205
206int
207setvarsafe(char *name, char *val, int flags)
208{
209	struct jmploc jmploc;
210	struct jmploc *volatile savehandler = handler;
211	int err = 0;
212#if __GNUC__
213	/* Avoid longjmp clobbering */
214	(void) &err;
215#endif
216
217	if (setjmp(jmploc.loc))
218		err = 1;
219	else {
220		handler = &jmploc;
221		setvar(name, val, flags);
222	}
223	handler = savehandler;
224	return err;
225}
226
227/*
228 * Set the value of a variable.  The flags argument is tored with the
229 * flags of the variable.  If val is NULL, the variable is unset.
230 */
231
232void
233setvar(char *name, char *val, int flags)
234{
235	char *p, *q;
236	int len;
237	int namelen;
238	char *nameeq;
239	int isbad;
240
241	isbad = 0;
242	p = name;
243	if (! is_name(*p))
244		isbad = 1;
245	p++;
246	for (;;) {
247		if (! is_in_name(*p)) {
248			if (*p == '\0' || *p == '=')
249				break;
250			isbad = 1;
251		}
252		p++;
253	}
254	namelen = p - name;
255	if (isbad)
256		error("%.*s: bad variable name", namelen, name);
257	len = namelen + 2;		/* 2 is space for '=' and '\0' */
258	if (val == NULL) {
259		flags |= VUNSET;
260	} else {
261		len += strlen(val);
262	}
263	p = nameeq = ckmalloc(len);
264	q = name;
265	while (--namelen >= 0)
266		*p++ = *q++;
267	*p++ = '=';
268	*p = '\0';
269	if (val)
270		scopy(val, p);
271	setvareq(nameeq, flags);
272}
273
274STATIC int
275localevar(char *s)
276{
277	static char *lnames[7] = {
278		"ALL", "COLLATE", "CTYPE", "MONETARY",
279		"NUMERIC", "TIME", NULL
280	};
281	char **ss;
282
283	if (*s != 'L')
284		return 0;
285	if (varequal(s + 1, "ANG"))
286		return 1;
287	if (strncmp(s + 1, "C_", 2) != 0)
288		return 0;
289	for (ss = lnames; *ss ; ss++)
290		if (varequal(s + 3, *ss))
291			return 1;
292	return 0;
293}
294
295/*
296 * Same as setvar except that the variable and value are passed in
297 * the first argument as name=value.  Since the first argument will
298 * be actually stored in the table, it should not be a string that
299 * will go away.
300 */
301
302void
303setvareq(char *s, int flags)
304{
305	struct var *vp, **vpp;
306	int len;
307
308	if (aflag)
309		flags |= VEXPORT;
310	vpp = hashvar(s);
311	for (vp = *vpp ; vp ; vp = vp->next) {
312		if (varequal(s, vp->text)) {
313			if (vp->flags & VREADONLY) {
314				len = strchr(s, '=') - s;
315				error("%.*s: is read only", len, s);
316			}
317			INTOFF;
318
319			if (vp->func && (flags & VNOFUNC) == 0)
320				(*vp->func)(strchr(s, '=') + 1);
321
322			if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
323				ckfree(vp->text);
324
325			vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
326			vp->flags |= flags;
327			vp->text = s;
328
329			/*
330			 * We could roll this to a function, to handle it as
331			 * a regular variable function callback, but why bother?
332			 */
333			if (vp == &vmpath || (vp == &vmail && ! mpathset()))
334				chkmail(1);
335			if ((vp->flags & VEXPORT) && localevar(s)) {
336				putenv(s);
337				(void) setlocale(LC_ALL, "");
338			}
339			INTON;
340			return;
341		}
342	}
343	/* not found */
344	vp = ckmalloc(sizeof (*vp));
345	vp->flags = flags;
346	vp->text = s;
347	vp->next = *vpp;
348	vp->func = NULL;
349	INTOFF;
350	*vpp = vp;
351	if ((vp->flags & VEXPORT) && localevar(s)) {
352		putenv(s);
353		(void) setlocale(LC_ALL, "");
354	}
355	INTON;
356}
357
358
359
360/*
361 * Process a linked list of variable assignments.
362 */
363
364void
365listsetvar(struct strlist *list)
366{
367	struct strlist *lp;
368
369	INTOFF;
370	for (lp = list ; lp ; lp = lp->next) {
371		setvareq(savestr(lp->text), 0);
372	}
373	INTON;
374}
375
376
377
378/*
379 * Find the value of a variable.  Returns NULL if not set.
380 */
381
382char *
383lookupvar(char *name)
384{
385	struct var *v;
386
387	for (v = *hashvar(name) ; v ; v = v->next) {
388		if (varequal(v->text, name)) {
389			if (v->flags & VUNSET)
390				return NULL;
391			return strchr(v->text, '=') + 1;
392		}
393	}
394	return NULL;
395}
396
397
398
399/*
400 * Search the environment of a builtin command.  If the second argument
401 * is nonzero, return the value of a variable even if it hasn't been
402 * exported.
403 */
404
405char *
406bltinlookup(char *name, int doall)
407{
408	struct strlist *sp;
409	struct var *v;
410
411	for (sp = cmdenviron ; sp ; sp = sp->next) {
412		if (varequal(sp->text, name))
413			return strchr(sp->text, '=') + 1;
414	}
415	for (v = *hashvar(name) ; v ; v = v->next) {
416		if (varequal(v->text, name)) {
417			if ((v->flags & VUNSET)
418			 || (!doall && (v->flags & VEXPORT) == 0))
419				return NULL;
420			return strchr(v->text, '=') + 1;
421		}
422	}
423	return NULL;
424}
425
426
427
428/*
429 * Generate a list of exported variables.  This routine is used to construct
430 * the third argument to execve when executing a program.
431 */
432
433char **
434environment(void)
435{
436	int nenv;
437	struct var **vpp;
438	struct var *vp;
439	char **env, **ep;
440
441	nenv = 0;
442	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
443		for (vp = *vpp ; vp ; vp = vp->next)
444			if (vp->flags & VEXPORT)
445				nenv++;
446	}
447	ep = env = stalloc((nenv + 1) * sizeof *env);
448	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
449		for (vp = *vpp ; vp ; vp = vp->next)
450			if (vp->flags & VEXPORT)
451				*ep++ = vp->text;
452	}
453	*ep = NULL;
454	return env;
455}
456
457
458/*
459 * Called when a shell procedure is invoked to clear out nonexported
460 * variables.  It is also necessary to reallocate variables of with
461 * VSTACK set since these are currently allocated on the stack.
462 */
463
464#ifdef mkinit
465MKINIT void shprocvar();
466
467SHELLPROC {
468	shprocvar();
469}
470#endif
471
472void
473shprocvar(void)
474{
475	struct var **vpp;
476	struct var *vp, **prev;
477
478	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
479		for (prev = vpp ; (vp = *prev) != NULL ; ) {
480			if ((vp->flags & VEXPORT) == 0) {
481				*prev = vp->next;
482				if ((vp->flags & VTEXTFIXED) == 0)
483					ckfree(vp->text);
484				if ((vp->flags & VSTRFIXED) == 0)
485					ckfree(vp);
486			} else {
487				if (vp->flags & VSTACK) {
488					vp->text = savestr(vp->text);
489					vp->flags &=~ VSTACK;
490				}
491				prev = &vp->next;
492			}
493		}
494	}
495	initvar();
496}
497
498
499
500/*
501 * Command to list all variables which are set.  Currently this command
502 * is invoked from the set command when the set command is called without
503 * any variables.
504 */
505
506int
507showvarscmd(int argc __unused, char **argv __unused)
508{
509	struct var **vpp;
510	struct var *vp;
511	const char *s;
512
513	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
514		for (vp = *vpp ; vp ; vp = vp->next) {
515			if (vp->flags & VUNSET)
516				continue;
517			for (s = vp->text; *s != '='; s++)
518				out1c(*s);
519			out1c('=');
520			out1qstr(s + 1);
521			out1c('\n');
522		}
523	}
524	return 0;
525}
526
527
528
529/*
530 * The export and readonly commands.
531 */
532
533int
534exportcmd(int argc, char **argv)
535{
536	struct var **vpp;
537	struct var *vp;
538	char *name;
539	char *p;
540	char *cmdname;
541	int ch, values;
542	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
543
544	cmdname = argv[0];
545	optreset = optind = 1;
546	values = 0;
547	while ((ch = getopt(argc, argv, "p")) != -1) {
548		switch (ch) {
549		case 'p':
550			values = 1;
551			break;
552		case '?':
553		default:
554			error("unknown option: -%c", optopt);
555		}
556	}
557	argc -= optind;
558	argv += optind;
559
560	listsetvar(cmdenviron);
561	if (argc != 0) {
562		while ((name = *argptr++) != NULL) {
563			if ((p = strchr(name, '=')) != NULL) {
564				p++;
565			} else {
566				vpp = hashvar(name);
567				for (vp = *vpp ; vp ; vp = vp->next) {
568					if (varequal(vp->text, name)) {
569
570						vp->flags |= flag;
571						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
572							putenv(vp->text);
573							(void) setlocale(LC_ALL, "");
574						}
575						goto found;
576					}
577				}
578			}
579			setvar(name, p, flag);
580found:;
581		}
582	} else {
583		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
584			for (vp = *vpp ; vp ; vp = vp->next) {
585				if (vp->flags & flag) {
586					if (values) {
587						out1str(cmdname);
588						out1c(' ');
589					}
590					for (p = vp->text ; *p != '=' ; p++)
591						out1c(*p);
592					if (values && !(vp->flags & VUNSET)) {
593						out1c('=');
594						out1qstr(p + 1);
595					}
596					out1c('\n');
597				}
598			}
599		}
600	}
601	return 0;
602}
603
604
605/*
606 * The "local" command.
607 */
608
609int
610localcmd(int argc __unused, char **argv __unused)
611{
612	char *name;
613
614	if (! in_function())
615		error("Not in a function");
616	while ((name = *argptr++) != NULL) {
617		mklocal(name);
618	}
619	return 0;
620}
621
622
623/*
624 * Make a variable a local variable.  When a variable is made local, it's
625 * value and flags are saved in a localvar structure.  The saved values
626 * will be restored when the shell function returns.  We handle the name
627 * "-" as a special case.
628 */
629
630void
631mklocal(char *name)
632{
633	struct localvar *lvp;
634	struct var **vpp;
635	struct var *vp;
636
637	INTOFF;
638	lvp = ckmalloc(sizeof (struct localvar));
639	if (name[0] == '-' && name[1] == '\0') {
640		lvp->text = ckmalloc(sizeof optlist);
641		memcpy(lvp->text, optlist, sizeof optlist);
642		vp = NULL;
643	} else {
644		vpp = hashvar(name);
645		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
646		if (vp == NULL) {
647			if (strchr(name, '='))
648				setvareq(savestr(name), VSTRFIXED);
649			else
650				setvar(name, NULL, VSTRFIXED);
651			vp = *vpp;	/* the new variable */
652			lvp->text = NULL;
653			lvp->flags = VUNSET;
654		} else {
655			lvp->text = vp->text;
656			lvp->flags = vp->flags;
657			vp->flags |= VSTRFIXED|VTEXTFIXED;
658			if (strchr(name, '='))
659				setvareq(savestr(name), 0);
660		}
661	}
662	lvp->vp = vp;
663	lvp->next = localvars;
664	localvars = lvp;
665	INTON;
666}
667
668
669/*
670 * Called after a function returns.
671 */
672
673void
674poplocalvars(void)
675{
676	struct localvar *lvp;
677	struct var *vp;
678
679	while ((lvp = localvars) != NULL) {
680		localvars = lvp->next;
681		vp = lvp->vp;
682		if (vp == NULL) {	/* $- saved */
683			memcpy(optlist, lvp->text, sizeof optlist);
684			ckfree(lvp->text);
685		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
686			(void)unsetvar(vp->text);
687		} else {
688			if ((vp->flags & VTEXTFIXED) == 0)
689				ckfree(vp->text);
690			vp->flags = lvp->flags;
691			vp->text = lvp->text;
692		}
693		ckfree(lvp);
694	}
695}
696
697
698int
699setvarcmd(int argc, char **argv)
700{
701	if (argc <= 2)
702		return unsetcmd(argc, argv);
703	else if (argc == 3)
704		setvar(argv[1], argv[2], 0);
705	else
706		error("List assignment not implemented");
707	return 0;
708}
709
710
711/*
712 * The unset builtin command.  We unset the function before we unset the
713 * variable to allow a function to be unset when there is a readonly variable
714 * with the same name.
715 */
716
717int
718unsetcmd(int argc __unused, char **argv __unused)
719{
720	char **ap;
721	int i;
722	int flg_func = 0;
723	int flg_var = 0;
724	int ret = 0;
725
726	while ((i = nextopt("vf")) != '\0') {
727		if (i == 'f')
728			flg_func = 1;
729		else
730			flg_var = 1;
731	}
732	if (flg_func == 0 && flg_var == 0)
733		flg_var = 1;
734
735	for (ap = argptr; *ap ; ap++) {
736		if (flg_func)
737			ret |= unsetfunc(*ap);
738		if (flg_var)
739			ret |= unsetvar(*ap);
740	}
741	return ret;
742}
743
744
745/*
746 * Unset the specified variable.
747 */
748
749int
750unsetvar(char *s)
751{
752	struct var **vpp;
753	struct var *vp;
754
755	vpp = hashvar(s);
756	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
757		if (varequal(vp->text, s)) {
758			if (vp->flags & VREADONLY)
759				return (1);
760			INTOFF;
761			if (*(strchr(vp->text, '=') + 1) != '\0')
762				setvar(s, nullstr, 0);
763			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
764				unsetenv(s);
765				setlocale(LC_ALL, "");
766			}
767			vp->flags &= ~VEXPORT;
768			vp->flags |= VUNSET;
769			if ((vp->flags & VSTRFIXED) == 0) {
770				if ((vp->flags & VTEXTFIXED) == 0)
771					ckfree(vp->text);
772				*vpp = vp->next;
773				ckfree(vp);
774			}
775			INTON;
776			return (0);
777		}
778	}
779
780	return (1);
781}
782
783
784
785/*
786 * Find the appropriate entry in the hash table from the name.
787 */
788
789STATIC struct var **
790hashvar(char *p)
791{
792	unsigned int hashval;
793
794	hashval = ((unsigned char) *p) << 4;
795	while (*p && *p != '=')
796		hashval += (unsigned char) *p++;
797	return &vartab[hashval % VTABSIZE];
798}
799
800
801
802/*
803 * Returns true if the two strings specify the same varable.  The first
804 * variable name is terminated by '='; the second may be terminated by
805 * either '=' or '\0'.
806 */
807
808STATIC int
809varequal(char *p, char *q)
810{
811	while (*p == *q++) {
812		if (*p++ == '=')
813			return 1;
814	}
815	if (*p == '=' && *(q - 1) == '\0')
816		return 1;
817	return 0;
818}
819