xref: /freebsd/bin/sh/var.c (revision daf1cffce2e07931f27c6c6998652e90df6ba87e)
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
39 static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 5/4/95";
40 #endif
41 static const char rcsid[] =
42   "$FreeBSD$";
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 
76 struct varinit {
77 	struct var *var;
78 	int flags;
79 	char *text;
80 	void (*func) __P((const char *));
81 };
82 
83 
84 #if ATTY
85 struct var vatty;
86 #endif
87 #ifndef NO_HISTORY
88 struct var vhistsize;
89 #endif
90 struct var vifs;
91 struct var vmail;
92 struct var vmpath;
93 struct var vpath;
94 struct var vps1;
95 struct var vps2;
96 struct var vvers;
97 #if ATTY
98 struct var vterm;
99 #endif
100 struct var voptind;
101 
102 const struct varinit varinit[] = {
103 #if ATTY
104 	{ &vatty,	VSTRFIXED|VTEXTFIXED|VUNSET,	"ATTY=",
105 	  NULL },
106 #endif
107 #ifndef NO_HISTORY
108 	{ &vhistsize,	VSTRFIXED|VTEXTFIXED|VUNSET,	"HISTSIZE=",
109 	  sethistsize },
110 #endif
111 	{ &vifs,	VSTRFIXED|VTEXTFIXED,		"IFS= \t\n",
112 	  NULL },
113 	{ &vmail,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAIL=",
114 	  NULL },
115 	{ &vmpath,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAILPATH=",
116 	  NULL },
117 	{ &vpath,	VSTRFIXED|VTEXTFIXED,		"PATH=/bin:/usr/bin",
118 	  changepath },
119 	/*
120 	 * vps1 depends on uid
121 	 */
122 	{ &vps2,	VSTRFIXED|VTEXTFIXED,		"PS2=> ",
123 	  NULL },
124 #if ATTY
125 	{ &vterm,	VSTRFIXED|VTEXTFIXED|VUNSET,	"TERM=",
126 	  NULL },
127 #endif
128 	{ &voptind,	VSTRFIXED|VTEXTFIXED,		"OPTIND=1",
129 	  getoptsreset },
130 	{ NULL,	0,				NULL,
131 	  NULL }
132 };
133 
134 struct var *vartab[VTABSIZE];
135 
136 STATIC struct var **hashvar __P((char *));
137 STATIC int varequal __P((char *, char *));
138 STATIC int localevar __P((char *));
139 
140 /*
141  * Initialize the varable symbol tables and import the environment
142  */
143 
144 #ifdef mkinit
145 INCLUDE "var.h"
146 INIT {
147 	char **envp;
148 	extern char **environ;
149 
150 	initvar();
151 	for (envp = environ ; *envp ; envp++) {
152 		if (strchr(*envp, '=')) {
153 			setvareq(*envp, VEXPORT|VTEXTFIXED);
154 		}
155 	}
156 }
157 #endif
158 
159 
160 /*
161  * This routine initializes the builtin variables.  It is called when the
162  * shell is initialized and again when a shell procedure is spawned.
163  */
164 
165 void
166 initvar() {
167 	const struct varinit *ip;
168 	struct var *vp;
169 	struct var **vpp;
170 
171 	for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
172 		if ((vp->flags & VEXPORT) == 0) {
173 			vpp = hashvar(ip->text);
174 			vp->next = *vpp;
175 			*vpp = vp;
176 			vp->text = ip->text;
177 			vp->flags = ip->flags;
178 			vp->func = ip->func;
179 		}
180 	}
181 	/*
182 	 * PS1 depends on uid
183 	 */
184 	if ((vps1.flags & VEXPORT) == 0) {
185 		vpp = hashvar("PS1=");
186 		vps1.next = *vpp;
187 		*vpp = &vps1;
188 		vps1.text = geteuid() ? "PS1=$ " : "PS1=# ";
189 		vps1.flags = VSTRFIXED|VTEXTFIXED;
190 	}
191 }
192 
193 /*
194  * Safe version of setvar, returns 1 on success 0 on failure.
195  */
196 
197 int
198 setvarsafe(name, val, flags)
199 	char *name, *val;
200 	int flags;
201 {
202 	struct jmploc jmploc;
203 	struct jmploc *volatile savehandler = handler;
204 	int err = 0;
205 #if __GNUC__
206 	/* Avoid longjmp clobbering */
207 	(void) &err;
208 #endif
209 
210 	if (setjmp(jmploc.loc))
211 		err = 1;
212 	else {
213 		handler = &jmploc;
214 		setvar(name, val, flags);
215 	}
216 	handler = savehandler;
217 	return err;
218 }
219 
220 /*
221  * Set the value of a variable.  The flags argument is tored with the
222  * flags of the variable.  If val is NULL, the variable is unset.
223  */
224 
225 void
226 setvar(name, val, flags)
227 	char *name, *val;
228 	int flags;
229 {
230 	char *p, *q;
231 	int len;
232 	int namelen;
233 	char *nameeq;
234 	int isbad;
235 
236 	isbad = 0;
237 	p = name;
238 	if (! is_name(*p))
239 		isbad = 1;
240 	p++;
241 	for (;;) {
242 		if (! is_in_name(*p)) {
243 			if (*p == '\0' || *p == '=')
244 				break;
245 			isbad = 1;
246 		}
247 		p++;
248 	}
249 	namelen = p - name;
250 	if (isbad)
251 		error("%.*s: bad variable name", namelen, name);
252 	len = namelen + 2;		/* 2 is space for '=' and '\0' */
253 	if (val == NULL) {
254 		flags |= VUNSET;
255 	} else {
256 		len += strlen(val);
257 	}
258 	p = nameeq = ckmalloc(len);
259 	q = name;
260 	while (--namelen >= 0)
261 		*p++ = *q++;
262 	*p++ = '=';
263 	*p = '\0';
264 	if (val)
265 		scopy(val, p);
266 	setvareq(nameeq, flags);
267 }
268 
269 STATIC int
270 localevar(s)
271 	char *s;
272 	{
273 	static char *lnames[7] = {
274 		"ALL", "COLLATE", "CTYPE", "MONETARY",
275 		"NUMERIC", "TIME", NULL
276 	};
277 	char **ss;
278 
279 	if (*s != 'L')
280 		return 0;
281 	if (varequal(s + 1, "ANG"))
282 		return 1;
283 	if (strncmp(s + 1, "C_", 2) != 0)
284 		return 0;
285 	for (ss = lnames; *ss ; ss++)
286 		if (varequal(s + 3, *ss))
287 			return 1;
288 	return 0;
289 }
290 
291 /*
292  * Same as setvar except that the variable and value are passed in
293  * the first argument as name=value.  Since the first argument will
294  * be actually stored in the table, it should not be a string that
295  * will go away.
296  */
297 
298 void
299 setvareq(s, flags)
300 	char *s;
301 	int flags;
302 {
303 	struct var *vp, **vpp;
304 
305 	if (aflag)
306 		flags |= VEXPORT;
307 	vpp = hashvar(s);
308 	for (vp = *vpp ; vp ; vp = vp->next) {
309 		if (varequal(s, vp->text)) {
310 			if (vp->flags & VREADONLY) {
311 				size_t len = strchr(s, '=') - s;
312 				error("%.*s: is read only", len, s);
313 			}
314 			INTOFF;
315 
316 			if (vp->func && (flags & VNOFUNC) == 0)
317 				(*vp->func)(strchr(s, '=') + 1);
318 
319 			if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
320 				ckfree(vp->text);
321 
322 			vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
323 			vp->flags |= flags;
324 			vp->text = s;
325 
326 			/*
327 			 * We could roll this to a function, to handle it as
328 			 * a regular variable function callback, but why bother?
329 			 */
330 			if (vp == &vmpath || (vp == &vmail && ! mpathset()))
331 				chkmail(1);
332 			if ((vp->flags & VEXPORT) && localevar(s)) {
333 				putenv(s);
334 				(void) setlocale(LC_ALL, "");
335 			}
336 			INTON;
337 			return;
338 		}
339 	}
340 	/* not found */
341 	vp = ckmalloc(sizeof (*vp));
342 	vp->flags = flags;
343 	vp->text = s;
344 	vp->next = *vpp;
345 	vp->func = NULL;
346 	INTOFF;
347 	*vpp = vp;
348 	if ((vp->flags & VEXPORT) && localevar(s)) {
349 		putenv(s);
350 		(void) setlocale(LC_ALL, "");
351 	}
352 	INTON;
353 }
354 
355 
356 
357 /*
358  * Process a linked list of variable assignments.
359  */
360 
361 void
362 listsetvar(list)
363 	struct strlist *list;
364 	{
365 	struct strlist *lp;
366 
367 	INTOFF;
368 	for (lp = list ; lp ; lp = lp->next) {
369 		setvareq(savestr(lp->text), 0);
370 	}
371 	INTON;
372 }
373 
374 
375 
376 /*
377  * Find the value of a variable.  Returns NULL if not set.
378  */
379 
380 char *
381 lookupvar(name)
382 	char *name;
383 	{
384 	struct var *v;
385 
386 	for (v = *hashvar(name) ; v ; v = v->next) {
387 		if (varequal(v->text, name)) {
388 			if (v->flags & VUNSET)
389 				return NULL;
390 			return strchr(v->text, '=') + 1;
391 		}
392 	}
393 	return NULL;
394 }
395 
396 
397 
398 /*
399  * Search the environment of a builtin command.  If the second argument
400  * is nonzero, return the value of a variable even if it hasn't been
401  * exported.
402  */
403 
404 char *
405 bltinlookup(name, doall)
406 	char *name;
407 	int doall;
408 {
409 	struct strlist *sp;
410 	struct var *v;
411 
412 	for (sp = cmdenviron ; sp ; sp = sp->next) {
413 		if (varequal(sp->text, name))
414 			return strchr(sp->text, '=') + 1;
415 	}
416 	for (v = *hashvar(name) ; v ; v = v->next) {
417 		if (varequal(v->text, name)) {
418 			if ((v->flags & VUNSET)
419 			 || (!doall && (v->flags & VEXPORT) == 0))
420 				return NULL;
421 			return strchr(v->text, '=') + 1;
422 		}
423 	}
424 	return NULL;
425 }
426 
427 
428 
429 /*
430  * Generate a list of exported variables.  This routine is used to construct
431  * the third argument to execve when executing a program.
432  */
433 
434 char **
435 environment() {
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
465 MKINIT void shprocvar();
466 
467 SHELLPROC {
468 	shprocvar();
469 }
470 #endif
471 
472 void
473 shprocvar() {
474 	struct var **vpp;
475 	struct var *vp, **prev;
476 
477 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
478 		for (prev = vpp ; (vp = *prev) != NULL ; ) {
479 			if ((vp->flags & VEXPORT) == 0) {
480 				*prev = vp->next;
481 				if ((vp->flags & VTEXTFIXED) == 0)
482 					ckfree(vp->text);
483 				if ((vp->flags & VSTRFIXED) == 0)
484 					ckfree(vp);
485 			} else {
486 				if (vp->flags & VSTACK) {
487 					vp->text = savestr(vp->text);
488 					vp->flags &=~ VSTACK;
489 				}
490 				prev = &vp->next;
491 			}
492 		}
493 	}
494 	initvar();
495 }
496 
497 
498 
499 /*
500  * Command to list all variables which are set.  Currently this command
501  * is invoked from the set command when the set command is called without
502  * any variables.
503  */
504 
505 int
506 showvarscmd(argc, argv)
507 	int argc __unused;
508 	char **argv __unused;
509 {
510 	struct var **vpp;
511 	struct var *vp;
512 
513 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
514 		for (vp = *vpp ; vp ; vp = vp->next) {
515 			if ((vp->flags & VUNSET) == 0)
516 				out1fmt("%s\n", vp->text);
517 		}
518 	}
519 	return 0;
520 }
521 
522 
523 
524 /*
525  * The export and readonly commands.
526  */
527 
528 int
529 exportcmd(argc, argv)
530 	int argc;
531 	char **argv;
532 {
533 	struct var **vpp;
534 	struct var *vp;
535 	char *name;
536 	char *p;
537 	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
538 
539 	listsetvar(cmdenviron);
540 	if (argc > 1) {
541 		while ((name = *argptr++) != NULL) {
542 			if ((p = strchr(name, '=')) != NULL) {
543 				p++;
544 			} else {
545 				vpp = hashvar(name);
546 				for (vp = *vpp ; vp ; vp = vp->next) {
547 					if (varequal(vp->text, name)) {
548 						vp->flags |= flag;
549 						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
550 							putenv(vp->text);
551 							(void) setlocale(LC_ALL, "");
552 						}
553 						goto found;
554 					}
555 				}
556 			}
557 			setvar(name, p, flag);
558 found:;
559 		}
560 	} else {
561 		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
562 			for (vp = *vpp ; vp ; vp = vp->next) {
563 				if (vp->flags & flag) {
564 					for (p = vp->text ; *p != '=' ; p++)
565 						out1c(*p);
566 					out1c('\n');
567 				}
568 			}
569 		}
570 	}
571 	return 0;
572 }
573 
574 
575 /*
576  * The "local" command.
577  */
578 
579 int
580 localcmd(argc, argv)
581 	int argc __unused;
582 	char **argv __unused;
583 {
584 	char *name;
585 
586 	if (! in_function())
587 		error("Not in a function");
588 	while ((name = *argptr++) != NULL) {
589 		mklocal(name);
590 	}
591 	return 0;
592 }
593 
594 
595 /*
596  * Make a variable a local variable.  When a variable is made local, it's
597  * value and flags are saved in a localvar structure.  The saved values
598  * will be restored when the shell function returns.  We handle the name
599  * "-" as a special case.
600  */
601 
602 void
603 mklocal(name)
604 	char *name;
605 	{
606 	struct localvar *lvp;
607 	struct var **vpp;
608 	struct var *vp;
609 
610 	INTOFF;
611 	lvp = ckmalloc(sizeof (struct localvar));
612 	if (name[0] == '-' && name[1] == '\0') {
613 		lvp->text = ckmalloc(sizeof optlist);
614 		memcpy(lvp->text, optlist, sizeof optlist);
615 		vp = NULL;
616 	} else {
617 		vpp = hashvar(name);
618 		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
619 		if (vp == NULL) {
620 			if (strchr(name, '='))
621 				setvareq(savestr(name), VSTRFIXED);
622 			else
623 				setvar(name, NULL, VSTRFIXED);
624 			vp = *vpp;	/* the new variable */
625 			lvp->text = NULL;
626 			lvp->flags = VUNSET;
627 		} else {
628 			lvp->text = vp->text;
629 			lvp->flags = vp->flags;
630 			vp->flags |= VSTRFIXED|VTEXTFIXED;
631 			if (strchr(name, '='))
632 				setvareq(savestr(name), 0);
633 		}
634 	}
635 	lvp->vp = vp;
636 	lvp->next = localvars;
637 	localvars = lvp;
638 	INTON;
639 }
640 
641 
642 /*
643  * Called after a function returns.
644  */
645 
646 void
647 poplocalvars() {
648 	struct localvar *lvp;
649 	struct var *vp;
650 
651 	while ((lvp = localvars) != NULL) {
652 		localvars = lvp->next;
653 		vp = lvp->vp;
654 		if (vp == NULL) {	/* $- saved */
655 			memcpy(optlist, lvp->text, sizeof optlist);
656 			ckfree(lvp->text);
657 		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
658 			(void)unsetvar(vp->text);
659 		} else {
660 			if ((vp->flags & VTEXTFIXED) == 0)
661 				ckfree(vp->text);
662 			vp->flags = lvp->flags;
663 			vp->text = lvp->text;
664 		}
665 		ckfree(lvp);
666 	}
667 }
668 
669 
670 int
671 setvarcmd(argc, argv)
672 	int argc;
673 	char **argv;
674 {
675 	if (argc <= 2)
676 		return unsetcmd(argc, argv);
677 	else if (argc == 3)
678 		setvar(argv[1], argv[2], 0);
679 	else
680 		error("List assignment not implemented");
681 	return 0;
682 }
683 
684 
685 /*
686  * The unset builtin command.  We unset the function before we unset the
687  * variable to allow a function to be unset when there is a readonly variable
688  * with the same name.
689  */
690 
691 int
692 unsetcmd(argc, argv)
693 	int argc __unused;
694 	char **argv __unused;
695 {
696 	char **ap;
697 	int i;
698 	int flg_func = 0;
699 	int flg_var = 0;
700 	int ret = 0;
701 
702 	while ((i = nextopt("vf")) != '\0') {
703 		if (i == 'f')
704 			flg_func = 1;
705 		else
706 			flg_var = 1;
707 	}
708 	if (flg_func == 0 && flg_var == 0)
709 		flg_var = 1;
710 
711 	for (ap = argptr; *ap ; ap++) {
712 		if (flg_func)
713 			ret |= unsetfunc(*ap);
714 		if (flg_var)
715 			ret |= unsetvar(*ap);
716 	}
717 	return ret;
718 }
719 
720 
721 /*
722  * Unset the specified variable.
723  */
724 
725 int
726 unsetvar(s)
727 	char *s;
728 	{
729 	struct var **vpp;
730 	struct var *vp;
731 
732 	vpp = hashvar(s);
733 	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
734 		if (varequal(vp->text, s)) {
735 			if (vp->flags & VREADONLY)
736 				return (1);
737 			INTOFF;
738 			if (*(strchr(vp->text, '=') + 1) != '\0')
739 				setvar(s, nullstr, 0);
740 			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
741 				unsetenv(s);
742 				setlocale(LC_ALL, "");
743 			}
744 			vp->flags &= ~VEXPORT;
745 			vp->flags |= VUNSET;
746 			if ((vp->flags & VSTRFIXED) == 0) {
747 				if ((vp->flags & VTEXTFIXED) == 0)
748 					ckfree(vp->text);
749 				*vpp = vp->next;
750 				ckfree(vp);
751 			}
752 			INTON;
753 			return (0);
754 		}
755 	}
756 
757 	return (1);
758 }
759 
760 
761 
762 /*
763  * Find the appropriate entry in the hash table from the name.
764  */
765 
766 STATIC struct var **
767 hashvar(p)
768 	char *p;
769 	{
770 	unsigned int hashval;
771 
772 	hashval = ((unsigned char) *p) << 4;
773 	while (*p && *p != '=')
774 		hashval += (unsigned char) *p++;
775 	return &vartab[hashval % VTABSIZE];
776 }
777 
778 
779 
780 /*
781  * Returns true if the two strings specify the same varable.  The first
782  * variable name is terminated by '='; the second may be terminated by
783  * either '=' or '\0'.
784  */
785 
786 STATIC int
787 varequal(p, q)
788 	char *p, *q;
789 	{
790 	while (*p == *q++) {
791 		if (*p++ == '=')
792 			return 1;
793 	}
794 	if (*p == '=' && *(q - 1) == '\0')
795 		return 1;
796 	return 0;
797 }
798