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