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