xref: /dragonfly/bin/sh/var.c (revision d5f516c3)
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  * @(#)var.c	8.3 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/var.c,v 1.15.2.2 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/var.c,v 1.7 2004/11/07 20:54:52 eirikn Exp $
39  */
40 
41 #include <unistd.h>
42 #include <stdlib.h>
43 
44 /*
45  * Shell variables.
46  */
47 
48 #include <locale.h>
49 
50 #include "shell.h"
51 #include "output.h"
52 #include "expand.h"
53 #include "nodes.h"	/* for other headers */
54 #include "eval.h"	/* defines cmdenviron */
55 #include "exec.h"
56 #include "syntax.h"
57 #include "options.h"
58 #include "mail.h"
59 #include "var.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "mystring.h"
63 #include "parser.h"
64 #ifndef NO_HISTORY
65 #include "myhistedit.h"
66 #endif
67 
68 
69 #define VTABSIZE 39
70 
71 
72 struct varinit {
73 	struct var *var;
74 	int flags;
75 	const char *text;
76 	void (*func)(const char *);
77 };
78 
79 
80 #ifndef NO_HISTORY
81 struct var vhistsize;
82 #endif
83 struct var vifs;
84 struct var vmail;
85 struct var vmpath;
86 struct var vpath;
87 struct var vppid;
88 struct var vps1;
89 struct var vps2;
90 struct var vvers;
91 STATIC struct var voptind;
92 
93 STATIC const struct varinit varinit[] = {
94 #ifndef NO_HISTORY
95 	{ &vhistsize,	VSTRFIXED|VTEXTFIXED|VUNSET,	"HISTSIZE=",
96 	  sethistsize },
97 #endif
98 	{ &vifs,	VSTRFIXED|VTEXTFIXED,		"IFS= \t\n",
99 	  NULL },
100 	{ &vmail,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAIL=",
101 	  NULL },
102 	{ &vmpath,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAILPATH=",
103 	  NULL },
104 	{ &vpath,	VSTRFIXED|VTEXTFIXED,		"PATH=/bin:/usr/bin",
105 	  changepath },
106 	{ &vppid,	VSTRFIXED|VTEXTFIXED|VUNSET,	"PPID=",
107 	  NULL },
108 	/*
109 	 * vps1 depends on uid
110 	 */
111 	{ &vps2,	VSTRFIXED|VTEXTFIXED,		"PS2=> ",
112 	  NULL },
113 	{ &voptind,	VSTRFIXED|VTEXTFIXED,		"OPTIND=1",
114 	  getoptsreset },
115 	{ NULL,	0,				NULL,
116 	  NULL }
117 };
118 
119 STATIC struct var *vartab[VTABSIZE];
120 
121 STATIC struct var **hashvar(const char *);
122 STATIC int varequal(const char *, const char *);
123 STATIC int localevar(const char *);
124 
125 /*
126  * Initialize the variable symbol tables and import the environment.
127  */
128 
129 #ifdef mkinit
130 INCLUDE "var.h"
131 INIT {
132 	char **envp;
133 	extern char **environ;
134 
135 	initvar();
136 	for (envp = environ ; *envp ; envp++) {
137 		if (strchr(*envp, '=')) {
138 			setvareq(*envp, VEXPORT|VTEXTFIXED);
139 		}
140 	}
141 }
142 #endif
143 
144 
145 /*
146  * This routine initializes the builtin variables.  It is called when the
147  * shell is initialized and again when a shell procedure is spawned.
148  */
149 
150 void
151 initvar(void)
152 {
153 	char ppid[20];
154 	const struct varinit *ip;
155 	struct var *vp;
156 	struct var **vpp;
157 
158 	for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
159 		if ((vp->flags & VEXPORT) == 0) {
160 			vpp = hashvar(ip->text);
161 			vp->next = *vpp;
162 			*vpp = vp;
163 			vp->text = ip->text;
164 			vp->flags = ip->flags;
165 			vp->func = ip->func;
166 		}
167 	}
168 	/*
169 	 * PS1 depends on uid
170 	 */
171 	if ((vps1.flags & VEXPORT) == 0) {
172 		vpp = hashvar("PS1=");
173 		vps1.next = *vpp;
174 		*vpp = &vps1;
175 		vps1.text = geteuid() ? "PS1=$ " : "PS1=# ";
176 		vps1.flags = VSTRFIXED|VTEXTFIXED;
177 	}
178 	if ((vppid.flags & VEXPORT) == 0) {
179 		fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
180 		setvarsafe("PPID", ppid, 0);
181 	}
182 }
183 
184 /*
185  * Safe version of setvar, returns 1 on success 0 on failure.
186  */
187 
188 int
189 setvarsafe(const char *name, const char *val, int flags)
190 {
191 	struct jmploc jmploc;
192 	struct jmploc *volatile savehandler = handler;
193 	int err = 0;
194 #if __GNUC__
195 	/* Avoid longjmp clobbering */
196 	(void) &err;
197 #endif
198 
199 	if (setjmp(jmploc.loc))
200 		err = 1;
201 	else {
202 		handler = &jmploc;
203 		setvar(name, val, flags);
204 	}
205 	handler = savehandler;
206 	return err;
207 }
208 
209 /*
210  * Set the value of a variable.  The flags argument is tored with the
211  * flags of the variable.  If val is NULL, the variable is unset.
212  */
213 
214 void
215 setvar(const char *name, const char *val, int flags)
216 {
217 	const char *cp;
218 	char *p;
219 	int len;
220 	int namelen;
221 	char *nameeq;
222 	int isbad;
223 
224 	isbad = 0;
225 	cp = name;
226 	if (!is_name(*cp))
227 		isbad = 1;
228 	cp++;
229 	for (;;) {
230 		if (!is_in_name(*cp)) {
231 			if (*cp == '\0' || *cp == '=')
232 				break;
233 			isbad = 1;
234 		}
235 		cp++;
236 	}
237 	namelen = cp - 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 	cp = name;
248 	while (--namelen >= 0)
249 		*p++ = *cp++;
250 	*p++ = '=';
251 	*p = '\0';
252 	if (val)
253 		scopy(val, p);
254 	setvareq(nameeq, flags);
255 }
256 
257 STATIC int
258 localevar(const char *s)
259 {
260 	static const char * const lnames[7] = {
261 		"ALL", "COLLATE", "CTYPE", "MONETARY",
262 		"NUMERIC", "TIME", NULL
263 	};
264 	const char * const *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 				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 		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(const 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(const 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 	listsetvar(cmdenviron);
545 	if (argc != 0) {
546 		while ((name = *argptr++) != NULL) {
547 			if ((p = strchr(name, '=')) != NULL) {
548 				p++;
549 			} else {
550 				vpp = hashvar(name);
551 				for (vp = *vpp ; vp ; vp = vp->next) {
552 					if (varequal(vp->text, name)) {
553 
554 						vp->flags |= flag;
555 						if ((vp->flags & VEXPORT) && localevar(vp->text)) {
556 							putenv(vp->text);
557 							setlocale(LC_ALL, "");
558 						}
559 						goto found;
560 					}
561 				}
562 			}
563 			setvar(name, p, flag);
564 found:;
565 		}
566 	} else {
567 		for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
568 			for (vp = *vpp ; vp ; vp = vp->next) {
569 				if (vp->flags & flag) {
570 					if (values) {
571 						out1str(cmdname);
572 						out1c(' ');
573 					}
574 					for (p = vp->text ; *p != '=' ; p++)
575 						out1c(*p);
576 					if (values && !(vp->flags & VUNSET)) {
577 						out1c('=');
578 						out1qstr(p + 1);
579 					}
580 					out1c('\n');
581 				}
582 			}
583 		}
584 	}
585 	return 0;
586 }
587 
588 
589 /*
590  * The "local" command.
591  */
592 
593 int
594 localcmd(int argc __unused, char **argv __unused)
595 {
596 	char *name;
597 
598 	if (! in_function())
599 		error("Not in a function");
600 	while ((name = *argptr++) != NULL) {
601 		mklocal(name);
602 	}
603 	return 0;
604 }
605 
606 
607 /*
608  * Make a variable a local variable.  When a variable is made local, it's
609  * value and flags are saved in a localvar structure.  The saved values
610  * will be restored when the shell function returns.  We handle the name
611  * "-" as a special case.
612  */
613 
614 void
615 mklocal(char *name)
616 {
617 	struct localvar *lvp;
618 	struct var **vpp;
619 	struct var *vp;
620 
621 	INTOFF;
622 	lvp = ckmalloc(sizeof (struct localvar));
623 	if (name[0] == '-' && name[1] == '\0') {
624 		lvp->text = ckmalloc(sizeof optlist);
625 		memcpy(lvp->text, optlist, sizeof optlist);
626 		vp = NULL;
627 	} else {
628 		vpp = hashvar(name);
629 		for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
630 		if (vp == NULL) {
631 			if (strchr(name, '='))
632 				setvareq(savestr(name), VSTRFIXED);
633 			else
634 				setvar(name, NULL, VSTRFIXED);
635 			vp = *vpp;	/* the new variable */
636 			lvp->text = NULL;
637 			lvp->flags = VUNSET;
638 		} else {
639 			lvp->text = vp->text;
640 			lvp->flags = vp->flags;
641 			vp->flags |= VSTRFIXED|VTEXTFIXED;
642 			if (strchr(name, '='))
643 				setvareq(savestr(name), 0);
644 		}
645 	}
646 	lvp->vp = vp;
647 	lvp->next = localvars;
648 	localvars = lvp;
649 	INTON;
650 }
651 
652 
653 /*
654  * Called after a function returns.
655  */
656 
657 void
658 poplocalvars(void)
659 {
660 	struct localvar *lvp;
661 	struct var *vp;
662 
663 	while ((lvp = localvars) != NULL) {
664 		localvars = lvp->next;
665 		vp = lvp->vp;
666 		if (vp == NULL) {	/* $- saved */
667 			memcpy(optlist, lvp->text, sizeof optlist);
668 			ckfree(lvp->text);
669 		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
670 			unsetvar(vp->text);
671 		} else {
672 			if ((vp->flags & VTEXTFIXED) == 0)
673 				ckfree(vp->text);
674 			vp->flags = lvp->flags;
675 			vp->text = lvp->text;
676 		}
677 		ckfree(lvp);
678 	}
679 }
680 
681 
682 int
683 setvarcmd(int argc, char **argv)
684 {
685 	if (argc <= 2)
686 		return unsetcmd(argc, argv);
687 	else if (argc == 3)
688 		setvar(argv[1], argv[2], 0);
689 	else
690 		error("List assignment not implemented");
691 	return 0;
692 }
693 
694 
695 /*
696  * The unset builtin command.  We unset the function before we unset the
697  * variable to allow a function to be unset when there is a readonly variable
698  * with the same name.
699  */
700 
701 int
702 unsetcmd(int argc __unused, char **argv __unused)
703 {
704 	char **ap;
705 	int i;
706 	int flg_func = 0;
707 	int flg_var = 0;
708 	int ret = 0;
709 
710 	while ((i = nextopt("vf")) != '\0') {
711 		if (i == 'f')
712 			flg_func = 1;
713 		else
714 			flg_var = 1;
715 	}
716 	if (flg_func == 0 && flg_var == 0)
717 		flg_var = 1;
718 
719 	for (ap = argptr; *ap ; ap++) {
720 		if (flg_func)
721 			ret |= unsetfunc(*ap);
722 		if (flg_var)
723 			ret |= unsetvar(*ap);
724 	}
725 	return ret;
726 }
727 
728 
729 /*
730  * Unset the specified variable.
731  */
732 
733 int
734 unsetvar(const char *s)
735 {
736 	struct var **vpp;
737 	struct var *vp;
738 
739 	vpp = hashvar(s);
740 	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
741 		if (varequal(vp->text, s)) {
742 			if (vp->flags & VREADONLY)
743 				return (1);
744 			INTOFF;
745 			if (*(strchr(vp->text, '=') + 1) != '\0')
746 				setvar(s, nullstr, 0);
747 			if ((vp->flags & VEXPORT) && localevar(vp->text)) {
748 				unsetenv(s);
749 				setlocale(LC_ALL, "");
750 			}
751 			vp->flags &= ~VEXPORT;
752 			vp->flags |= VUNSET;
753 			if ((vp->flags & VSTRFIXED) == 0) {
754 				if ((vp->flags & VTEXTFIXED) == 0)
755 					ckfree(vp->text);
756 				*vpp = vp->next;
757 				ckfree(vp);
758 			}
759 			INTON;
760 			return (0);
761 		}
762 	}
763 	return (0);
764 }
765 
766 
767 
768 /*
769  * Find the appropriate entry in the hash table from the name.
770  */
771 
772 STATIC struct var **
773 hashvar(const char *p)
774 {
775 	unsigned int hashval;
776 
777 	hashval = ((unsigned char) *p) << 4;
778 	while (*p && *p != '=')
779 		hashval += (unsigned char) *p++;
780 	return &vartab[hashval % VTABSIZE];
781 }
782 
783 
784 
785 /*
786  * Returns true if the two strings specify the same varable.  The first
787  * variable name is terminated by '='; the second may be terminated by
788  * either '=' or '\0'.
789  */
790 
791 STATIC int
792 varequal(const char *p, const char *q)
793 {
794 	while (*p == *q++) {
795 		if (*p++ == '=')
796 			return 1;
797 	}
798 	if (*p == '=' && *(q - 1) == '\0')
799 		return 1;
800 	return 0;
801 }
802