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