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