var.c revision 1.32 1 /* $NetBSD: var.c,v 1.32 2003/01/22 20:36:04 dsl Exp $ */
2
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 5/4/95";
43 #else
44 __RCSID("$NetBSD: var.c,v 1.32 2003/01/22 20:36:04 dsl Exp $");
45 #endif
46 #endif /* not lint */
47
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <paths.h>
51
52 /*
53 * Shell variables.
54 */
55
56 #include "shell.h"
57 #include "output.h"
58 #include "expand.h"
59 #include "nodes.h" /* for other headers */
60 #include "eval.h" /* defines cmdenviron */
61 #include "exec.h"
62 #include "syntax.h"
63 #include "options.h"
64 #include "mail.h"
65 #include "var.h"
66 #include "memalloc.h"
67 #include "error.h"
68 #include "mystring.h"
69 #include "parser.h"
70 #include "show.h"
71 #ifndef SMALL
72 #include "myhistedit.h"
73 #endif
74
75
76 #define VTABSIZE 39
77
78
79 struct varinit {
80 struct var *var;
81 int flags;
82 const char *text;
83 void (*func)(const char *);
84 };
85
86
87 #if ATTY
88 struct var vatty;
89 #endif
90 #ifndef SMALL
91 struct var vhistsize;
92 struct var vterm;
93 #endif
94 struct var vifs;
95 struct var vmail;
96 struct var vmpath;
97 struct var vpath;
98 struct var vps1;
99 struct var vps2;
100 struct var vps4;
101 struct var vvers;
102 struct var voptind;
103
104 const struct varinit varinit[] = {
105 #if ATTY
106 { &vatty, VSTRFIXED|VTEXTFIXED|VUNSET, "ATTY=",
107 NULL },
108 #endif
109 #ifndef SMALL
110 { &vhistsize, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE=",
111 sethistsize },
112 #endif
113 { &vifs, VSTRFIXED|VTEXTFIXED, "IFS= \t\n",
114 NULL },
115 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
116 NULL },
117 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
118 NULL },
119 { &vpath, VSTRFIXED|VTEXTFIXED, "PATH=" _PATH_DEFPATH,
120 changepath },
121 /*
122 * vps1 depends on uid
123 */
124 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
125 NULL },
126 { &vps4, VSTRFIXED|VTEXTFIXED, "PS4=+ ",
127 NULL },
128 #ifndef SMALL
129 { &vterm, VSTRFIXED|VTEXTFIXED|VUNSET, "TERM=",
130 setterm },
131 #endif
132 { &voptind, VSTRFIXED|VTEXTFIXED|VNOFUNC, "OPTIND=1",
133 getoptsreset },
134 { NULL, 0, NULL,
135 NULL }
136 };
137
138 struct var *vartab[VTABSIZE];
139
140 STATIC struct var **hashvar(const char *);
141 STATIC int varequal(const char *, const char *);
142
143 /*
144 * Initialize the varable symbol tables and import the environment
145 */
146
147 #ifdef mkinit
148 INCLUDE "var.h"
149 MKINIT char **environ;
150 INIT {
151 char **envp;
152
153 initvar();
154 for (envp = environ ; *envp ; envp++) {
155 if (strchr(*envp, '=')) {
156 setvareq(*envp, VEXPORT|VTEXTFIXED);
157 }
158 }
159 }
160 #endif
161
162
163 /*
164 * This routine initializes the builtin variables. It is called when the
165 * shell is initialized and again when a shell procedure is spawned.
166 */
167
168 void
169 initvar(void)
170 {
171 const struct varinit *ip;
172 struct var *vp;
173 struct var **vpp;
174
175 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
176 if ((vp->flags & VEXPORT) == 0) {
177 vpp = hashvar(ip->text);
178 vp->next = *vpp;
179 *vpp = vp;
180 vp->text = strdup(ip->text);
181 vp->flags = ip->flags;
182 vp->func = ip->func;
183 }
184 }
185 /*
186 * PS1 depends on uid
187 */
188 if ((vps1.flags & VEXPORT) == 0) {
189 vpp = hashvar("PS1=");
190 vps1.next = *vpp;
191 *vpp = &vps1;
192 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
193 vps1.flags = VSTRFIXED|VTEXTFIXED;
194 }
195 }
196
197 /*
198 * Safe version of setvar, returns 1 on success 0 on failure.
199 */
200
201 int
202 setvarsafe(const char *name, const char *val, int flags)
203 {
204 struct jmploc jmploc;
205 struct jmploc *volatile savehandler = handler;
206 int err = 0;
207 #ifdef __GNUC__
208 (void) &err;
209 #endif
210
211 if (setjmp(jmploc.loc))
212 err = 1;
213 else {
214 handler = &jmploc;
215 setvar(name, val, flags);
216 }
217 handler = savehandler;
218 return err;
219 }
220
221 /*
222 * Set the value of a variable. The flags argument is ored with the
223 * flags of the variable. If val is NULL, the variable is unset.
224 */
225
226 void
227 setvar(const char *name, const char *val, int flags)
228 {
229 const char *p;
230 const char *q;
231 char *d;
232 int len;
233 int namelen;
234 char *nameeq;
235 int isbad;
236
237 isbad = 0;
238 p = name;
239 if (! is_name(*p))
240 isbad = 1;
241 p++;
242 for (;;) {
243 if (! is_in_name(*p)) {
244 if (*p == '\0' || *p == '=')
245 break;
246 isbad = 1;
247 }
248 p++;
249 }
250 namelen = p - name;
251 if (isbad)
252 error("%.*s: bad variable name", namelen, name);
253 len = namelen + 2; /* 2 is space for '=' and '\0' */
254 if (val == NULL) {
255 flags |= VUNSET;
256 } else {
257 len += strlen(val);
258 }
259 d = nameeq = ckmalloc(len);
260 q = name;
261 while (--namelen >= 0)
262 *d++ = *q++;
263 *d++ = '=';
264 *d = '\0';
265 if (val)
266 scopy(val, d);
267 setvareq(nameeq, flags);
268 }
269
270
271
272 /*
273 * Same as setvar except that the variable and value are passed in
274 * the first argument as name=value. Since the first argument will
275 * be actually stored in the table, it should not be a string that
276 * will go away.
277 */
278
279 void
280 setvareq(char *s, int flags)
281 {
282 struct var *vp, **vpp;
283
284 if (aflag)
285 flags |= VEXPORT;
286 vpp = hashvar(s);
287 for (vp = *vpp ; vp ; vp = vp->next) {
288 if (varequal(s, vp->text)) {
289 if (vp->flags & VREADONLY) {
290 size_t len = strchr(s, '=') - s;
291 error("%.*s: is read only", len, s);
292 }
293 if (flags & VNOSET)
294 return;
295 INTOFF;
296
297 if (vp->func && (flags & VNOFUNC) == 0)
298 (*vp->func)(strchr(s, '=') + 1);
299
300 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
301 ckfree(vp->text);
302
303 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
304 vp->flags |= flags & ~VNOFUNC;
305 vp->text = s;
306
307 /*
308 * We could roll this to a function, to handle it as
309 * a regular variable function callback, but why bother?
310 */
311 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
312 chkmail(1);
313 INTON;
314 return;
315 }
316 }
317 /* not found */
318 if (flags & VNOSET)
319 return;
320 vp = ckmalloc(sizeof (*vp));
321 vp->flags = flags & ~VNOFUNC;
322 vp->text = s;
323 vp->next = *vpp;
324 vp->func = NULL;
325 *vpp = vp;
326 }
327
328
329
330 /*
331 * Process a linked list of variable assignments.
332 */
333
334 void
335 listsetvar(struct strlist *list, int flags)
336 {
337 struct strlist *lp;
338
339 INTOFF;
340 for (lp = list ; lp ; lp = lp->next) {
341 setvareq(savestr(lp->text), flags);
342 }
343 INTON;
344 }
345
346 void
347 listmklocal(struct strlist *list, int flags)
348 {
349 struct strlist *lp;
350
351 for (lp = list ; lp ; lp = lp->next)
352 mklocal(lp->text, flags);
353 }
354
355
356 /*
357 * Find the value of a variable. Returns NULL if not set.
358 */
359
360 char *
361 lookupvar(const char *name)
362 {
363 struct var *v;
364
365 for (v = *hashvar(name) ; v ; v = v->next) {
366 if (varequal(v->text, name)) {
367 if (v->flags & VUNSET)
368 return NULL;
369 return strchr(v->text, '=') + 1;
370 }
371 }
372 return NULL;
373 }
374
375
376
377 /*
378 * Search the environment of a builtin command. If the second argument
379 * is nonzero, return the value of a variable even if it hasn't been
380 * exported.
381 */
382
383 char *
384 bltinlookup(const char *name, int doall)
385 {
386 struct strlist *sp;
387 struct var *v;
388
389 for (sp = cmdenviron ; sp ; sp = sp->next) {
390 if (varequal(sp->text, name))
391 return strchr(sp->text, '=') + 1;
392 }
393 for (v = *hashvar(name) ; v ; v = v->next) {
394 if (varequal(v->text, name)) {
395 if ((v->flags & VUNSET)
396 || (!doall && (v->flags & VEXPORT) == 0))
397 return NULL;
398 return strchr(v->text, '=') + 1;
399 }
400 }
401 return NULL;
402 }
403
404
405
406 /*
407 * Generate a list of exported variables. This routine is used to construct
408 * the third argument to execve when executing a program.
409 */
410
411 char **
412 environment(void)
413 {
414 int nenv;
415 struct var **vpp;
416 struct var *vp;
417 char **env;
418 char **ep;
419
420 nenv = 0;
421 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
422 for (vp = *vpp ; vp ; vp = vp->next)
423 if (vp->flags & VEXPORT)
424 nenv++;
425 }
426 ep = env = stalloc((nenv + 1) * sizeof *env);
427 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
428 for (vp = *vpp ; vp ; vp = vp->next)
429 if (vp->flags & VEXPORT)
430 *ep++ = vp->text;
431 }
432 *ep = NULL;
433 return env;
434 }
435
436
437 /*
438 * Called when a shell procedure is invoked to clear out nonexported
439 * variables. It is also necessary to reallocate variables of with
440 * VSTACK set since these are currently allocated on the stack.
441 */
442
443 #ifdef mkinit
444 void shprocvar(void);
445
446 SHELLPROC {
447 shprocvar();
448 }
449 #endif
450
451 void
452 shprocvar(void)
453 {
454 struct var **vpp;
455 struct var *vp, **prev;
456
457 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
458 for (prev = vpp ; (vp = *prev) != NULL ; ) {
459 if ((vp->flags & VEXPORT) == 0) {
460 *prev = vp->next;
461 if ((vp->flags & VTEXTFIXED) == 0)
462 ckfree(vp->text);
463 if ((vp->flags & VSTRFIXED) == 0)
464 ckfree(vp);
465 } else {
466 if (vp->flags & VSTACK) {
467 vp->text = savestr(vp->text);
468 vp->flags &=~ VSTACK;
469 }
470 prev = &vp->next;
471 }
472 }
473 }
474 initvar();
475 }
476
477
478
479 /*
480 * Command to list all variables which are set. Currently this command
481 * is invoked from the set command when the set command is called without
482 * any variables.
483 */
484
485 void
486 print_quoted(const char *p)
487 {
488 const char *q;
489
490 if (strcspn(p, "|&;<>()$`\\\"' \t\n*?[]#~=%") == strlen(p)) {
491 out1fmt("%s", p);
492 return;
493 }
494 while (*p) {
495 if (*p == '\'') {
496 out1fmt("\\'");
497 p++;
498 continue;
499 }
500 q = index(p, '\'');
501 if (!q) {
502 out1fmt("'%s'", p );
503 return;
504 }
505 out1fmt("'%.*s'", (int)(q - p), p );
506 p = q;
507 }
508 }
509
510 static int
511 sort_var(const void *v_v1, const void *v_v2)
512 {
513 const struct var * const *v1 = v_v1;
514 const struct var * const *v2 = v_v2;
515
516 /* XXX Will anyone notice we include the '=' of the shorter name? */
517 return strcoll((*v1)->text, (*v2)->text);
518 }
519
520 /*
521 * POSIX requires that 'set' (but not export or readonly) output the
522 * variables in lexicographic order - by the locale's collating order (sigh).
523 * Maybe we could keep them in an ordered balanced binary tree
524 * instead of hashed lists.
525 * For now just roll 'em through qsort for printing...
526 */
527
528 int
529 showvars(const char *name, int flag, int show_value)
530 {
531 struct var **vpp;
532 struct var *vp;
533 const char *p;
534
535 static struct var **list; /* static in case we are interrupted */
536 static int list_len;
537 int count = 0;
538
539 if (!list) {
540 list_len = 32;
541 list = ckmalloc(list_len * sizeof *list);
542 }
543
544 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
545 for (vp = *vpp ; vp ; vp = vp->next) {
546 if (flag && !(vp->flags & flag))
547 continue;
548 if (vp->flags & VUNSET && !(show_value & 2))
549 continue;
550 if (count >= list_len) {
551 list = ckrealloc(list,
552 (list_len << 1) * sizeof *list);
553 list_len <<= 1;
554 }
555 list[count++] = vp;
556 }
557 }
558
559 qsort(list, count, sizeof *list, sort_var);
560
561 for (vpp = list; count--; vpp++) {
562 vp = *vpp;
563 if (name)
564 out1fmt("%s ", name);
565 for (p = vp->text ; *p != '=' ; p++)
566 out1c(*p);
567 if (!(vp->flags & VUNSET) && show_value) {
568 out1fmt("=");
569 print_quoted(++p);
570 }
571 out1c('\n');
572 }
573 return 0;
574 }
575
576
577
578 /*
579 * The export and readonly commands.
580 */
581
582 int
583 exportcmd(int argc, char **argv)
584 {
585 struct var **vpp;
586 struct var *vp;
587 char *name;
588 const char *p;
589 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
590 int pflag;
591
592 pflag = nextopt("p") == 'p' ? 3 : 0;
593 if (argc <= 1 || pflag) {
594 showvars( pflag ? argv[0] : 0, flag, pflag );
595 return 0;
596 }
597
598 while ((name = *argptr++) != NULL) {
599 if ((p = strchr(name, '=')) != NULL) {
600 p++;
601 } else {
602 vpp = hashvar(name);
603 for (vp = *vpp ; vp ; vp = vp->next) {
604 if (varequal(vp->text, name)) {
605 vp->flags |= flag;
606 goto found;
607 }
608 }
609 }
610 setvar(name, p, flag);
611 found:;
612 }
613 return 0;
614 }
615
616
617 /*
618 * The "local" command.
619 */
620
621 int
622 localcmd(int argc, char **argv)
623 {
624 char *name;
625
626 if (! in_function())
627 error("Not in a function");
628 while ((name = *argptr++) != NULL) {
629 mklocal(name, 0);
630 }
631 return 0;
632 }
633
634
635 /*
636 * Make a variable a local variable. When a variable is made local, it's
637 * value and flags are saved in a localvar structure. The saved values
638 * will be restored when the shell function returns. We handle the name
639 * "-" as a special case.
640 */
641
642 void
643 mklocal(const char *name, int flags)
644 {
645 struct localvar *lvp;
646 struct var **vpp;
647 struct var *vp;
648
649 INTOFF;
650 lvp = ckmalloc(sizeof (struct localvar));
651 if (name[0] == '-' && name[1] == '\0') {
652 char *p;
653 p = ckmalloc(sizeof_optlist);
654 lvp->text = memcpy(p, optlist, sizeof_optlist);
655 vp = NULL;
656 } else {
657 vpp = hashvar(name);
658 for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
659 if (vp == NULL) {
660 if (strchr(name, '='))
661 setvareq(savestr(name), VSTRFIXED|flags);
662 else
663 setvar(name, NULL, VSTRFIXED|flags);
664 vp = *vpp; /* the new variable */
665 lvp->text = NULL;
666 lvp->flags = VUNSET;
667 } else {
668 lvp->text = vp->text;
669 lvp->flags = vp->flags;
670 vp->flags |= VSTRFIXED|VTEXTFIXED;
671 if (strchr(name, '='))
672 setvareq(savestr(name), flags);
673 }
674 }
675 lvp->vp = vp;
676 lvp->next = localvars;
677 localvars = lvp;
678 INTON;
679 }
680
681
682 /*
683 * Called after a function returns.
684 */
685
686 void
687 poplocalvars(void)
688 {
689 struct localvar *lvp;
690 struct var *vp;
691
692 while ((lvp = localvars) != NULL) {
693 localvars = lvp->next;
694 vp = lvp->vp;
695 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
696 if (vp == NULL) { /* $- saved */
697 memcpy(optlist, lvp->text, sizeof_optlist);
698 ckfree(lvp->text);
699 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
700 (void)unsetvar(vp->text, 0);
701 } else {
702 if (vp->func && (vp->flags & VNOFUNC) == 0)
703 (*vp->func)(strchr(lvp->text, '=') + 1);
704 if ((vp->flags & VTEXTFIXED) == 0)
705 ckfree(vp->text);
706 vp->flags = lvp->flags;
707 vp->text = lvp->text;
708 }
709 ckfree(lvp);
710 }
711 }
712
713
714 int
715 setvarcmd(int argc, char **argv)
716 {
717 if (argc <= 2)
718 return unsetcmd(argc, argv);
719 else if (argc == 3)
720 setvar(argv[1], argv[2], 0);
721 else
722 error("List assignment not implemented");
723 return 0;
724 }
725
726
727 /*
728 * The unset builtin command. We unset the function before we unset the
729 * variable to allow a function to be unset when there is a readonly variable
730 * with the same name.
731 */
732
733 int
734 unsetcmd(int argc, char **argv)
735 {
736 char **ap;
737 int i;
738 int flg_func = 0;
739 int flg_var = 0;
740 int ret = 0;
741
742 while ((i = nextopt("evf")) != '\0') {
743 if (i == 'f')
744 flg_func = 1;
745 else
746 flg_var = i;
747 }
748 if (flg_func == 0 && flg_var == 0)
749 flg_var = 1;
750
751 for (ap = argptr; *ap ; ap++) {
752 if (flg_func)
753 ret |= unsetfunc(*ap);
754 if (flg_var)
755 ret |= unsetvar(*ap, flg_var == 'e');
756 }
757 return ret;
758 }
759
760
761 /*
762 * Unset the specified variable.
763 */
764
765 int
766 unsetvar(const char *s, int unexport)
767 {
768 struct var **vpp;
769 struct var *vp;
770
771 vpp = hashvar(s);
772 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
773 if (varequal(vp->text, s)) {
774 if (vp->flags & VREADONLY)
775 return (1);
776 INTOFF;
777 if (unexport) {
778 vp->flags &= ~VEXPORT;
779 } else {
780 if (*(strchr(vp->text, '=') + 1) != '\0')
781 setvar(s, nullstr, 0);
782 vp->flags &= ~VEXPORT;
783 vp->flags |= VUNSET;
784 if ((vp->flags & VSTRFIXED) == 0) {
785 if ((vp->flags & VTEXTFIXED) == 0)
786 ckfree(vp->text);
787 *vpp = vp->next;
788 ckfree(vp);
789 }
790 }
791 INTON;
792 return (0);
793 }
794 }
795
796 return (1);
797 }
798
799
800
801 /*
802 * Find the appropriate entry in the hash table from the name.
803 */
804
805 STATIC struct var **
806 hashvar(const char *p)
807 {
808 unsigned int hashval;
809
810 hashval = ((unsigned char) *p) << 4;
811 while (*p && *p != '=')
812 hashval += (unsigned char) *p++;
813 return &vartab[hashval % VTABSIZE];
814 }
815
816
817
818 /*
819 * Returns true if the two strings specify the same varable. The first
820 * variable name is terminated by '='; the second may be terminated by
821 * either '=' or '\0'.
822 */
823
824 STATIC int
825 varequal(const char *p, const char *q)
826 {
827 while (*p == *q++) {
828 if (*p++ == '=')
829 return 1;
830 }
831 if (*p == '=' && *(q - 1) == '\0')
832 return 1;
833 return 0;
834 }
835