var.c revision 203576
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 203576 2010-02-06 22:57:24Z jilles $");
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	const 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,	VUNSET,				"HISTSIZE=",
98	  sethistsize },
99#endif
100	{ &vifs,	0,				"IFS= \t\n",
101	  NULL },
102	{ &vmail,	VUNSET,				"MAIL=",
103	  NULL },
104	{ &vmpath,	VUNSET,				"MAILPATH=",
105	  NULL },
106	{ &vpath,	0,				"PATH=" _PATH_DEFPATH,
107	  changepath },
108	{ &vppid,	VUNSET,				"PPID=",
109	  NULL },
110	/*
111	 * vps1 depends on uid
112	 */
113	{ &vps2,	0,				"PS2=> ",
114	  NULL },
115	{ &vps4,	0,				"PS4=+ ",
116	  NULL },
117	{ &voptind,	0,				"OPTIND=1",
118	  getoptsreset },
119	{ NULL,	0,				NULL,
120	  NULL }
121};
122
123STATIC struct var *vartab[VTABSIZE];
124
125STATIC struct var **hashvar(const char *);
126STATIC int varequal(const char *, const char *);
127STATIC int localevar(const char *);
128
129/*
130 * Initialize the variable symbol tables and import the environment.
131 */
132
133#ifdef mkinit
134INCLUDE "var.h"
135MKINIT char **environ;
136INIT {
137	char **envp;
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 = __DECONST(char *, ip->text);
168			vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
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 = __DECONST(char *, 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(const char *name, const char *val, int flags)
194{
195	struct jmploc jmploc;
196	struct jmploc *const savehandler = handler;
197	int err = 0;
198	int inton;
199
200	inton = is_int_on();
201	if (setjmp(jmploc.loc))
202		err = 1;
203	else {
204		handler = &jmploc;
205		setvar(name, val, flags);
206	}
207	handler = savehandler;
208	SETINTON(inton);
209	return err;
210}
211
212/*
213 * Set the value of a variable.  The flags argument is stored with the
214 * flags of the variable.  If val is NULL, the variable is unset.
215 */
216
217void
218setvar(const char *name, const char *val, int flags)
219{
220	const char *p;
221	int len;
222	int namelen;
223	char *nameeq;
224	int isbad;
225
226	isbad = 0;
227	p = name;
228	if (! is_name(*p))
229		isbad = 1;
230	p++;
231	for (;;) {
232		if (! is_in_name(*p)) {
233			if (*p == '\0' || *p == '=')
234				break;
235			isbad = 1;
236		}
237		p++;
238	}
239	namelen = p - name;
240	if (isbad)
241		error("%.*s: bad variable name", namelen, name);
242	len = namelen + 2;		/* 2 is space for '=' and '\0' */
243	if (val == NULL) {
244		flags |= VUNSET;
245	} else {
246		len += strlen(val);
247	}
248	nameeq = ckmalloc(len);
249	memcpy(nameeq, name, namelen);
250	nameeq[namelen] = '=';
251	if (val)
252		scopy(val, nameeq + namelen + 1);
253	else
254		nameeq[namelen + 1] = '\0';
255	setvareq(nameeq, flags);
256}
257
258STATIC int
259localevar(const char *s)
260{
261	static const char *lnames[7] = {
262		"ALL", "COLLATE", "CTYPE", "MONETARY",
263		"NUMERIC", "TIME", NULL
264	};
265	const char **ss;
266
267	if (*s != 'L')
268		return 0;
269	if (varequal(s + 1, "ANG"))
270		return 1;
271	if (strncmp(s + 1, "C_", 2) != 0)
272		return 0;
273	for (ss = lnames; *ss ; ss++)
274		if (varequal(s + 3, *ss))
275			return 1;
276	return 0;
277}
278
279
280/*
281 * Sets/unsets an environment variable from a pointer that may actually be a
282 * pointer into environ where the string should not be manipulated.
283 */
284static void
285change_env(const char *s, int set)
286{
287	char *eqp;
288	char *ss;
289
290	ss = savestr(s);
291	if ((eqp = strchr(ss, '=')) != NULL)
292		*eqp = '\0';
293	if (set && eqp != NULL)
294		(void) setenv(ss, eqp + 1, 1);
295	else
296		(void) unsetenv(ss);
297	ckfree(ss);
298
299	return;
300}
301
302
303/*
304 * Same as setvar except that the variable and value are passed in
305 * the first argument as name=value.  Since the first argument will
306 * be actually stored in the table, it should not be a string that
307 * will go away.
308 */
309
310void
311setvareq(char *s, int flags)
312{
313	struct var *vp, **vpp;
314	int len;
315
316	if (aflag)
317		flags |= VEXPORT;
318	vpp = hashvar(s);
319	for (vp = *vpp ; vp ; vp = vp->next) {
320		if (varequal(s, vp->text)) {
321			if (vp->flags & VREADONLY) {
322				len = strchr(s, '=') - s;
323				error("%.*s: is read only", len, s);
324			}
325			INTOFF;
326
327			if (vp->func && (flags & VNOFUNC) == 0)
328				(*vp->func)(strchr(s, '=') + 1);
329
330			if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
331				ckfree(vp->text);
332
333			vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
334			vp->flags |= flags;
335			vp->text = s;
336
337			/*
338			 * We could roll this to a function, to handle it as
339			 * a regular variable function callback, but why bother?
340			 *
341			 * Note: this assumes iflag is not set to 1 initially.
342			 * As part of init(), this is called before arguments
343			 * are looked at.
344			 */
345			if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
346			    iflag == 1)
347				chkmail(1);
348			if ((vp->flags & VEXPORT) && localevar(s)) {
349				change_env(s, 1);
350				(void) setlocale(LC_ALL, "");
351			}
352			INTON;
353			return;
354		}
355	}
356	/* not found */
357	vp = ckmalloc(sizeof (*vp));
358	vp->flags = flags;
359	vp->text = s;
360	vp->next = *vpp;
361	vp->func = NULL;
362	INTOFF;
363	*vpp = vp;
364	if ((vp->flags & VEXPORT) && localevar(s)) {
365		change_env(s, 1);
366		(void) setlocale(LC_ALL, "");
367	}
368	INTON;
369}
370
371
372
373/*
374 * Process a linked list of variable assignments.
375 */
376
377void
378listsetvar(struct strlist *list)
379{
380	struct strlist *lp;
381
382	INTOFF;
383	for (lp = list ; lp ; lp = lp->next) {
384		setvareq(savestr(lp->text), 0);
385	}
386	INTON;
387}
388
389
390
391/*
392 * Find the value of a variable.  Returns NULL if not set.
393 */
394
395char *
396lookupvar(const char *name)
397{
398	struct var *v;
399
400	for (v = *hashvar(name) ; v ; v = v->next) {
401		if (varequal(v->text, name)) {
402			if (v->flags & VUNSET)
403				return NULL;
404			return strchr(v->text, '=') + 1;
405		}
406	}
407	return NULL;
408}
409
410
411
412/*
413 * Search the environment of a builtin command.  If the second argument
414 * is nonzero, return the value of a variable even if it hasn't been
415 * exported.
416 */
417
418char *
419bltinlookup(const char *name, int doall)
420{
421	struct strlist *sp;
422	struct var *v;
423
424	for (sp = cmdenviron ; sp ; sp = sp->next) {
425		if (varequal(sp->text, name))
426			return strchr(sp->text, '=') + 1;
427	}
428	for (v = *hashvar(name) ; v ; v = v->next) {
429		if (varequal(v->text, name)) {
430			if ((v->flags & VUNSET)
431			 || (!doall && (v->flags & VEXPORT) == 0))
432				return NULL;
433			return strchr(v->text, '=') + 1;
434		}
435	}
436	return NULL;
437}
438
439
440
441/*
442 * Generate a list of exported variables.  This routine is used to construct
443 * the third argument to execve when executing a program.
444 */
445
446char **
447environment(void)
448{
449	int nenv;
450	struct var **vpp;
451	struct var *vp;
452	char **env, **ep;
453
454	nenv = 0;
455	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
456		for (vp = *vpp ; vp ; vp = vp->next)
457			if (vp->flags & VEXPORT)
458				nenv++;
459	}
460	ep = env = stalloc((nenv + 1) * sizeof *env);
461	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
462		for (vp = *vpp ; vp ; vp = vp->next)
463			if (vp->flags & VEXPORT)
464				*ep++ = vp->text;
465	}
466	*ep = NULL;
467	return env;
468}
469
470
471/*
472 * Called when a shell procedure is invoked to clear out nonexported
473 * variables.  It is also necessary to reallocate variables of with
474 * VSTACK set since these are currently allocated on the stack.
475 */
476
477MKINIT void shprocvar(void);
478
479#ifdef mkinit
480SHELLPROC {
481	shprocvar();
482}
483#endif
484
485void
486shprocvar(void)
487{
488	struct var **vpp;
489	struct var *vp, **prev;
490
491	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
492		for (prev = vpp ; (vp = *prev) != NULL ; ) {
493			if ((vp->flags & VEXPORT) == 0) {
494				*prev = vp->next;
495				if ((vp->flags & VTEXTFIXED) == 0)
496					ckfree(vp->text);
497				if ((vp->flags & VSTRFIXED) == 0)
498					ckfree(vp);
499			} else {
500				if (vp->flags & VSTACK) {
501					vp->text = savestr(vp->text);
502					vp->flags &=~ VSTACK;
503				}
504				prev = &vp->next;
505			}
506		}
507	}
508	initvar();
509}
510
511
512static int
513var_compare(const void *a, const void *b)
514{
515	const char *const *sa, *const *sb;
516
517	sa = a;
518	sb = b;
519	/*
520	 * This compares two var=value strings which creates a different
521	 * order from what you would probably expect.  POSIX is somewhat
522	 * ambiguous on what should be sorted exactly.
523	 */
524	return strcoll(*sa, *sb);
525}
526
527
528/*
529 * Command to list all variables which are set.  Currently this command
530 * is invoked from the set command when the set command is called without
531 * any variables.
532 */
533
534int
535showvarscmd(int argc __unused, char **argv __unused)
536{
537	struct var **vpp;
538	struct var *vp;
539	const char *s;
540	const char **vars;
541	int i, n;
542
543	/*
544	 * POSIX requires us to sort the variables.
545	 */
546	n = 0;
547	for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
548		for (vp = *vpp; vp; vp = vp->next) {
549			if (!(vp->flags & VUNSET))
550				n++;
551		}
552	}
553
554	INTON;
555	vars = ckmalloc(n * sizeof(*vars));
556	i = 0;
557	for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
558		for (vp = *vpp; vp; vp = vp->next) {
559			if (!(vp->flags & VUNSET))
560				vars[i++] = vp->text;
561		}
562	}
563
564	qsort(vars, n, sizeof(*vars), var_compare);
565	for (i = 0; i < n; i++) {
566		for (s = vars[i]; *s != '='; s++)
567			out1c(*s);
568		out1c('=');
569		out1qstr(s + 1);
570		out1c('\n');
571	}
572	ckfree(vars);
573	INTOFF;
574
575	return 0;
576}
577
578
579
580/*
581 * The export and readonly commands.
582 */
583
584int
585exportcmd(int argc, char **argv)
586{
587	struct var **vpp;
588	struct var *vp;
589	char *name;
590	char *p;
591	char *cmdname;
592	int ch, values;
593	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
594
595	cmdname = argv[0];
596	optreset = optind = 1;
597	opterr = 0;
598	values = 0;
599	while ((ch = getopt(argc, argv, "p")) != -1) {
600		switch (ch) {
601		case 'p':
602			values = 1;
603			break;
604		case '?':
605		default:
606			error("unknown option: -%c", optopt);
607		}
608	}
609	argc -= optind;
610	argv += optind;
611
612	if (values && argc != 0)
613		error("-p requires no arguments");
614	if (argc != 0) {
615		while ((name = *argv++) != NULL) {
616			if ((p = strchr(name, '=')) != NULL) {
617				p++;
618			} else {
619				vpp = hashvar(name);
620				for (vp = *vpp ; vp ; vp = vp->next) {
621					if (varequal(vp->text, name)) {
622
623						vp->flags |= flag;
624						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
625							change_env(vp->text, 1);
626							(void) setlocale(LC_ALL, "");
627						}
628						goto found;
629					}
630				}
631			}
632			setvar(name, p, flag);
633found:;
634		}
635	} else {
636		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
637			for (vp = *vpp ; vp ; vp = vp->next) {
638				if (vp->flags & flag) {
639					if (values) {
640						out1str(cmdname);
641						out1c(' ');
642					}
643					for (p = vp->text ; *p != '=' ; p++)
644						out1c(*p);
645					if (values && !(vp->flags & VUNSET)) {
646						out1c('=');
647						out1qstr(p + 1);
648					}
649					out1c('\n');
650				}
651			}
652		}
653	}
654	return 0;
655}
656
657
658/*
659 * The "local" command.
660 */
661
662int
663localcmd(int argc __unused, char **argv __unused)
664{
665	char *name;
666
667	if (! in_function())
668		error("Not in a function");
669	while ((name = *argptr++) != NULL) {
670		mklocal(name);
671	}
672	return 0;
673}
674
675
676/*
677 * Make a variable a local variable.  When a variable is made local, it's
678 * value and flags are saved in a localvar structure.  The saved values
679 * will be restored when the shell function returns.  We handle the name
680 * "-" as a special case.
681 */
682
683void
684mklocal(char *name)
685{
686	struct localvar *lvp;
687	struct var **vpp;
688	struct var *vp;
689
690	INTOFF;
691	lvp = ckmalloc(sizeof (struct localvar));
692	if (name[0] == '-' && name[1] == '\0') {
693		lvp->text = ckmalloc(sizeof optlist);
694		memcpy(lvp->text, optlist, sizeof optlist);
695		vp = NULL;
696	} else {
697		vpp = hashvar(name);
698		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
699		if (vp == NULL) {
700			if (strchr(name, '='))
701				setvareq(savestr(name), VSTRFIXED);
702			else
703				setvar(name, NULL, VSTRFIXED);
704			vp = *vpp;	/* the new variable */
705			lvp->text = NULL;
706			lvp->flags = VUNSET;
707		} else {
708			lvp->text = vp->text;
709			lvp->flags = vp->flags;
710			vp->flags |= VSTRFIXED|VTEXTFIXED;
711			if (strchr(name, '='))
712				setvareq(savestr(name), 0);
713		}
714	}
715	lvp->vp = vp;
716	lvp->next = localvars;
717	localvars = lvp;
718	INTON;
719}
720
721
722/*
723 * Called after a function returns.
724 */
725
726void
727poplocalvars(void)
728{
729	struct localvar *lvp;
730	struct var *vp;
731
732	while ((lvp = localvars) != NULL) {
733		localvars = lvp->next;
734		vp = lvp->vp;
735		if (vp == NULL) {	/* $- saved */
736			memcpy(optlist, lvp->text, sizeof optlist);
737			ckfree(lvp->text);
738		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
739			(void)unsetvar(vp->text);
740		} else {
741			if ((vp->flags & VTEXTFIXED) == 0)
742				ckfree(vp->text);
743			vp->flags = lvp->flags;
744			vp->text = lvp->text;
745		}
746		ckfree(lvp);
747	}
748}
749
750
751int
752setvarcmd(int argc, char **argv)
753{
754	if (argc <= 2)
755		return unsetcmd(argc, argv);
756	else if (argc == 3)
757		setvar(argv[1], argv[2], 0);
758	else
759		error("List assignment not implemented");
760	return 0;
761}
762
763
764/*
765 * The unset builtin command.  We unset the function before we unset the
766 * variable to allow a function to be unset when there is a readonly variable
767 * with the same name.
768 */
769
770int
771unsetcmd(int argc __unused, char **argv __unused)
772{
773	char **ap;
774	int i;
775	int flg_func = 0;
776	int flg_var = 0;
777	int ret = 0;
778
779	while ((i = nextopt("vf")) != '\0') {
780		if (i == 'f')
781			flg_func = 1;
782		else
783			flg_var = 1;
784	}
785	if (flg_func == 0 && flg_var == 0)
786		flg_var = 1;
787
788	for (ap = argptr; *ap ; ap++) {
789		if (flg_func)
790			ret |= unsetfunc(*ap);
791		if (flg_var)
792			ret |= unsetvar(*ap);
793	}
794	return ret;
795}
796
797
798/*
799 * Unset the specified variable.
800 */
801
802int
803unsetvar(const char *s)
804{
805	struct var **vpp;
806	struct var *vp;
807
808	vpp = hashvar(s);
809	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
810		if (varequal(vp->text, s)) {
811			if (vp->flags & VREADONLY)
812				return (1);
813			INTOFF;
814			if (*(strchr(vp->text, '=') + 1) != '\0')
815				setvar(s, nullstr, 0);
816			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
817				change_env(s, 0);
818				setlocale(LC_ALL, "");
819			}
820			vp->flags &= ~VEXPORT;
821			vp->flags |= VUNSET;
822			if ((vp->flags & VSTRFIXED) == 0) {
823				if ((vp->flags & VTEXTFIXED) == 0)
824					ckfree(vp->text);
825				*vpp = vp->next;
826				ckfree(vp);
827			}
828			INTON;
829			return (0);
830		}
831	}
832
833	return (0);
834}
835
836
837
838/*
839 * Find the appropriate entry in the hash table from the name.
840 */
841
842STATIC struct var **
843hashvar(const char *p)
844{
845	unsigned int hashval;
846
847	hashval = ((unsigned char) *p) << 4;
848	while (*p && *p != '=')
849		hashval += (unsigned char) *p++;
850	return &vartab[hashval % VTABSIZE];
851}
852
853
854
855/*
856 * Returns true if the two strings specify the same varable.  The first
857 * variable name is terminated by '='; the second may be terminated by
858 * either '=' or '\0'.
859 */
860
861STATIC int
862varequal(const char *p, const char *q)
863{
864	while (*p == *q++) {
865		if (*p++ == '=')
866			return 1;
867	}
868	if (*p == '=' && *(q - 1) == '\0')
869		return 1;
870	return 0;
871}
872