var.c revision 171195
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 171195 2007-07-04 00:00:41Z scf $");
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	char *p;
293	int len;
294
295	if (aflag)
296		flags |= VEXPORT;
297	vpp = hashvar(s);
298	for (vp = *vpp ; vp ; vp = vp->next) {
299		if (varequal(s, vp->text)) {
300			if (vp->flags & VREADONLY) {
301				len = strchr(s, '=') - s;
302				error("%.*s: is read only", len, s);
303			}
304			INTOFF;
305
306			if (vp->func && (flags & VNOFUNC) == 0)
307				(*vp->func)(strchr(s, '=') + 1);
308
309			if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
310				ckfree(vp->text);
311
312			vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
313			vp->flags |= flags;
314			vp->text = s;
315
316			/*
317			 * We could roll this to a function, to handle it as
318			 * a regular variable function callback, but why bother?
319			 */
320			if (vp == &vmpath || (vp == &vmail && ! mpathset()))
321				chkmail(1);
322			if ((vp->flags & VEXPORT) && localevar(s)) {
323				p = strchr(s, '=');
324				*p = '\0';
325				(void) setenv(s, p + 1, 1);
326				*p = '=';
327				(void) setlocale(LC_ALL, "");
328			}
329			INTON;
330			return;
331		}
332	}
333	/* not found */
334	vp = ckmalloc(sizeof (*vp));
335	vp->flags = flags;
336	vp->text = s;
337	vp->next = *vpp;
338	vp->func = NULL;
339	INTOFF;
340	*vpp = vp;
341	if ((vp->flags & VEXPORT) && localevar(s)) {
342		p = strchr(s, '=');
343		*p = '\0';
344		(void) setenv(s, p + 1, 1);
345		*p = '=';
346		(void) setlocale(LC_ALL, "");
347	}
348	INTON;
349}
350
351
352
353/*
354 * Process a linked list of variable assignments.
355 */
356
357void
358listsetvar(struct strlist *list)
359{
360	struct strlist *lp;
361
362	INTOFF;
363	for (lp = list ; lp ; lp = lp->next) {
364		setvareq(savestr(lp->text), 0);
365	}
366	INTON;
367}
368
369
370
371/*
372 * Find the value of a variable.  Returns NULL if not set.
373 */
374
375char *
376lookupvar(char *name)
377{
378	struct var *v;
379
380	for (v = *hashvar(name) ; v ; v = v->next) {
381		if (varequal(v->text, name)) {
382			if (v->flags & VUNSET)
383				return NULL;
384			return strchr(v->text, '=') + 1;
385		}
386	}
387	return NULL;
388}
389
390
391
392/*
393 * Search the environment of a builtin command.  If the second argument
394 * is nonzero, return the value of a variable even if it hasn't been
395 * exported.
396 */
397
398char *
399bltinlookup(char *name, int doall)
400{
401	struct strlist *sp;
402	struct var *v;
403
404	for (sp = cmdenviron ; sp ; sp = sp->next) {
405		if (varequal(sp->text, name))
406			return strchr(sp->text, '=') + 1;
407	}
408	for (v = *hashvar(name) ; v ; v = v->next) {
409		if (varequal(v->text, name)) {
410			if ((v->flags & VUNSET)
411			 || (!doall && (v->flags & VEXPORT) == 0))
412				return NULL;
413			return strchr(v->text, '=') + 1;
414		}
415	}
416	return NULL;
417}
418
419
420
421/*
422 * Generate a list of exported variables.  This routine is used to construct
423 * the third argument to execve when executing a program.
424 */
425
426char **
427environment(void)
428{
429	int nenv;
430	struct var **vpp;
431	struct var *vp;
432	char **env, **ep;
433
434	nenv = 0;
435	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
436		for (vp = *vpp ; vp ; vp = vp->next)
437			if (vp->flags & VEXPORT)
438				nenv++;
439	}
440	ep = env = stalloc((nenv + 1) * sizeof *env);
441	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
442		for (vp = *vpp ; vp ; vp = vp->next)
443			if (vp->flags & VEXPORT)
444				*ep++ = vp->text;
445	}
446	*ep = NULL;
447	return env;
448}
449
450
451/*
452 * Called when a shell procedure is invoked to clear out nonexported
453 * variables.  It is also necessary to reallocate variables of with
454 * VSTACK set since these are currently allocated on the stack.
455 */
456
457#ifdef mkinit
458MKINIT void shprocvar(void);
459
460SHELLPROC {
461	shprocvar();
462}
463#endif
464
465void
466shprocvar(void)
467{
468	struct var **vpp;
469	struct var *vp, **prev;
470
471	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
472		for (prev = vpp ; (vp = *prev) != NULL ; ) {
473			if ((vp->flags & VEXPORT) == 0) {
474				*prev = vp->next;
475				if ((vp->flags & VTEXTFIXED) == 0)
476					ckfree(vp->text);
477				if ((vp->flags & VSTRFIXED) == 0)
478					ckfree(vp);
479			} else {
480				if (vp->flags & VSTACK) {
481					vp->text = savestr(vp->text);
482					vp->flags &=~ VSTACK;
483				}
484				prev = &vp->next;
485			}
486		}
487	}
488	initvar();
489}
490
491
492static int
493var_compare(const void *a, const void *b)
494{
495	const char *const *sa, *const *sb;
496
497	sa = a;
498	sb = b;
499	/*
500	 * This compares two var=value strings which creates a different
501	 * order from what you would probably expect.  POSIX is somewhat
502	 * ambiguous on what should be sorted exactly.
503	 */
504	return strcoll(*sa, *sb);
505}
506
507
508/*
509 * Command to list all variables which are set.  Currently this command
510 * is invoked from the set command when the set command is called without
511 * any variables.
512 */
513
514int
515showvarscmd(int argc __unused, char **argv __unused)
516{
517	struct var **vpp;
518	struct var *vp;
519	const char *s;
520	const char **vars;
521	int i, n;
522
523	/*
524	 * POSIX requires us to sort the variables.
525	 */
526	n = 0;
527	for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
528		for (vp = *vpp; vp; vp = vp->next) {
529			if (!(vp->flags & VUNSET))
530				n++;
531		}
532	}
533
534	INTON;
535	vars = ckmalloc(n * sizeof(*vars));
536	i = 0;
537	for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
538		for (vp = *vpp; vp; vp = vp->next) {
539			if (!(vp->flags & VUNSET))
540				vars[i++] = vp->text;
541		}
542	}
543
544	qsort(vars, n, sizeof(*vars), var_compare);
545	for (i = 0; i < n; i++) {
546		for (s = vars[i]; *s != '='; s++)
547			out1c(*s);
548		out1c('=');
549		out1qstr(s + 1);
550		out1c('\n');
551	}
552	ckfree(vars);
553	INTOFF;
554
555	return 0;
556}
557
558
559
560/*
561 * The export and readonly commands.
562 */
563
564int
565exportcmd(int argc, char **argv)
566{
567	struct var **vpp;
568	struct var *vp;
569	char *name;
570	char *p;
571	char *cmdname;
572	int ch, values;
573	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
574
575	cmdname = argv[0];
576	optreset = optind = 1;
577	opterr = 0;
578	values = 0;
579	while ((ch = getopt(argc, argv, "p")) != -1) {
580		switch (ch) {
581		case 'p':
582			values = 1;
583			break;
584		case '?':
585		default:
586			error("unknown option: -%c", optopt);
587		}
588	}
589	argc -= optind;
590	argv += optind;
591
592	if (values && argc != 0)
593		error("-p requires no arguments");
594	listsetvar(cmdenviron);
595	if (argc != 0) {
596		while ((name = *argv++) != NULL) {
597			if ((p = strchr(name, '=')) != NULL) {
598				p++;
599			} else {
600				vpp = hashvar(name);
601				for (vp = *vpp ; vp ; vp = vp->next) {
602					if (varequal(vp->text, name)) {
603
604						vp->flags |= flag;
605						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
606							p = strchr(vp->text, '=');
607							*p = '\0';
608							(void) setenv(vp->text, p + 1, 1);
609							*p = '=';
610							(void) setlocale(LC_ALL, "");
611						}
612						goto found;
613					}
614				}
615			}
616			setvar(name, p, flag);
617found:;
618		}
619	} else {
620		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
621			for (vp = *vpp ; vp ; vp = vp->next) {
622				if (vp->flags & flag) {
623					if (values) {
624						out1str(cmdname);
625						out1c(' ');
626					}
627					for (p = vp->text ; *p != '=' ; p++)
628						out1c(*p);
629					if (values && !(vp->flags & VUNSET)) {
630						out1c('=');
631						out1qstr(p + 1);
632					}
633					out1c('\n');
634				}
635			}
636		}
637	}
638	return 0;
639}
640
641
642/*
643 * The "local" command.
644 */
645
646int
647localcmd(int argc __unused, char **argv __unused)
648{
649	char *name;
650
651	if (! in_function())
652		error("Not in a function");
653	while ((name = *argptr++) != NULL) {
654		mklocal(name);
655	}
656	return 0;
657}
658
659
660/*
661 * Make a variable a local variable.  When a variable is made local, it's
662 * value and flags are saved in a localvar structure.  The saved values
663 * will be restored when the shell function returns.  We handle the name
664 * "-" as a special case.
665 */
666
667void
668mklocal(char *name)
669{
670	struct localvar *lvp;
671	struct var **vpp;
672	struct var *vp;
673
674	INTOFF;
675	lvp = ckmalloc(sizeof (struct localvar));
676	if (name[0] == '-' && name[1] == '\0') {
677		lvp->text = ckmalloc(sizeof optlist);
678		memcpy(lvp->text, optlist, sizeof optlist);
679		vp = NULL;
680	} else {
681		vpp = hashvar(name);
682		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
683		if (vp == NULL) {
684			if (strchr(name, '='))
685				setvareq(savestr(name), VSTRFIXED);
686			else
687				setvar(name, NULL, VSTRFIXED);
688			vp = *vpp;	/* the new variable */
689			lvp->text = NULL;
690			lvp->flags = VUNSET;
691		} else {
692			lvp->text = vp->text;
693			lvp->flags = vp->flags;
694			vp->flags |= VSTRFIXED|VTEXTFIXED;
695			if (strchr(name, '='))
696				setvareq(savestr(name), 0);
697		}
698	}
699	lvp->vp = vp;
700	lvp->next = localvars;
701	localvars = lvp;
702	INTON;
703}
704
705
706/*
707 * Called after a function returns.
708 */
709
710void
711poplocalvars(void)
712{
713	struct localvar *lvp;
714	struct var *vp;
715
716	while ((lvp = localvars) != NULL) {
717		localvars = lvp->next;
718		vp = lvp->vp;
719		if (vp == NULL) {	/* $- saved */
720			memcpy(optlist, lvp->text, sizeof optlist);
721			ckfree(lvp->text);
722		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
723			(void)unsetvar(vp->text);
724		} else {
725			if ((vp->flags & VTEXTFIXED) == 0)
726				ckfree(vp->text);
727			vp->flags = lvp->flags;
728			vp->text = lvp->text;
729		}
730		ckfree(lvp);
731	}
732}
733
734
735int
736setvarcmd(int argc, char **argv)
737{
738	if (argc <= 2)
739		return unsetcmd(argc, argv);
740	else if (argc == 3)
741		setvar(argv[1], argv[2], 0);
742	else
743		error("List assignment not implemented");
744	return 0;
745}
746
747
748/*
749 * The unset builtin command.  We unset the function before we unset the
750 * variable to allow a function to be unset when there is a readonly variable
751 * with the same name.
752 */
753
754int
755unsetcmd(int argc __unused, char **argv __unused)
756{
757	char **ap;
758	int i;
759	int flg_func = 0;
760	int flg_var = 0;
761	int ret = 0;
762
763	while ((i = nextopt("vf")) != '\0') {
764		if (i == 'f')
765			flg_func = 1;
766		else
767			flg_var = 1;
768	}
769	if (flg_func == 0 && flg_var == 0)
770		flg_var = 1;
771
772	for (ap = argptr; *ap ; ap++) {
773		if (flg_func)
774			ret |= unsetfunc(*ap);
775		if (flg_var)
776			ret |= unsetvar(*ap);
777	}
778	return ret;
779}
780
781
782/*
783 * Unset the specified variable.
784 */
785
786int
787unsetvar(char *s)
788{
789	struct var **vpp;
790	struct var *vp;
791
792	vpp = hashvar(s);
793	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
794		if (varequal(vp->text, s)) {
795			if (vp->flags & VREADONLY)
796				return (1);
797			INTOFF;
798			if (*(strchr(vp->text, '=') + 1) != '\0')
799				setvar(s, nullstr, 0);
800			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
801				unsetenv(s);
802				setlocale(LC_ALL, "");
803			}
804			vp->flags &= ~VEXPORT;
805			vp->flags |= VUNSET;
806			if ((vp->flags & VSTRFIXED) == 0) {
807				if ((vp->flags & VTEXTFIXED) == 0)
808					ckfree(vp->text);
809				*vpp = vp->next;
810				ckfree(vp);
811			}
812			INTON;
813			return (0);
814		}
815	}
816
817	return (0);
818}
819
820
821
822/*
823 * Find the appropriate entry in the hash table from the name.
824 */
825
826STATIC struct var **
827hashvar(char *p)
828{
829	unsigned int hashval;
830
831	hashval = ((unsigned char) *p) << 4;
832	while (*p && *p != '=')
833		hashval += (unsigned char) *p++;
834	return &vartab[hashval % VTABSIZE];
835}
836
837
838
839/*
840 * Returns true if the two strings specify the same varable.  The first
841 * variable name is terminated by '='; the second may be terminated by
842 * either '=' or '\0'.
843 */
844
845STATIC int
846varequal(char *p, char *q)
847{
848	while (*p == *q++) {
849		if (*p++ == '=')
850			return 1;
851	}
852	if (*p == '=' && *(q - 1) == '\0')
853		return 1;
854	return 0;
855}
856