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