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