xref: /freebsd/bin/sh/var.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
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 #endif /* not lint */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
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)(const char *);
81 };
82 
83 
84 #ifndef NO_HISTORY
85 struct var vhistsize;
86 #endif
87 struct var vifs;
88 struct var vmail;
89 struct var vmpath;
90 struct var vpath;
91 struct var vppid;
92 struct var vps1;
93 struct var vps2;
94 struct var vvers;
95 struct var voptind;
96 
97 const struct varinit varinit[] = {
98 #ifndef NO_HISTORY
99 	{ &vhistsize,	VSTRFIXED|VTEXTFIXED|VUNSET,	"HISTSIZE=",
100 	  sethistsize },
101 #endif
102 	{ &vifs,	VSTRFIXED|VTEXTFIXED,		"IFS= \t\n",
103 	  NULL },
104 	{ &vmail,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAIL=",
105 	  NULL },
106 	{ &vmpath,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAILPATH=",
107 	  NULL },
108 	{ &vpath,	VSTRFIXED|VTEXTFIXED,		"PATH=/bin:/usr/bin",
109 	  changepath },
110 	{ &vppid,	VSTRFIXED|VTEXTFIXED|VUNSET,	"PPID=",
111 	  NULL },
112 	/*
113 	 * vps1 depends on uid
114 	 */
115 	{ &vps2,	VSTRFIXED|VTEXTFIXED,		"PS2=> ",
116 	  NULL },
117 	{ &voptind,	VSTRFIXED|VTEXTFIXED,		"OPTIND=1",
118 	  getoptsreset },
119 	{ NULL,	0,				NULL,
120 	  NULL }
121 };
122 
123 struct var *vartab[VTABSIZE];
124 
125 STATIC struct var **hashvar(char *);
126 STATIC int varequal(char *, char *);
127 STATIC int localevar(char *);
128 
129 /*
130  * Initialize the varable symbol tables and import the environment
131  */
132 
133 #ifdef mkinit
134 INCLUDE "var.h"
135 INIT {
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 
154 void
155 initvar(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 
192 int
193 setvarsafe(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 tored with the
215  * flags of the variable.  If val is NULL, the variable is unset.
216  */
217 
218 void
219 setvar(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 
260 STATIC int
261 localevar(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 
288 void
289 setvareq(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 				putenv(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 		putenv(s);
339 		(void) setlocale(LC_ALL, "");
340 	}
341 	INTON;
342 }
343 
344 
345 
346 /*
347  * Process a linked list of variable assignments.
348  */
349 
350 void
351 listsetvar(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 
368 char *
369 lookupvar(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 
391 char *
392 bltinlookup(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 
419 char **
420 environment(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
451 MKINIT void shprocvar();
452 
453 SHELLPROC {
454 	shprocvar();
455 }
456 #endif
457 
458 void
459 shprocvar(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 
485 
486 /*
487  * Command to list all variables which are set.  Currently this command
488  * is invoked from the set command when the set command is called without
489  * any variables.
490  */
491 
492 int
493 showvarscmd(int argc __unused, char **argv __unused)
494 {
495 	struct var **vpp;
496 	struct var *vp;
497 	const char *s;
498 
499 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
500 		for (vp = *vpp ; vp ; vp = vp->next) {
501 			if (vp->flags & VUNSET)
502 				continue;
503 			for (s = vp->text; *s != '='; s++)
504 				out1c(*s);
505 			out1c('=');
506 			out1qstr(s + 1);
507 			out1c('\n');
508 		}
509 	}
510 	return 0;
511 }
512 
513 
514 
515 /*
516  * The export and readonly commands.
517  */
518 
519 int
520 exportcmd(int argc, char **argv)
521 {
522 	struct var **vpp;
523 	struct var *vp;
524 	char *name;
525 	char *p;
526 	char *cmdname;
527 	int ch, values;
528 	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
529 
530 	cmdname = argv[0];
531 	optreset = optind = 1;
532 	opterr = 0;
533 	values = 0;
534 	while ((ch = getopt(argc, argv, "p")) != -1) {
535 		switch (ch) {
536 		case 'p':
537 			values = 1;
538 			break;
539 		case '?':
540 		default:
541 			error("unknown option: -%c", optopt);
542 		}
543 	}
544 	argc -= optind;
545 	argv += optind;
546 
547 	listsetvar(cmdenviron);
548 	if (argc != 0) {
549 		while ((name = *argptr++) != NULL) {
550 			if ((p = strchr(name, '=')) != NULL) {
551 				p++;
552 			} else {
553 				vpp = hashvar(name);
554 				for (vp = *vpp ; vp ; vp = vp->next) {
555 					if (varequal(vp->text, name)) {
556 
557 						vp->flags |= flag;
558 						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
559 							putenv(vp->text);
560 							(void) setlocale(LC_ALL, "");
561 						}
562 						goto found;
563 					}
564 				}
565 			}
566 			setvar(name, p, flag);
567 found:;
568 		}
569 	} else {
570 		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
571 			for (vp = *vpp ; vp ; vp = vp->next) {
572 				if (vp->flags & flag) {
573 					if (values) {
574 						out1str(cmdname);
575 						out1c(' ');
576 					}
577 					for (p = vp->text ; *p != '=' ; p++)
578 						out1c(*p);
579 					if (values && !(vp->flags & VUNSET)) {
580 						out1c('=');
581 						out1qstr(p + 1);
582 					}
583 					out1c('\n');
584 				}
585 			}
586 		}
587 	}
588 	return 0;
589 }
590 
591 
592 /*
593  * The "local" command.
594  */
595 
596 int
597 localcmd(int argc __unused, char **argv __unused)
598 {
599 	char *name;
600 
601 	if (! in_function())
602 		error("Not in a function");
603 	while ((name = *argptr++) != NULL) {
604 		mklocal(name);
605 	}
606 	return 0;
607 }
608 
609 
610 /*
611  * Make a variable a local variable.  When a variable is made local, it's
612  * value and flags are saved in a localvar structure.  The saved values
613  * will be restored when the shell function returns.  We handle the name
614  * "-" as a special case.
615  */
616 
617 void
618 mklocal(char *name)
619 {
620 	struct localvar *lvp;
621 	struct var **vpp;
622 	struct var *vp;
623 
624 	INTOFF;
625 	lvp = ckmalloc(sizeof (struct localvar));
626 	if (name[0] == '-' && name[1] == '\0') {
627 		lvp->text = ckmalloc(sizeof optlist);
628 		memcpy(lvp->text, optlist, sizeof optlist);
629 		vp = NULL;
630 	} else {
631 		vpp = hashvar(name);
632 		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
633 		if (vp == NULL) {
634 			if (strchr(name, '='))
635 				setvareq(savestr(name), VSTRFIXED);
636 			else
637 				setvar(name, NULL, VSTRFIXED);
638 			vp = *vpp;	/* the new variable */
639 			lvp->text = NULL;
640 			lvp->flags = VUNSET;
641 		} else {
642 			lvp->text = vp->text;
643 			lvp->flags = vp->flags;
644 			vp->flags |= VSTRFIXED|VTEXTFIXED;
645 			if (strchr(name, '='))
646 				setvareq(savestr(name), 0);
647 		}
648 	}
649 	lvp->vp = vp;
650 	lvp->next = localvars;
651 	localvars = lvp;
652 	INTON;
653 }
654 
655 
656 /*
657  * Called after a function returns.
658  */
659 
660 void
661 poplocalvars(void)
662 {
663 	struct localvar *lvp;
664 	struct var *vp;
665 
666 	while ((lvp = localvars) != NULL) {
667 		localvars = lvp->next;
668 		vp = lvp->vp;
669 		if (vp == NULL) {	/* $- saved */
670 			memcpy(optlist, lvp->text, sizeof optlist);
671 			ckfree(lvp->text);
672 		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
673 			(void)unsetvar(vp->text);
674 		} else {
675 			if ((vp->flags & VTEXTFIXED) == 0)
676 				ckfree(vp->text);
677 			vp->flags = lvp->flags;
678 			vp->text = lvp->text;
679 		}
680 		ckfree(lvp);
681 	}
682 }
683 
684 
685 int
686 setvarcmd(int argc, char **argv)
687 {
688 	if (argc <= 2)
689 		return unsetcmd(argc, argv);
690 	else if (argc == 3)
691 		setvar(argv[1], argv[2], 0);
692 	else
693 		error("List assignment not implemented");
694 	return 0;
695 }
696 
697 
698 /*
699  * The unset builtin command.  We unset the function before we unset the
700  * variable to allow a function to be unset when there is a readonly variable
701  * with the same name.
702  */
703 
704 int
705 unsetcmd(int argc __unused, char **argv __unused)
706 {
707 	char **ap;
708 	int i;
709 	int flg_func = 0;
710 	int flg_var = 0;
711 	int ret = 0;
712 
713 	while ((i = nextopt("vf")) != '\0') {
714 		if (i == 'f')
715 			flg_func = 1;
716 		else
717 			flg_var = 1;
718 	}
719 	if (flg_func == 0 && flg_var == 0)
720 		flg_var = 1;
721 
722 	for (ap = argptr; *ap ; ap++) {
723 		if (flg_func)
724 			ret |= unsetfunc(*ap);
725 		if (flg_var)
726 			ret |= unsetvar(*ap);
727 	}
728 	return ret;
729 }
730 
731 
732 /*
733  * Unset the specified variable.
734  */
735 
736 int
737 unsetvar(char *s)
738 {
739 	struct var **vpp;
740 	struct var *vp;
741 
742 	vpp = hashvar(s);
743 	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
744 		if (varequal(vp->text, s)) {
745 			if (vp->flags & VREADONLY)
746 				return (1);
747 			INTOFF;
748 			if (*(strchr(vp->text, '=') + 1) != '\0')
749 				setvar(s, nullstr, 0);
750 			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
751 				unsetenv(s);
752 				setlocale(LC_ALL, "");
753 			}
754 			vp->flags &= ~VEXPORT;
755 			vp->flags |= VUNSET;
756 			if ((vp->flags & VSTRFIXED) == 0) {
757 				if ((vp->flags & VTEXTFIXED) == 0)
758 					ckfree(vp->text);
759 				*vpp = vp->next;
760 				ckfree(vp);
761 			}
762 			INTON;
763 			return (0);
764 		}
765 	}
766 
767 	return (1);
768 }
769 
770 
771 
772 /*
773  * Find the appropriate entry in the hash table from the name.
774  */
775 
776 STATIC struct var **
777 hashvar(char *p)
778 {
779 	unsigned int hashval;
780 
781 	hashval = ((unsigned char) *p) << 4;
782 	while (*p && *p != '=')
783 		hashval += (unsigned char) *p++;
784 	return &vartab[hashval % VTABSIZE];
785 }
786 
787 
788 
789 /*
790  * Returns true if the two strings specify the same varable.  The first
791  * variable name is terminated by '='; the second may be terminated by
792  * either '=' or '\0'.
793  */
794 
795 STATIC int
796 varequal(char *p, char *q)
797 {
798 	while (*p == *q++) {
799 		if (*p++ == '=')
800 			return 1;
801 	}
802 	if (*p == '=' && *(q - 1) == '\0')
803 		return 1;
804 	return 0;
805 }
806