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