var.c revision 1.73 1 /* $NetBSD: var.c,v 1.73 2018/12/12 07:56:57 kre 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.73 2018/12/12 07:56:57 kre Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <stdio.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <paths.h>
49 #include <limits.h>
50 #include <time.h>
51 #include <pwd.h>
52 #include <fcntl.h>
53 #include <inttypes.h>
54
55 /*
56 * Shell variables.
57 */
58
59 #include "shell.h"
60 #include "output.h"
61 #include "expand.h"
62 #include "nodes.h" /* for other headers */
63 #include "eval.h" /* defines cmdenviron */
64 #include "exec.h"
65 #include "syntax.h"
66 #include "options.h"
67 #include "builtins.h"
68 #include "mail.h"
69 #include "var.h"
70 #include "memalloc.h"
71 #include "error.h"
72 #include "mystring.h"
73 #include "parser.h"
74 #include "show.h"
75 #include "machdep.h"
76 #ifndef SMALL
77 #include "myhistedit.h"
78 #endif
79
80 #ifdef SMALL
81 #define VTABSIZE 39
82 #else
83 #define VTABSIZE 517
84 #endif
85
86
87 struct varinit {
88 struct var *var;
89 int flags;
90 const char *text;
91 union var_func_union v_u;
92 };
93 #define func v_u.set_func
94 #define rfunc v_u.ref_func
95
96 char *get_lineno(struct var *);
97
98 #ifndef SMALL
99 char *get_tod(struct var *);
100 char *get_hostname(struct var *);
101 char *get_seconds(struct var *);
102 char *get_euser(struct var *);
103 char *get_random(struct var *);
104 #endif
105
106 struct localvar *localvars;
107
108 #ifndef SMALL
109 struct var vhistsize;
110 struct var vterm;
111 struct var editrc;
112 struct var ps_lit;
113 #endif
114 struct var vifs;
115 struct var vmail;
116 struct var vmpath;
117 struct var vpath;
118 struct var vps1;
119 struct var vps2;
120 struct var vps4;
121 struct var vvers;
122 struct var voptind;
123 struct var line_num;
124 #ifndef SMALL
125 struct var tod;
126 struct var host_name;
127 struct var seconds;
128 struct var euname;
129 struct var random_num;
130
131 intmax_t sh_start_time;
132 #endif
133
134 struct var line_num;
135 int line_number;
136 int funclinebase = 0;
137 int funclineabs = 0;
138
139 char ifs_default[] = " \t\n";
140
141 const struct varinit varinit[] = {
142 #ifndef SMALL
143 { &vhistsize, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE=",
144 { .set_func= sethistsize } },
145 #endif
146 { &vifs, VSTRFIXED|VTEXTFIXED, "IFS= \t\n",
147 { NULL } },
148 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
149 { NULL } },
150 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
151 { NULL } },
152 { &vvers, VSTRFIXED|VTEXTFIXED|VNOEXPORT, "NETBSD_SHELL=",
153 { NULL } },
154 { &vpath, VSTRFIXED|VTEXTFIXED, "PATH=" _PATH_DEFPATH,
155 { .set_func= changepath } },
156 /*
157 * vps1 depends on uid
158 */
159 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
160 { NULL } },
161 { &vps4, VSTRFIXED|VTEXTFIXED, "PS4=+ ",
162 { NULL } },
163 #ifndef SMALL
164 { &vterm, VSTRFIXED|VTEXTFIXED|VUNSET, "TERM=",
165 { .set_func= setterm } },
166 { &editrc, VSTRFIXED|VTEXTFIXED|VUNSET, "EDITRC=",
167 { .set_func= set_editrc } },
168 { &ps_lit, VSTRFIXED|VTEXTFIXED|VUNSET, "PSlit=",
169 { .set_func= set_prompt_lit } },
170 #endif
171 { &voptind, VSTRFIXED|VTEXTFIXED|VNOFUNC, "OPTIND=1",
172 { .set_func= getoptsreset } },
173 { &line_num, VSTRFIXED|VTEXTFIXED|VFUNCREF|VSPECIAL, "LINENO=1",
174 { .ref_func= get_lineno } },
175 #ifndef SMALL
176 { &tod, VSTRFIXED|VTEXTFIXED|VFUNCREF, "ToD=",
177 { .ref_func= get_tod } },
178 { &host_name, VSTRFIXED|VTEXTFIXED|VFUNCREF, "HOSTNAME=",
179 { .ref_func= get_hostname } },
180 { &seconds, VSTRFIXED|VTEXTFIXED|VFUNCREF, "SECONDS=",
181 { .ref_func= get_seconds } },
182 { &euname, VSTRFIXED|VTEXTFIXED|VFUNCREF, "EUSER=",
183 { .ref_func= get_euser } },
184 { &random_num, VSTRFIXED|VTEXTFIXED|VFUNCREF|VSPECIAL, "RANDOM=",
185 { .ref_func= get_random } },
186 #endif
187 { NULL, 0, NULL,
188 { NULL } }
189 };
190
191 struct var *vartab[VTABSIZE];
192
193 STATIC int strequal(const char *, const char *);
194 STATIC struct var *find_var(const char *, struct var ***, int *);
195
196 /*
197 * Initialize the varable symbol tables and import the environment
198 */
199
200 #ifdef mkinit
201 INCLUDE <stdio.h>
202 INCLUDE <unistd.h>
203 INCLUDE <time.h>
204 INCLUDE "var.h"
205 INCLUDE "version.h"
206 MKINIT char **environ;
207 INIT {
208 char **envp;
209 char buf[64];
210
211 #ifndef SMALL
212 sh_start_time = (intmax_t)time((time_t *)0);
213 #endif
214 /*
215 * Set up our default variables and their values.
216 */
217 initvar();
218
219 /*
220 * Import variables from the environment, which will
221 * override anything initialised just previously.
222 */
223 for (envp = environ ; *envp ; envp++) {
224 if (strchr(*envp, '=')) {
225 setvareq(*envp, VEXPORT|VTEXTFIXED);
226 }
227 }
228
229 /*
230 * Set variables which override anything read from environment.
231 *
232 * PPID is readonly
233 * Always default IFS
234 * POSIX: "Whenever the shell is invoked, OPTIND shall
235 * be initialized to 1."
236 * PSc indicates the root/non-root status of this shell.
237 * START_TIME belongs only to this shell.
238 * NETBSD_SHELL is a constant (readonly), and is never exported
239 * LINENO is simply magic...
240 */
241 snprintf(buf, sizeof(buf), "%d", (int)getppid());
242 setvar("PPID", buf, VREADONLY);
243 setvar("IFS", ifs_default, VTEXTFIXED);
244 setvar("OPTIND", "1", VTEXTFIXED);
245 setvar("PSc", (geteuid() == 0 ? "#" : "$"), VTEXTFIXED);
246
247 #ifndef SMALL
248 snprintf(buf, sizeof(buf), "%jd", sh_start_time);
249 setvar("START_TIME", buf, VTEXTFIXED);
250 #endif
251
252 setvar("NETBSD_SHELL", NETBSD_SHELL
253 #ifdef BUILD_DATE
254 " BUILD:" BUILD_DATE
255 #endif
256 #ifdef DEBUG
257 " DEBUG"
258 #endif
259 #if !defined(JOBS) || JOBS == 0
260 " -JOBS"
261 #endif
262 #ifndef DO_SHAREDVFORK
263 " -VFORK"
264 #endif
265 #ifdef SMALL
266 " SMALL"
267 #endif
268 #ifdef TINY
269 " TINY"
270 #endif
271 #ifdef OLD_TTY_DRIVER
272 " OLD_TTY"
273 #endif
274 #ifdef SYSV
275 " SYSV"
276 #endif
277 #ifndef BSD
278 " -BSD"
279 #endif
280 #ifdef BOGUS_NOT_COMMAND
281 " BOGUS_NOT"
282 #endif
283 , VTEXTFIXED|VREADONLY|VNOEXPORT);
284
285 setvar("LINENO", "1", VTEXTFIXED);
286 }
287 #endif
288
289
290 /*
291 * This routine initializes the builtin variables. It is called when the
292 * shell is initialized and again when a shell procedure is spawned.
293 */
294
295 void
296 initvar(void)
297 {
298 const struct varinit *ip;
299 struct var *vp;
300 struct var **vpp;
301
302 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
303 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
304 continue;
305 vp->next = *vpp;
306 *vpp = vp;
307 vp->text = strdup(ip->text);
308 vp->flags = (ip->flags & ~VTEXTFIXED) | VSTRFIXED;
309 vp->v_u = ip->v_u;
310 }
311 /*
312 * PS1 depends on uid
313 */
314 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
315 vps1.next = *vpp;
316 *vpp = &vps1;
317 vps1.flags = VSTRFIXED;
318 vps1.text = NULL;
319 choose_ps1();
320 }
321 }
322
323 void
324 choose_ps1(void)
325 {
326 uid_t u = geteuid();
327
328 if ((vps1.flags & (VTEXTFIXED|VSTACK)) == 0)
329 free(vps1.text);
330 vps1.text = strdup(u != 0 ? "PS1=$ " : "PS1=# ");
331 vps1.flags &= ~(VTEXTFIXED|VSTACK);
332
333 /*
334 * Update PSc whenever we feel the need to update PS1
335 */
336 setvarsafe("PSc", (u == 0 ? "#" : "$"), 0);
337 }
338
339 /*
340 * Validate a string as a valid variable name
341 * nb: not parameter - special params and such are "invalid" here.
342 * Name terminated by either \0 or the term param (usually '=' or '\0').
343 *
344 * If not NULL, the length of the (intended) name is returned via len
345 */
346
347 int
348 validname(const char *name, int term, int *len)
349 {
350 const char *p = name;
351 int ok = 1;
352
353 if (p == NULL || *p == '\0' || *p == term) {
354 if (len != NULL)
355 *len = 0;
356 return 0;
357 }
358
359 if (!is_name(*p))
360 ok = 0;
361 p++;
362 for (;;) {
363 if (*p == '\0' || *p == term)
364 break;
365 if (!is_in_name(*p))
366 ok = 0;
367 p++;
368 }
369 if (len != NULL)
370 *len = p - name;
371
372 return ok;
373 }
374
375 /*
376 * Safe version of setvar, returns 1 on success 0 on failure.
377 */
378
379 int
380 setvarsafe(const char *name, const char *val, int flags)
381 {
382 struct jmploc jmploc;
383 struct jmploc * const savehandler = handler;
384 int volatile err = 0;
385
386 if (setjmp(jmploc.loc))
387 err = 1;
388 else {
389 handler = &jmploc;
390 setvar(name, val, flags);
391 }
392 handler = savehandler;
393 return err;
394 }
395
396 /*
397 * Set the value of a variable. The flags argument is ored with the
398 * flags of the variable. If val is NULL, the variable is unset.
399 *
400 * This always copies name and val when setting a variable, so
401 * the source strings can be from anywhere, and are no longer needed
402 * after this function returns. The VTEXTFIXED and VSTACK flags should
403 * not be used (but just in case they were, clear them.)
404 */
405
406 void
407 setvar(const char *name, const char *val, int flags)
408 {
409 const char *p;
410 const char *q;
411 char *d;
412 int len;
413 int namelen;
414 char *nameeq;
415
416 p = name;
417
418 if (!validname(p, '=', &namelen))
419 error("%.*s: bad variable name", namelen, name);
420 len = namelen + 2; /* 2 is space for '=' and '\0' */
421 if (val == NULL) {
422 flags |= VUNSET;
423 } else {
424 len += strlen(val);
425 }
426 d = nameeq = ckmalloc(len);
427 q = name;
428 while (--namelen >= 0)
429 *d++ = *q++;
430 *d++ = '=';
431 *d = '\0';
432 if (val)
433 scopy(val, d);
434 setvareq(nameeq, flags & ~(VTEXTFIXED | VSTACK));
435 }
436
437
438
439 /*
440 * Same as setvar except that the variable and value are passed in
441 * the first argument as name=value. Since the first argument will
442 * be actually stored in the table, it should not be a string that
443 * will go away. The flags (VTEXTFIXED or VSTACK) can be used to
444 * indicate the source of the string (if neither is set, the string will
445 * eventually be free()d when a replacement value is assigned.)
446 */
447
448 void
449 setvareq(char *s, int flags)
450 {
451 struct var *vp, **vpp;
452 int nlen;
453
454 VTRACE(DBG_VARS, ("setvareq([%s],%#x) aflag=%d ", s, flags, aflag));
455 if (aflag && !(flags & VNOEXPORT))
456 flags |= VEXPORT;
457 vp = find_var(s, &vpp, &nlen);
458 if (vp != NULL) {
459 VTRACE(DBG_VARS, ("was [%s] fl:%#x\n", vp->text,
460 vp->flags));
461 if (vp->flags & VREADONLY) {
462 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
463 ckfree(s);
464 if (flags & VNOERROR)
465 return;
466 error("%.*s: is read only", vp->name_len, vp->text);
467 }
468 if (flags & VNOSET) {
469 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
470 ckfree(s);
471 return;
472 }
473
474 INTOFF;
475
476 if (vp->func && !(vp->flags & VFUNCREF) && !(flags & VNOFUNC))
477 (*vp->func)(s + vp->name_len + 1);
478
479 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
480 ckfree(vp->text);
481
482 /*
483 * if we set a magic var, the magic dissipates,
484 * unless it is very special indeed.
485 */
486 if (vp->rfunc && (vp->flags & (VFUNCREF|VSPECIAL)) == VFUNCREF)
487 vp->rfunc = NULL;
488
489 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
490 if (flags & VNOEXPORT)
491 vp->flags &= ~VEXPORT;
492 if (flags & VDOEXPORT)
493 vp->flags &= ~VNOEXPORT;
494 if (vp->flags & VNOEXPORT)
495 flags &= ~VEXPORT;
496 vp->flags |= flags & ~(VNOFUNC | VDOEXPORT);
497 vp->text = s;
498
499 /*
500 * We could roll this to a function, to handle it as
501 * a regular variable function callback, but why bother?
502 */
503 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
504 chkmail(1);
505
506 INTON;
507 return;
508 }
509 /* not found */
510 if (flags & VNOSET) {
511 VTRACE(DBG_VARS, ("new noset\n"));
512 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
513 ckfree(s);
514 return;
515 }
516 vp = ckmalloc(sizeof (*vp));
517 vp->flags = flags & ~(VNOFUNC|VFUNCREF|VDOEXPORT);
518 vp->text = s;
519 vp->name_len = nlen;
520 vp->func = NULL;
521 vp->next = *vpp;
522 *vpp = vp;
523
524 VTRACE(DBG_VARS, ("new [%s] (%d) %#x\n", s, nlen, vp->flags));
525 }
526
527
528
529 /*
530 * Process a linked list of variable assignments.
531 */
532
533 void
534 listsetvar(struct strlist *list, int flags)
535 {
536 struct strlist *lp;
537
538 INTOFF;
539 for (lp = list ; lp ; lp = lp->next) {
540 setvareq(savestr(lp->text), flags);
541 }
542 INTON;
543 }
544
545 void
546 listmklocal(struct strlist *list, int flags)
547 {
548 struct strlist *lp;
549
550 for (lp = list ; lp ; lp = lp->next)
551 mklocal(lp->text, flags);
552 }
553
554
555 /*
556 * Find the value of a variable. Returns NULL if not set.
557 */
558
559 char *
560 lookupvar(const char *name)
561 {
562 struct var *v;
563
564 v = find_var(name, NULL, NULL);
565 if (v == NULL || v->flags & VUNSET)
566 return NULL;
567 if (v->rfunc && (v->flags & VFUNCREF) != 0)
568 return (*v->rfunc)(v) + v->name_len + 1;
569 return v->text + v->name_len + 1;
570 }
571
572
573
574 /*
575 * Search the environment of a builtin command. If the second argument
576 * is nonzero, return the value of a variable even if it hasn't been
577 * exported.
578 */
579
580 char *
581 bltinlookup(const char *name, int doall)
582 {
583 struct strlist *sp;
584 struct var *v;
585
586 for (sp = cmdenviron ; sp ; sp = sp->next) {
587 if (strequal(sp->text, name))
588 return strchr(sp->text, '=') + 1;
589 }
590
591 v = find_var(name, NULL, NULL);
592
593 if (v == NULL || v->flags & VUNSET || (!doall && !(v->flags & VEXPORT)))
594 return NULL;
595 if (v->rfunc && (v->flags & VFUNCREF) != 0)
596 return (*v->rfunc)(v) + v->name_len + 1;
597 return v->text + v->name_len + 1;
598 }
599
600
601
602 /*
603 * Generate a list of exported variables. This routine is used to construct
604 * the third argument to execve when executing a program.
605 */
606
607 char **
608 environment(void)
609 {
610 int nenv;
611 struct var **vpp;
612 struct var *vp;
613 char **env;
614 char **ep;
615
616 nenv = 0;
617 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
618 for (vp = *vpp ; vp ; vp = vp->next)
619 if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
620 nenv++;
621 }
622 CTRACE(DBG_VARS, ("environment: %d vars to export\n", nenv));
623 ep = env = stalloc((nenv + 1) * sizeof *env);
624 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
625 for (vp = *vpp ; vp ; vp = vp->next)
626 if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT) {
627 if (vp->rfunc && (vp->flags & VFUNCREF))
628 *ep++ = (*vp->rfunc)(vp);
629 else
630 *ep++ = vp->text;
631 VTRACE(DBG_VARS, ("environment: %s\n", ep[-1]));
632 }
633 }
634 *ep = NULL;
635 return env;
636 }
637
638
639 /*
640 * Called when a shell procedure is invoked to clear out nonexported
641 * variables. It is also necessary to reallocate variables of with
642 * VSTACK set since these are currently allocated on the stack.
643 */
644
645 #ifdef mkinit
646 void shprocvar(void);
647
648 SHELLPROC {
649 shprocvar();
650 }
651 #endif
652
653 void
654 shprocvar(void)
655 {
656 struct var **vpp;
657 struct var *vp, **prev;
658
659 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
660 for (prev = vpp ; (vp = *prev) != NULL ; ) {
661 if ((vp->flags & VEXPORT) == 0) {
662 *prev = vp->next;
663 if ((vp->flags & VTEXTFIXED) == 0)
664 ckfree(vp->text);
665 if ((vp->flags & VSTRFIXED) == 0)
666 ckfree(vp);
667 } else {
668 if (vp->flags & VSTACK) {
669 vp->text = savestr(vp->text);
670 vp->flags &=~ VSTACK;
671 }
672 prev = &vp->next;
673 }
674 }
675 }
676 initvar();
677 }
678
679
680
681 /*
682 * Command to list all variables which are set. Currently this command
683 * is invoked from the set command when the set command is called without
684 * any variables.
685 */
686
687 void
688 print_quoted(const char *p)
689 {
690 const char *q;
691
692 if (p[0] == '\0') {
693 out1fmt("''");
694 return;
695 }
696 if (strcspn(p, "|&;<>()$`\\\"' \t\n*?[]#~=%") == strlen(p)) {
697 out1fmt("%s", p);
698 return;
699 }
700 while (*p) {
701 if (*p == '\'') {
702 out1fmt("\\'");
703 p++;
704 continue;
705 }
706 q = strchr(p, '\'');
707 if (!q) {
708 out1fmt("'%s'", p );
709 return;
710 }
711 out1fmt("'%.*s'", (int)(q - p), p );
712 p = q;
713 }
714 }
715
716 static int
717 sort_var(const void *v_v1, const void *v_v2)
718 {
719 const struct var * const *v1 = v_v1;
720 const struct var * const *v2 = v_v2;
721 char *t1 = (*v1)->text, *t2 = (*v2)->text;
722
723 if (*t1 == *t2) {
724 char *p, *s;
725
726 STARTSTACKSTR(p);
727
728 /*
729 * note: if lengths are equal, strings must be different
730 * so we don't care which string we pick for the \0 in
731 * that case.
732 */
733 if ((strchr(t1, '=') - t1) <= (strchr(t2, '=') - t2)) {
734 s = t1;
735 t1 = p;
736 } else {
737 s = t2;
738 t2 = p;
739 }
740
741 while (*s && *s != '=') {
742 STPUTC(*s, p);
743 s++;
744 }
745 STPUTC('\0', p);
746 }
747
748 return strcoll(t1, t2);
749 }
750
751 /*
752 * POSIX requires that 'set' (but not export or readonly) output the
753 * variables in lexicographic order - by the locale's collating order (sigh).
754 * Maybe we could keep them in an ordered balanced binary tree
755 * instead of hashed lists.
756 * For now just roll 'em through qsort for printing...
757 */
758
759 int
760 showvars(const char *name, int flag, int show_value, const char *xtra)
761 {
762 struct var **vpp;
763 struct var *vp;
764 const char *p;
765
766 static struct var **list; /* static in case we are interrupted */
767 static int list_len;
768 int count = 0;
769
770 if (!list) {
771 list_len = 32;
772 list = ckmalloc(list_len * sizeof *list);
773 }
774
775 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
776 for (vp = *vpp ; vp ; vp = vp->next) {
777 if (flag && !(vp->flags & flag))
778 continue;
779 if (vp->flags & VUNSET && !(show_value & 2))
780 continue;
781 if (count >= list_len) {
782 list = ckrealloc(list,
783 (list_len << 1) * sizeof *list);
784 list_len <<= 1;
785 }
786 list[count++] = vp;
787 }
788 }
789
790 qsort(list, count, sizeof *list, sort_var);
791
792 for (vpp = list; count--; vpp++) {
793 vp = *vpp;
794 if (name)
795 out1fmt("%s ", name);
796 if (xtra)
797 out1fmt("%s ", xtra);
798 p = vp->text;
799 if (vp->rfunc && (vp->flags & VFUNCREF) != 0) {
800 p = (*vp->rfunc)(vp);
801 if (p == NULL)
802 p = vp->text;
803 }
804 for ( ; *p != '=' ; p++)
805 out1c(*p);
806 if (!(vp->flags & VUNSET) && show_value) {
807 out1fmt("=");
808 print_quoted(++p);
809 }
810 out1c('\n');
811 }
812 return 0;
813 }
814
815
816
817 /*
818 * The export and readonly commands.
819 */
820
821 int
822 exportcmd(int argc, char **argv)
823 {
824 struct var *vp;
825 char *name;
826 const char *p;
827 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
828 int pflg = 0;
829 int nflg = 0;
830 int xflg = 0;
831 int res;
832 int c;
833 int f;
834
835 while ((c = nextopt("npx")) != '\0') {
836 switch (c) {
837 case 'p':
838 if (nflg)
839 return 1;
840 pflg = 3;
841 break;
842 case 'n':
843 if (pflg || xflg || flag == VREADONLY)
844 return 1;
845 nflg = 1;
846 break;
847 case 'x':
848 if (nflg || flag == VREADONLY)
849 return 1;
850 flag = VNOEXPORT;
851 xflg = 1;
852 break;
853 default:
854 return 1;
855 }
856 }
857
858 if (nflg && *argptr == NULL)
859 return 1;
860
861 if (pflg || *argptr == NULL) {
862 showvars( pflg ? argv[0] : 0, flag, pflg,
863 pflg && xflg ? "-x" : NULL );
864 return 0;
865 }
866
867 res = 0;
868 while ((name = *argptr++) != NULL) {
869 int len;
870
871 f = flag;
872
873 vp = find_var(name, NULL, &len);
874 p = name + len;
875 if (*p++ != '=')
876 p = NULL;
877
878 if (vp != NULL) {
879 if (nflg)
880 vp->flags &= ~flag;
881 else if (flag&VEXPORT && vp->flags&VNOEXPORT) {
882 /* note we go ahead and do any assignment */
883 sh_warnx("%.*s: not available for export",
884 len, name);
885 res = 1;
886 } else {
887 if (flag == VNOEXPORT)
888 vp->flags &= ~VEXPORT;
889
890 /* if not NULL will be done in setvar below */
891 if (p == NULL)
892 vp->flags |= flag;
893 }
894 if (p == NULL)
895 continue;
896 }
897
898 if (!nflg || p != NULL)
899 setvar(name, p, f);
900 }
901 return res;
902 }
903
904
905 /*
906 * The "local" command.
907 */
908
909 int
910 localcmd(int argc, char **argv)
911 {
912 char *name;
913 int c;
914 int flags = 0; /*XXX perhaps VUNSET from a -o option value */
915
916 if (! in_function())
917 error("Not in a function");
918
919 /* upper case options, as bash stole all the good ones ... */
920 while ((c = nextopt("INx")) != '\0')
921 switch (c) {
922 case 'I': flags &= ~VUNSET; break;
923 case 'N': flags |= VUNSET; break;
924 case 'x': flags |= VEXPORT; break;
925 }
926
927 while ((name = *argptr++) != NULL) {
928 mklocal(name, flags);
929 }
930 return 0;
931 }
932
933
934 /*
935 * Make a variable a local variable. When a variable is made local, its
936 * value and flags are saved in a localvar structure. The saved values
937 * will be restored when the shell function returns. We handle the name
938 * "-" as a special case.
939 */
940
941 void
942 mklocal(const char *name, int flags)
943 {
944 struct localvar *lvp;
945 struct var **vpp;
946 struct var *vp;
947
948 INTOFF;
949 lvp = ckmalloc(sizeof (struct localvar));
950 if (name[0] == '-' && name[1] == '\0') {
951 char *p;
952 p = ckmalloc(sizeof_optlist);
953 lvp->text = memcpy(p, optlist, sizeof_optlist);
954 lvp->rfunc = NULL;
955 vp = NULL;
956 xtrace_clone(0);
957 } else {
958 vp = find_var(name, &vpp, NULL);
959 if (vp == NULL) {
960 flags &= ~VNOEXPORT;
961 if (strchr(name, '='))
962 setvareq(savestr(name),
963 VSTRFIXED | (flags & ~VUNSET));
964 else
965 setvar(name, NULL, VSTRFIXED|flags);
966 vp = *vpp; /* the new variable */
967 lvp->text = NULL;
968 lvp->flags = VUNSET;
969 lvp->rfunc = NULL;
970 } else {
971 lvp->text = vp->text;
972 lvp->flags = vp->flags;
973 lvp->v_u = vp->v_u;
974 vp->flags |= VSTRFIXED|VTEXTFIXED;
975 if (flags & (VDOEXPORT | VUNSET))
976 vp->flags &= ~VNOEXPORT;
977 if (vp->flags & VNOEXPORT &&
978 (flags & (VEXPORT|VDOEXPORT|VUNSET)) == VEXPORT)
979 flags &= ~VEXPORT;
980 if (flags & (VNOEXPORT | VUNSET))
981 vp->flags &= ~VEXPORT;
982 flags &= ~VNOEXPORT;
983 if (name[vp->name_len] == '=')
984 setvareq(savestr(name), flags & ~VUNSET);
985 else if (flags & VUNSET)
986 unsetvar(name, 0);
987 else
988 vp->flags |= flags & (VUNSET|VEXPORT);
989
990 if (vp == &line_num) {
991 if (name[vp->name_len] == '=')
992 funclinebase = funclineabs -1;
993 else
994 funclinebase = 0;
995 }
996 }
997 }
998 lvp->vp = vp;
999 lvp->next = localvars;
1000 localvars = lvp;
1001 INTON;
1002 }
1003
1004
1005 /*
1006 * Called after a function returns.
1007 */
1008
1009 void
1010 poplocalvars(void)
1011 {
1012 struct localvar *lvp;
1013 struct var *vp;
1014
1015 while ((lvp = localvars) != NULL) {
1016 localvars = lvp->next;
1017 vp = lvp->vp;
1018 VTRACE(DBG_VARS, ("poplocalvar %s\n", vp ? vp->text : "-"));
1019 if (vp == NULL) { /* $- saved */
1020 memcpy(optlist, lvp->text, sizeof_optlist);
1021 ckfree(lvp->text);
1022 xtrace_pop();
1023 optschanged();
1024 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
1025 (void)unsetvar(vp->text, 0);
1026 } else {
1027 if (lvp->func && (lvp->flags & (VNOFUNC|VFUNCREF)) == 0)
1028 (*lvp->func)(lvp->text + vp->name_len + 1);
1029 if ((vp->flags & VTEXTFIXED) == 0)
1030 ckfree(vp->text);
1031 vp->flags = lvp->flags;
1032 vp->text = lvp->text;
1033 vp->v_u = lvp->v_u;
1034 }
1035 ckfree(lvp);
1036 }
1037 }
1038
1039
1040 int
1041 setvarcmd(int argc, char **argv)
1042 {
1043 if (argc <= 2)
1044 return unsetcmd(argc, argv);
1045 else if (argc == 3)
1046 setvar(argv[1], argv[2], 0);
1047 else
1048 error("List assignment not implemented");
1049 return 0;
1050 }
1051
1052
1053 /*
1054 * The unset builtin command. We unset the function before we unset the
1055 * variable to allow a function to be unset when there is a readonly variable
1056 * with the same name.
1057 */
1058
1059 int
1060 unsetcmd(int argc, char **argv)
1061 {
1062 char **ap;
1063 int i;
1064 int flg_func = 0;
1065 int flg_var = 0;
1066 int flg_x = 0;
1067 int ret = 0;
1068
1069 while ((i = nextopt("efvx")) != '\0') {
1070 switch (i) {
1071 case 'f':
1072 flg_func = 1;
1073 break;
1074 case 'e':
1075 case 'x':
1076 flg_x = (2 >> (i == 'e'));
1077 /* FALLTHROUGH */
1078 case 'v':
1079 flg_var = 1;
1080 break;
1081 }
1082 }
1083
1084 if (flg_func == 0 && flg_var == 0)
1085 flg_var = 1;
1086
1087 for (ap = argptr; *ap ; ap++) {
1088 if (flg_func)
1089 ret |= unsetfunc(*ap);
1090 if (flg_var)
1091 ret |= unsetvar(*ap, flg_x);
1092 }
1093 return ret;
1094 }
1095
1096
1097 /*
1098 * Unset the specified variable.
1099 */
1100
1101 int
1102 unsetvar(const char *s, int unexport)
1103 {
1104 struct var **vpp;
1105 struct var *vp;
1106
1107 vp = find_var(s, &vpp, NULL);
1108 if (vp == NULL)
1109 return 0;
1110
1111 if (vp->flags & VREADONLY && !(unexport & 1))
1112 return 1;
1113
1114 INTOFF;
1115 if (unexport & 1) {
1116 vp->flags &= ~VEXPORT;
1117 } else {
1118 if (vp->text[vp->name_len + 1] != '\0')
1119 setvar(s, nullstr, 0);
1120 if (!(unexport & 2))
1121 vp->flags &= ~VEXPORT;
1122 vp->flags |= VUNSET;
1123 if ((vp->flags&(VEXPORT|VSTRFIXED|VREADONLY|VNOEXPORT)) == 0) {
1124 if ((vp->flags & VTEXTFIXED) == 0)
1125 ckfree(vp->text);
1126 *vpp = vp->next;
1127 ckfree(vp);
1128 }
1129 }
1130 INTON;
1131 return 0;
1132 }
1133
1134
1135 /*
1136 * Returns true if the two strings specify the same varable. The first
1137 * variable name is terminated by '='; the second may be terminated by
1138 * either '=' or '\0'.
1139 */
1140
1141 STATIC int
1142 strequal(const char *p, const char *q)
1143 {
1144 while (*p == *q++) {
1145 if (*p++ == '=')
1146 return 1;
1147 }
1148 if (*p == '=' && *(q - 1) == '\0')
1149 return 1;
1150 return 0;
1151 }
1152
1153 /*
1154 * Search for a variable.
1155 * 'name' may be terminated by '=' or a NUL.
1156 * vppp is set to the pointer to vp, or the list head if vp isn't found
1157 * lenp is set to the number of characters in 'name'
1158 */
1159
1160 STATIC struct var *
1161 find_var(const char *name, struct var ***vppp, int *lenp)
1162 {
1163 unsigned int hashval;
1164 int len;
1165 struct var *vp, **vpp;
1166 const char *p = name;
1167
1168 hashval = 0;
1169 while (*p && *p != '=')
1170 hashval = 2 * hashval + (unsigned char)*p++;
1171
1172 len = p - name;
1173 if (lenp)
1174 *lenp = len;
1175
1176 vpp = &vartab[hashval % VTABSIZE];
1177 if (vppp)
1178 *vppp = vpp;
1179
1180 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
1181 if (vp->name_len != len)
1182 continue;
1183 if (memcmp(vp->text, name, len) != 0)
1184 continue;
1185 if (vppp)
1186 *vppp = vpp;
1187 return vp;
1188 }
1189 return NULL;
1190 }
1191
1192 /*
1193 * The following are the functions that create the values for
1194 * shell variables that are dynamically produced when needed.
1195 *
1196 * The output strings cannot be malloc'd as there is nothing to
1197 * free them - callers assume these are ordinary variables where
1198 * the value returned is vp->text
1199 *
1200 * Each function needs its own storage space, as the results are
1201 * used to create processes' environment, and (if exported) all
1202 * the values will (might) be needed simultaneously.
1203 *
1204 * It is not a problem if a var is updated while nominally in use
1205 * somewhere, all these are intended to be dynamic, the value they
1206 * return is not guaranteed, an updated vaue is just as good.
1207 *
1208 * So, malloc a single buffer for the result of each function,
1209 * grow, and even shrink, it as needed, but once we have one that
1210 * is a suitable size for the actual usage, simply hold it forever.
1211 *
1212 * For a SMALL shell we implement only LINENO, none of the others,
1213 * and give it just a fixed length static buffer for its result.
1214 */
1215
1216 #ifndef SMALL
1217
1218 struct space_reserved { /* record of space allocated for results */
1219 char *b;
1220 int len;
1221 };
1222
1223 /* rough (over-)estimate of the number of bytes needed to hold a number */
1224 static int
1225 digits_in(intmax_t number)
1226 {
1227 int res = 0;
1228
1229 if (number & ~((1LL << 62) - 1))
1230 res = 64; /* enough for 2^200 and a bit more */
1231 else if (number & ~((1LL << 32) - 1))
1232 res = 20; /* enough for 2^64 */
1233 else if (number & ~((1 << 23) - 1))
1234 res = 10; /* enough for 2^32 */
1235 else
1236 res = 8; /* enough for 2^23 or smaller */
1237
1238 return res;
1239 }
1240
1241 static int
1242 make_space(struct space_reserved *m, int bytes)
1243 {
1244 void *p;
1245
1246 if (m->len >= bytes && m->len <= (bytes<<2))
1247 return 1;
1248
1249 bytes = SHELL_ALIGN(bytes);
1250 /* not ckrealloc() - we want failure, not error() here */
1251 p = realloc(m->b, bytes);
1252 if (p == NULL) /* what we had should still be there */
1253 return 0;
1254
1255 m->b = p;
1256 m->len = bytes;
1257 m->b[bytes - 1] = '\0';
1258
1259 return 1;
1260 }
1261 #endif
1262
1263 char *
1264 get_lineno(struct var *vp)
1265 {
1266 #ifdef SMALL
1267 #define length (8 + 10) /* 10 digits is enough for a 32 bit line num */
1268 static char result[length];
1269 #else
1270 static struct space_reserved buf;
1271 #define result buf.b
1272 #define length buf.len
1273 #endif
1274 int ln = line_number;
1275
1276 if (vp->flags & VUNSET)
1277 return NULL;
1278
1279 ln -= funclinebase;
1280
1281 #ifndef SMALL
1282 if (!make_space(&buf, vp->name_len + 2 + digits_in(ln)))
1283 return vp->text;
1284 #endif
1285
1286 snprintf(result, length - 1, "%.*s=%d", vp->name_len, vp->text, ln);
1287 return result;
1288 }
1289 #undef result
1290 #undef length
1291
1292 #ifndef SMALL
1293
1294 char *
1295 get_hostname(struct var *vp)
1296 {
1297 static struct space_reserved buf;
1298
1299 if (vp->flags & VUNSET)
1300 return NULL;
1301
1302 if (!make_space(&buf, vp->name_len + 2 + 256))
1303 return vp->text;
1304
1305 memcpy(buf.b, vp->text, vp->name_len + 1); /* include '=' */
1306 (void)gethostname(buf.b + vp->name_len + 1,
1307 buf.len - vp->name_len - 3);
1308 return buf.b;
1309 }
1310
1311 char *
1312 get_tod(struct var *vp)
1313 {
1314 static struct space_reserved buf; /* space for answers */
1315 static struct space_reserved tzs; /* remember TZ last used */
1316 static timezone_t last_zone; /* timezone data for tzs zone */
1317 const char *fmt;
1318 char *tz;
1319 time_t now;
1320 struct tm tm_now, *tmp;
1321 timezone_t zone = NULL;
1322 static char t_err[] = "time error";
1323 int len;
1324
1325 if (vp->flags & VUNSET)
1326 return NULL;
1327
1328 fmt = lookupvar("ToD_FORMAT");
1329 if (fmt == NULL)
1330 fmt="%T";
1331 tz = lookupvar("TZ");
1332 (void)time(&now);
1333
1334 if (tz != NULL) {
1335 if (tzs.b == NULL || strcmp(tzs.b, tz) != 0) {
1336 if (make_space(&tzs, strlen(tz) + 1)) {
1337 INTOFF;
1338 strcpy(tzs.b, tz);
1339 if (last_zone)
1340 tzfree(last_zone);
1341 last_zone = zone = tzalloc(tz);
1342 INTON;
1343 } else
1344 zone = tzalloc(tz);
1345 } else
1346 zone = last_zone;
1347
1348 tmp = localtime_rz(zone, &now, &tm_now);
1349 } else
1350 tmp = localtime_r(&now, &tm_now);
1351
1352 len = (strlen(fmt) * 4) + vp->name_len + 2;
1353 while (make_space(&buf, len)) {
1354 memcpy(buf.b, vp->text, vp->name_len+1);
1355 if (tmp == NULL) {
1356 if (buf.len >= vp->name_len+2+(int)(sizeof t_err - 1)) {
1357 strcpy(buf.b + vp->name_len + 1, t_err);
1358 if (zone && zone != last_zone)
1359 tzfree(zone);
1360 return buf.b;
1361 }
1362 len = vp->name_len + 4 + sizeof t_err - 1;
1363 continue;
1364 }
1365 if (strftime_z(zone, buf.b + vp->name_len + 1,
1366 buf.len - vp->name_len - 2, fmt, tmp)) {
1367 if (zone && zone != last_zone)
1368 tzfree(zone);
1369 return buf.b;
1370 }
1371 if (len >= 4096) /* Let's be reasonable */
1372 break;
1373 len <<= 1;
1374 }
1375 if (zone && zone != last_zone)
1376 tzfree(zone);
1377 return vp->text;
1378 }
1379
1380 char *
1381 get_seconds(struct var *vp)
1382 {
1383 static struct space_reserved buf;
1384 intmax_t secs;
1385
1386 if (vp->flags & VUNSET)
1387 return NULL;
1388
1389 secs = (intmax_t)time((time_t *)0) - sh_start_time;
1390 if (!make_space(&buf, vp->name_len + 2 + digits_in(secs)))
1391 return vp->text;
1392
1393 snprintf(buf.b, buf.len-1, "%.*s=%jd", vp->name_len, vp->text, secs);
1394 return buf.b;
1395 }
1396
1397 char *
1398 get_euser(struct var *vp)
1399 {
1400 static struct space_reserved buf;
1401 static uid_t lastuid = 0;
1402 uid_t euid;
1403 struct passwd *pw;
1404
1405 if (vp->flags & VUNSET)
1406 return NULL;
1407
1408 euid = geteuid();
1409 if (buf.b != NULL && lastuid == euid)
1410 return buf.b;
1411
1412 pw = getpwuid(euid);
1413 if (pw == NULL)
1414 return vp->text;
1415
1416 if (make_space(&buf, vp->name_len + 2 + strlen(pw->pw_name))) {
1417 lastuid = euid;
1418 snprintf(buf.b, buf.len, "%.*s=%s", vp->name_len, vp->text,
1419 pw->pw_name);
1420 return buf.b;
1421 }
1422
1423 return vp->text;
1424 }
1425
1426 char *
1427 get_random(struct var *vp)
1428 {
1429 static struct space_reserved buf;
1430 static intmax_t random_val = 0;
1431
1432 #ifdef USE_LRAND48
1433 #define random lrand48
1434 #define srandom srand48
1435 #endif
1436
1437 if (vp->flags & VUNSET)
1438 return NULL;
1439
1440 if (vp->text != buf.b) {
1441 /*
1442 * Either initialisation, or a new seed has been set
1443 */
1444 if (vp->text[vp->name_len + 1] == '\0') {
1445 int fd;
1446
1447 /*
1448 * initialisation (without pre-seeding),
1449 * or explictly requesting a truly random seed.
1450 */
1451 fd = open("/dev/urandom", 0);
1452 if (fd == -1) {
1453 out2str("RANDOM initialisation failed\n");
1454 random_val = (getpid()<<3) ^ time((time_t *)0);
1455 } else {
1456 int n;
1457
1458 do {
1459 n = read(fd,&random_val,sizeof random_val);
1460 } while (n != sizeof random_val);
1461 close(fd);
1462 }
1463 } else
1464 /* good enough for today */
1465 random_val = strtoimax(vp->text+vp->name_len+1,NULL,0);
1466
1467 srandom((long)random_val);
1468 }
1469
1470 #if 0
1471 random_val = (random_val + 1) & 0x7FFF; /* 15 bit "random" numbers */
1472 #else
1473 random_val = (random() >> 5) & 0x7FFF;
1474 #endif
1475
1476 if (!make_space(&buf, vp->name_len + 2 + digits_in(random_val)))
1477 return vp->text;
1478
1479 snprintf(buf.b, buf.len-1, "%.*s=%jd", vp->name_len, vp->text,
1480 random_val);
1481
1482 if (buf.b != vp->text && (vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1483 free(vp->text);
1484 vp->flags |= VTEXTFIXED;
1485 vp->text = buf.b;
1486
1487 return vp->text;
1488 #undef random
1489 #undef srandom
1490 }
1491
1492 #endif /* SMALL */
1493